IamLupo

Basic Upload

May 17th, 2016
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.57 KB | None | 0 0
  1. <html>
  2.     <body>
  3.         <form action="index.php" method="post" enctype="multipart/form-data">
  4.             Select image to upload:
  5.             <input type="file" name="upload" id="upload">
  6.             <input type="submit" value="Upload Image" name="submit">
  7.         </form>
  8.     </body>
  9. </html>
  10.  
  11. <?php
  12.  
  13. try {
  14.     //Settings
  15.     $target_dir = "uploads/";
  16.     $mimes = array("jpg", "png", "jpeg", "gif");
  17.  
  18.     //Generated variables
  19.     $file = $_FILES["upload"];
  20.     $file_name = basename($file["name"]);
  21.     $target_file = $target_dir . $file_name;
  22.    
  23.     if(isset($_POST["submit"])) {
  24.         $check = getimagesize($file["tmp_name"]);
  25.         $extension = pathinfo($target_file, PATHINFO_EXTENSION);
  26.        
  27.         if($check === false)
  28.             throw new Exception('FILE_NOT_IMAGE');
  29.        
  30.         // Check if file already exists
  31.         if(file_exists($target_file))
  32.             throw new Exception('FILE_EXIST');
  33.  
  34.         // Check file size
  35.         if($file["size"] > 5 * 1024 * 1024)
  36.             throw new Exception('FILE_LARGE');
  37.  
  38.         // Allow certain file formats
  39.         if(!in_array($extension, $mimes))
  40.             throw new Exception('FILE_EXTENSION_NOT_ALLOWED');
  41.        
  42.         // Check if $uploadOk is set to 0 by an error
  43.         if (move_uploaded_file($file["tmp_name"], $target_file))
  44.             echo "The file ". $file_name . " has been uploaded.";
  45.         else
  46.             throw new Exception('FILE_ERROR');
  47.     }
  48. } catch (Exception $e) {
  49.     if($e->getMessage() == 'FILE_NOT_IMAGE')
  50.         echo "Error: File is not a image.";
  51.     else if($e->getMessage() == 'FILE_EXIST')
  52.         echo "Error: File already exist.";
  53.     else if($e->getMessage() == 'FILE_EXTENSION_NOT_ALLOWED')
  54.         echo "Error: File extension not allowed.";
  55.     else
  56.         echo "Epic Fail!";
  57. }
  58.  
  59. ?>
Advertisement
Add Comment
Please, Sign In to add comment