Advertisement
Guest User

uploadimg.php

a guest
May 2nd, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. <form name="upload" action="uploadimg.php" method="POST" enctype="multipart/form-data">
  2. Select image to upload: <input type="file" name="image">
  3. <input type="submit" name="upload" value="upload">
  4. </form>
  5.  
  6. <?php
  7. if(!empty($_POST['upload']) && !empty($_FILES['image']) && $_FILES['image']['error'] == 0) {
  8.  
  9. $uploaddir = 'uploads/';
  10.  
  11. /* Generates random filename and extension */
  12. function tempnam_sfx($path, $suffix){
  13. do {
  14. $file = $path."/".mt_rand().$suffix;
  15. $fp = @fopen($file, 'x');
  16. }
  17. while(!$fp);
  18.  
  19. fclose($fp);
  20. return $file;
  21. }
  22.  
  23. /* Process image with GD library */
  24. $verifyimg = getimagesize($_FILES['image']['tmp_name']);
  25.  
  26. /* Make sure the MIME type is an image */
  27. $pattern = "#^(image/)[^\s\n<]+$#i";
  28.  
  29. if(!preg_match($pattern, $verifyimg['mime'])){
  30. die("Only image files are allowed!");
  31. }
  32.  
  33. /* Rename both the image and the extension */
  34. $uploadfile = tempnam_sfx($uploaddir, ".tmp");
  35.  
  36. /* Upload the file to a secure directory with the new name and extension */
  37. if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
  38.  
  39. /* Setup a database connection with PDO */
  40. $dbhost = "localhost";
  41. $dbuser = "";
  42. $dbpass = "";
  43. $dbname = "";
  44.  
  45. // Set DSN
  46. $dsn = 'mysql:host='.$dbhost.';dbname='.$dbname;
  47.  
  48. // Set options
  49. $options = array(
  50. PDO::ATTR_PERSISTENT => true,
  51. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  52. );
  53.  
  54. try {
  55. $db = new PDO($dsn, $dbuser, $dbpass, $options);
  56. }
  57. catch(PDOException $e){
  58. die("Error!: " . $e->getMessage());
  59. }
  60.  
  61. /* Setup query */
  62. $query = 'INSERT INTO uploads (name, original_name, mime_type) VALUES (:name, :oriname, :mime)';
  63.  
  64. /* Prepare query */
  65. $db->prepare($query);
  66.  
  67. /* Bind parameters */
  68. $db->bindParam(':name', basename($uploadfile));
  69. $db->bindParam(':oriname', basename($_FILES['image']['name']));
  70. $db->bindParam(':mime', $_FILES['image']['type']);
  71.  
  72. /* Execute query */
  73. try {
  74. $db->execute();
  75. }
  76. catch(PDOException $e){
  77. // Remove the uploaded file
  78. unlink($uploadfile);
  79.  
  80. die("Error!: " . $e->getMessage());
  81. }
  82. } else {
  83. die("Image upload failed!");
  84. }
  85. }
  86. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement