Guest User

File uploads

a guest
Jul 8th, 2013
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. /**
  4. */
  5.  
  6. /**
  7. * You can add more file inputs by just copying & pase line
  8. * <input name='p1' type='file' accept='<?= implode(',', $settings['ext']); ?>' />
  9. * remember about changing the field name eg. p2, p3, p4, ...
  10. */
  11.  
  12. /* ----------------------------------------------- */
  13. /* SETTINGS */
  14. /* ----------------------------------------------- */
  15.  
  16. $settings = array(
  17.     //Maximum file size defined in Bytes. However it depends on what values are set for directives in php.ini: upload_max_filesize, post_max_size and memory_limit
  18.     'file_maxsize'  => 5000000,
  19.    
  20.     // Accepted extensions
  21.     'ext'           => array(
  22.         'image/gif'
  23.     ),
  24.    
  25.     // Directory where files should be placed. Note this is relative path, so folder images/ will be serached in the same location as script execution
  26.     'dir'           => 'images/',
  27.    
  28.     'handleUps'             => true, // Upload enabled/disabled -> options: true/false
  29.     'createDirIfNoExist'    => true, // Create output directory (specified at 'dir') when doesn't exist. Options true/false
  30.     'allowNoFile'           => false // Allow to execute script if no file has been selected for at least one file field. Options true/false
  31. );
  32.  
  33. /* ----------------------------------------------- */
  34. /* NO MORE FURTHER EDITING NEEDED */
  35. /* ----------------------------------------------- */
  36.  
  37. try
  38. {
  39.     // Check if file handling on and ifdata has been sent
  40.     if ($settings['handleUps'] && array_key_exists('send', $_POST))
  41.     {
  42.         // yes - proceed
  43.         $errors = array();
  44.        
  45.         // Check if files has been sent without any problems
  46.         foreach ($_FILES as $fieldname => $fileprop)
  47.         {
  48.             // Check file error
  49.             if ($fileprop != UPLOAD_ERR_OK)
  50.             {
  51.                 switch ($fileprop['error'])
  52.                 {
  53.                     case UPLOAD_ERR_INI_SIZE:
  54.                     case UPLOAD_ERR_FORM_SIZE:
  55.                         $errors[] = 'File '.$fileprop['name'].' is too big (maximum size is '.sizeFormat($settings['file_maxsize'], 'MB').')';
  56.                     break;
  57.                     case UPLOAD_ERR_PARTIAL:
  58.                     case UPLOAD_ERR_NO_TMP_DIR:
  59.                     case UPLOAD_ERR_CANT_WRITE:
  60.                         $errors[] = 'File '.$fileprop['name'].' wasn\'t succesfully uploaded.';
  61.                     break;
  62.                     case UPLOAD_ERR_NO_FILE:
  63.                         if (!$settings['allowNoFile'])
  64.                         {
  65.                             $errors[] = 'No file has been selected at field '.$fieldname.'.';
  66.                         }
  67.                     break;
  68.                     case UPLOAD_ERR_EXTENSION:
  69.                         $errors[] = 'File '.$fileprop['name'].' extension is not correct.';
  70.                     break;
  71.                 }
  72.             }
  73.         }
  74.        
  75.         // If there are errors -> do not proceed
  76.         if (!empty($errors))
  77.         {
  78.             throw new Exception(implode('<br />', $errors));
  79.         }
  80.        
  81.         // Create target directory if not exists and if script allowed to
  82.         if (!file_exists($settings['dir']))
  83.         {
  84.             if (!$settings['createDirIfNoExist'])
  85.             {
  86.                 throw new Exception('Target directory does not exists.');
  87.             }
  88.            
  89.             if (!mkdir($settings['dir'], 0777))
  90.             {
  91.                 throw new Exception('Target directory error.');
  92.             }
  93.         }
  94.        
  95.         // Continue with checking size, veryfing extensions and moving files to te proper directory
  96.         $filesExt = array();
  97.        
  98.         foreach ($_FILES as $filename => $fileprop)
  99.         {  
  100.             try
  101.             {
  102.                 // If file is uploaded one
  103.                 if (!is_uploaded_file($fileprop['tmp_name']))
  104.                 {              
  105.                     throw new Exception('There was a problem with handling '.$fileprop['name'].' file.');
  106.                 }
  107.                
  108.                 // Filesize
  109.                 if ($fileprop['size'] > $settings['file_maxsize'])
  110.                 {                
  111.                     throw new Exception('File '.$fileprop['name'].' is too big (maximum size is '.sizeFormat($settings['file_maxsize']).').');
  112.                 }
  113.                
  114.                 // Check claimed extension
  115.                 if (!in_array($fileprop['type'], $settings['ext']))
  116.                 {
  117.                     throw new Exception('File '.$fileprop['name'].' has inapropriate extension.');
  118.                 }
  119.                
  120.                 // Verify extension
  121.                 if (class_exists('finfo') && floatval(phpversion()) >= 5.3)
  122.                 {
  123.                     $finfo = finfo_open(FILEINFO_MIME_TYPE);
  124.                     $type = finfo_file($finfo, $fileprop['tmp_name']);
  125.                 }
  126.                 else if (function_exists('exif_imagetype'))
  127.                 {                  
  128.                     $type = exif_imagetype($fileprop['tmp_name']);
  129.                 }
  130.                 else
  131.                 {    
  132.                     $type = $fileprop['type'];
  133.                 }
  134.                
  135.                 if (!in_array($type, $settings['ext']))
  136.                 {              
  137.                     throw new Exception('File '.$fileprop['name'].' has inappropriate extension.');
  138.                 }
  139.                
  140.                 // Save ext
  141.                 $filesExt[$filename] = end(explode('/', $type));
  142.             }
  143.             catch (Exception $ex)
  144.             {
  145.                 $errors[] = $ex->getMessage();
  146.             }
  147.         }
  148.        
  149.         // Save files only if there are no errors
  150.         if (!empty($errors))
  151.         {
  152.             throw new Exception(implode('<br />', $errors));
  153.         }
  154.        
  155.         foreach ($_FILES as $filename => $fileprop)
  156.         {
  157.             // Move uploaded file
  158.             if (!move_uploaded_file($fileprop['tmp_name'], $settings['dir'].time().'.'.$filesExt[$filename]))
  159.             {
  160.                 throw new Exception('File '.$fileprop['name'].' couldn\'t be saved.');
  161.             }
  162.         }
  163.     }
  164. }
  165. catch (Exception $ex)
  166. {
  167.     echo '<div style=\'border: 1px solid red; background-color: rgba(255, 0, 0, 0.1); color: red; padding: 15px; text-align: center;\'>'.$ex->getMessage().'</div>';
  168. }
  169.  
  170. function sizeFormat($size, $format)
  171. {
  172.     switch ($format)
  173.     {
  174.         case 'GB': $size /= 1000;
  175.         case 'MB': $size /= 1000;
  176.         case 'KB': $size /= 1000;
  177.     }
  178.    
  179.     return $size.' '.$format;
  180. }
  181.  
  182. ?>
  183.  
  184. <form method='post' enctype='multipart/form-data'>
  185.     <input name='MAX_FILE_SIZE' type='hidden' value='<?= $settings['file_maxsize']; ?>' />
  186.     <input name='p1' type='file' accept='<?= implode(',', $settings['ext']); ?>' />
  187.     <input name='send' type='submit' value='Send' />
  188. </form>
Advertisement
Add Comment
Please, Sign In to add comment