Advertisement
ptamzz

PHP upload class

Feb 2nd, 2012
645
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.19 KB | None | 0 0
  1. <?php
  2. /*
  3. Easy PHP Upload - version 2.33
  4. A easy to use class for your (multiple) file uploads
  5.  
  6. Copyright (c) 2004 - 2011, Olaf Lederer
  7. All rights reserved.
  8.  
  9. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  10.  
  11.     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  12.     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  13.     * Neither the name of the finalwebsites.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  14.  
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16.  
  17. _________________________________________________________________________
  18. available at http://www.finalwebsites.com/snippets.php?id=7
  19. Comments & suggestions: http://www.finalwebsites.com/blog/submit-a-question/
  20.  
  21. *************************************************************************/
  22.  
  23. class file_upload {
  24.  
  25.     var $the_file;
  26.     var $the_temp_file;
  27.     var $the_mime_type; // new in 2.33
  28.     var $upload_dir;
  29.     var $replace;
  30.     var $do_filename_check;
  31.     var $max_length_filename = 100;
  32.     var $extensions;
  33.     var $valid_mime_types = array('.bmp'=>'image/bmp', '.gif'=>'image/gif', '.jpg'=>'image/jpeg', '.jpeg'=>'image/jpeg', '.pdf'=>'application/pdf', '.png'=>'image/png', '.zip'=>'application/zip'); // new in 2.33 (search google for a complete list)
  34.     var $ext_string;
  35.     var $language;
  36.     var $http_error;
  37.     var $rename_file; // if this var is true the file copy get a new name
  38.     var $file_copy; // the new name
  39.     var $message = array();
  40.     var $create_directory = true;
  41.     /*
  42.     ver. 2.32
  43.     Added vars for file and directory permissions, check also the methods move_upload() and check_dir().
  44.     */
  45.     var $fileperm = 0644;
  46.     var $dirperm = 0755;
  47.    
  48.     function file_upload() {
  49.         $this->language = 'en'; // choice of en, nl, es
  50.         $this->rename_file = false;
  51.         $this->ext_string = '';
  52.     }
  53.     function show_error_string($br = '<br />') {
  54.         $msg_string = '';
  55.         foreach ($this->message as $value) {
  56.             $msg_string .= $value.$br;
  57.         }
  58.         return $msg_string;
  59.     }
  60.     function set_file_name($new_name = '') { // this 'conversion' is used for unique/new filenames
  61.         if ($this->rename_file) {
  62.             if ($this->the_file == '') return;
  63.             $name = ($new_name == '') ? strtotime('now') : $new_name;
  64.             sleep(3);
  65.             $name = $name.$this->get_extension($this->the_file);
  66.         } else {
  67.             $name = str_replace(' ', '_', $this->the_file); // space will result in problems on linux systems
  68.         }
  69.         return $name;
  70.     }
  71.     function upload($to_name = '') {
  72.         $new_name = $this->set_file_name($to_name);
  73.         if ($this->check_file_name($new_name)) {
  74.             if ($this->validateExtension()) {
  75.                 if (is_uploaded_file($this->the_temp_file)) {
  76.                     $this->file_copy = $new_name;
  77.                     if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
  78.                         $this->message[] = $this->error_text($this->http_error);
  79.                         if ($this->rename_file) $this->message[] = $this->error_text(16);
  80.                         return true;
  81.                     }
  82.                 } else {
  83.                     $this->message[] = $this->error_text($this->http_error);
  84.                     return false;
  85.                 }
  86.             } else {
  87.                 $this->show_extensions();
  88.                 $this->message[] = $this->error_text(11);
  89.                 return false;
  90.             }
  91.         } else {
  92.             return false;
  93.         }
  94.     }
  95.     function check_file_name($the_name) {
  96.         if ($the_name != '') {
  97.             if (strlen($the_name) > $this->max_length_filename) {
  98.                 $this->message[] = $this->error_text(13);
  99.                 return false;
  100.             } else {
  101.                 if ($this->do_filename_check == 'y') {
  102.                     if (preg_match('/^[a-z0-9_]*\.(.){1,5}$/i', $the_name)) {
  103.                         return true;
  104.                     } else {
  105.                         $this->message[] = $this->error_text(12);
  106.                         return false;
  107.                     }
  108.                 } else {
  109.                     return true;
  110.                 }
  111.             }
  112.         } else {
  113.             $this->message[] = $this->error_text(10);
  114.             return false;
  115.         }
  116.     }
  117.     function get_extension($from_file) {
  118.         $ext = strtolower(strrchr($from_file,'.'));
  119.         return $ext;
  120.     }
  121.     /* New in version 2.33 */
  122.     function validateMimeType() {
  123.         $ext = $this->get_extension($this->the_file);
  124.         if ($this->the_mime_type == $this->valid_mime_types[$ext]) {
  125.             return true;
  126.         } else {
  127.             $this->message[] = $this->error_text(18);
  128.             return false;
  129.         }
  130.     }
  131.     /* Added here the mime check in ver. 2.33 */
  132.     function validateExtension() {
  133.         $extension = $this->get_extension($this->the_file);
  134.         $ext_array = $this->extensions;
  135.         if (in_array($extension, $ext_array)) {
  136.             if (!empty($this->the_mime_type)) {
  137.                 if ($this->validateMimeType()) {
  138.                     return true;
  139.                 } else {
  140.                     return false;
  141.                 }
  142.             } else {
  143.                 return true;
  144.             }
  145.         } else {
  146.             return false;
  147.         }
  148.     }
  149.     // this method is only used for detailed error reporting
  150.     function show_extensions() {
  151.         $this->ext_string = implode(' ', $this->extensions);
  152.     }
  153.     function move_upload($tmp_file, $new_file) {
  154.         if ($this->existing_file($new_file)) {
  155.             $newfile = $this->upload_dir.$new_file;
  156.             if ($this->check_dir($this->upload_dir)) {
  157.                 if (move_uploaded_file($tmp_file, $newfile)) {
  158.                     umask(0);
  159.                     chmod($newfile , $this->fileperm);
  160.                     return true;
  161.                 } else {
  162.                     return false;
  163.                 }
  164.             } else {
  165.                 $this->message[] = $this->error_text(14);
  166.                 return false;
  167.             }
  168.         } else {
  169.             $this->message[] = $this->error_text(15);
  170.             return false;
  171.         }
  172.     }
  173.     function check_dir($directory) {
  174.         if (!is_dir($directory)) {
  175.             if ($this->create_directory) {
  176.                 umask(0);
  177.                 mkdir($directory, $this->dirperm);
  178.                 return true;
  179.             } else {
  180.                 return false;
  181.             }
  182.         } else {
  183.             return true;
  184.         }
  185.     }
  186.     function existing_file($file_name) {
  187.         if ($this->replace == 'y') {
  188.             return true;
  189.         } else {
  190.             if (file_exists($this->upload_dir.$file_name)) {
  191.                 return false;
  192.             } else {
  193.                 return true;
  194.             }
  195.         }
  196.     }
  197.     /*
  198.     ver. 2.32
  199.     Method get_uploaded_file_info(): Replaced old \n line-ends with the PHP constant variable PHP_EOL
  200.     */
  201.     function get_uploaded_file_info($name) {
  202.         $str = 'File name: '.basename($name).PHP_EOL;
  203.         $str .= 'File size: '.filesize($name).' bytes'.PHP_EOL;
  204.         if (function_exists('mime_content_type')) {
  205.             $str .= 'Mime type: '.mime_content_type($name).PHP_EOL;
  206.         }
  207.         if ($img_dim = getimagesize($name)) {
  208.             $str .= 'Image dimensions: x = '.$img_dim[0].'px, y = '.$img_dim[1].'px'.PHP_EOL;
  209.         }
  210.         return $str;
  211.     }
  212.     // this method was first located inside the foto_upload extension
  213.     function del_temp_file($file) {
  214.         $delete = @unlink($file);
  215.         clearstatcache();
  216.         if (@file_exists($file)) {
  217.             $filesys = eregi_replace('/','\\',$file);
  218.             $delete = @system('del $filesys');
  219.             clearstatcache();
  220.             if (@file_exists($file)) {
  221.                 $delete = @chmod ($file, 0644);
  222.                 $delete = @unlink($file);
  223.                 $delete = @system('del $filesys');
  224.             }
  225.         }
  226.     }
  227.     // this function creates a file field and if $show_alternate is true it will show a text field if the given file already exists
  228.     // there is also a submit button to remove the text field value
  229.     /*
  230.     ver. 2.32
  231.     Method create_file_field(): Minor code clean up (better code formatting and replaced double with single quotes)
  232.     */
  233.     function create_file_field($element, $label = '', $length = 25, $show_replace = true, $replace_label = 'Replace old file?', $file_path = '', $file_name = '', $show_alternate = false, $alt_length = 30, $alt_btn_label = 'Delete image') {
  234.         $field = '';
  235.         if ($label != '') $field = '
  236.             <label>'.$label.'</label>';
  237.         $field = '
  238.             <input type="file" name="'.$element.'" size="'.$length.'" />';
  239.         if ($show_replace) $field .= '
  240.             <span>'.$replace_label.'</span>
  241.             <input type="checkbox" name="replace" value="y" />';
  242.         if ($file_name != '' && $show_alternate) {
  243.             $field .= '
  244.             <input type="text" name="'.$element.'" size="'.$alt_length.'" value="'.$file_name.'" readonly="readonly"';
  245.             $field .= (!@file_exists($file_path.$file_name)) ? ' title="'.sprintf($this->error_text(17), $file_name).'" />' : ' />';
  246.             $field .= '
  247.             <input type="checkbox" name="del_img" value="y" />
  248.             <span>'.$alt_btn_label.'</span>';
  249.         }
  250.         return $field;
  251.     }
  252.     // some error (HTTP)reporting, change the messages or remove options if you like.
  253.     /* ver 2.32
  254.     Method error_text(): Older Dutch language messages are re-written, thanks Julian A. de Marchi. Added HTTP error messages (error 6-7 introduced with newer PHP versions, error no. 5 doesn't exists)
  255.     */
  256.     function error_text($err_num) {
  257.         switch ($this->language) {
  258.             case 'nl': 
  259.             $error[0] = 'Bestand <b>'.$this->the_file.'</b> staat nu op de server.';
  260.             $error[1] = 'Dit bestand is groter dan de toegestaane upload bestandgrootte in de server configuratie.';
  261.             $error[2] = 'Dit bestand is groter dan de MAX_FILE_SIZE parameter welke in de html formulier werdt gespecificiëerd.';
  262.             $error[3] = 'De upload is helaas mislukt.  Slechts een deel van het bestand is bij de server aangekomen.  Probeer het opnieuw.';
  263.             $error[4] = 'De upload is helaas mislukt.  Geen betrouwbare verbinding met de server kwam tot stand.  Probeer het opnieuw.';
  264.             $error[6] = 'De map voor tijdelijke opslag ontbreekt. ';
  265.             $error[7] = 'Het schrijven op de server is mislukt. ';
  266.             $error[8] = 'Een PHP extensie is gestopt tijdens het uploaden. ';
  267.             // end  http errors
  268.             $error[10] = 'Selecteer een bestand om te uploaden.';
  269.             $error[11] = 'Uitsluitend bestanden van de volgende types zijn toegestaan: <b>'.$this->ext_string.'</b>';
  270.             $error[12] = 'Helaas heeft het gekozen bestand karakters die niet zijn toegestaan. Gebruik uitsluitend cijfers, letters, en onderstrepen. <br>Een geldige naam eindigt met een punt met daarop volgend het extensietype.';
  271.             $error[13] = 'De bestandsnaam is echter te lang, en mag een maximum van '.$this->max_length_filename.' tekens bevatten.';
  272.             $error[14] = 'De gekozen map werdt niet gevonden.';
  273.             $error[15] = 'Een bestand met dezelfde naam ('.$this->the_file.') bestaat al op de server.  Probeer opnieuw met een andere naam.';
  274.             $error[16] = 'Op de server werdt het bestand hernoemd tot <b>'.$this->file_copy.'</b>.';
  275.             $error[17] = 'Het bestand %s bestaat niet.';
  276.             $error[18] = 'De soort bestand (mime type) is niet toegestaan.'; // new ver. 2.33
  277.             break;
  278.             case 'de':
  279.             $error[0] = 'Die Datei: <b>'.$this->the_file.'</b> wurde hochgeladen!';
  280.             $error[1] = 'Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Server-Konfiguration!';
  281.             $error[2] = 'Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Klassen-Konfiguration!';
  282.             $error[3] = 'Die hochzuladende Datei wurde nur teilweise &uuml;bertragen';
  283.             $error[4] = 'Es wurde keine Datei hochgeladen';
  284.             $error[6] = 'Der tempor&auml;re Dateiordner fehlt';
  285.             $error[7] = 'Das Schreiben der Datei auf der Festplatte war nicht m&ouml;glich.';
  286.             $error[8] = 'Eine PHP Erweiterung hat w&auml;hrend dem hochladen aufgeh&ouml;rt zu arbeiten. ';
  287.            
  288.             $error[10] = 'W&auml;hlen Sie eine Datei aus!.';
  289.             $error[11] = 'Es sind nur Dateien mit folgenden Endungen erlaubt: <b>'.$this->ext_string.'</b>';
  290.             $error[12] = 'Der Dateiname enth&auml;lt ung&uuml;ltige Zeichen. Benutzen Sie nur alphanumerische Zeichen f&uuml;r den Dateinamen mit Unterstrich. <br>Ein g&uuml;ltiger Dateiname endet mit einem Punkt, gefolgt von der Endung.';
  291.             $error[13] = 'Der Dateiname &uuml;berschreitet die maximale Anzahl von '.$this->max_length_filename.' Zeichen.';
  292.             $error[14] = 'Das Upload-Verzeichnis existiert nicht!';
  293.             $error[15] = 'Upload <b>'.$this->the_file.'...Fehler!</b> Eine Datei mit gleichem Dateinamen existiert bereits.';
  294.             $error[16] = 'Die hochgeladene Datei ist umbenannt in <b>'.$this->file_copy.'</b>.';
  295.             $error[17] = 'Die Datei %s existiert nicht.';
  296.             $error[18] = 'Der Datei Typ (mime type) ist nicht erlaubt.'; // new ver. 2.33
  297.             break;
  298.             //
  299.             // place here the translations (if you need) from the directory 'add_translations'
  300.             //
  301.             default:
  302.             // start http errors
  303.             $error[0] = 'File: <b>'.$this->the_file.'</b> successfully uploaded!';
  304.             $error[1] = 'The uploaded file exceeds the max. upload filesize directive in the server configuration.';
  305.             $error[2] = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.';
  306.             $error[3] = 'The uploaded file was only partially uploaded';
  307.             $error[4] = 'No file was uploaded';
  308.             $error[6] = 'Missing a temporary folder. ';
  309.             $error[7] = 'Failed to write file to disk. ';
  310.             $error[8] = 'A PHP extension stopped the file upload. ';
  311.            
  312.             // end  http errors
  313.             $error[10] = 'Please select a file for upload.';
  314.             $error[11] = 'Only files with the following extensions are allowed: <b>'.$this->ext_string.'</b>';
  315.             $error[12] = 'Sorry, the filename contains invalid characters. Use only alphanumerical chars and separate parts of the name (if needed) with an underscore. <br>A valid filename ends with one dot followed by the extension.';
  316.             $error[13] = 'The filename exceeds the maximum length of '.$this->max_length_filename.' characters.';
  317.             $error[14] = 'Sorry, the upload directory does not exist!';
  318.             $error[15] = 'Uploading <b>'.$this->the_file.'...Error!</b> Sorry, a file with this name already exitst.';
  319.             $error[16] = 'The uploaded file is renamed to <b>'.$this->file_copy.'</b>.';
  320.             $error[17] = 'The file %s does not exist.';
  321.             $error[18] = 'The file type (mime type) is not valid.'; // new ver. 2.33
  322.         }
  323.         return $error[$err_num];
  324.     }
  325. }
  326. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement