Uploading files with PHP

If you are new to PHP or web programming in general, ever wonder how to upload files to your server?

You do wonder?

...word?

Well here is an example of how to do so.

If you want to follow this code along with you actually programming first do this. Create a folder called "uploads" on your server so that when following this tutorial you will have a directory your files will upload to.

First as how I roll, I'll throw the entire code at your brain.

upload.php

  1. <?php
  2. //tutorial - file uploader
  3.  
  4. //ok we start by setting the allowed file types to be uploaded
  5. //lets do... txt and a few image files by listing them by mime type
  6. $allowed_types = array('text/plain', 'image/jpeg', 'image/gif', 'image/png');
  7.  
  8. //now we specify what upload directory we want our files to upload to
  9. $upload_dir = 'uploads/';
  10.  
  11. //now we can make a function that parses through the file string and gets rid of special characters
  12. function string_clean($str) {
  13.         $new_str = str_replace(" ", "-", $str);
  14.         $new_str = str_replace("//", "", $new_str);
  15.         $new_str = str_replace("/", "", $new_str);
  16.         $new_str = str_replace(":", "", $new_str);
  17.         $new_str = str_replace("*", "", $new_str);
  18.         $new_str = str_replace("?", "", $new_str);
  19.         $new_str = str_replace("<", "", $new_str);
  20.         $new_str = str_replace(">", "", $new_str);
  21.         $new_str = str_replace("|", "", $new_str);
  22.         $new_str = str_replace("'", "", $new_str);
  23.         $new_str = str_replace("\"", "", $new_str);
  24.         $new_str = str_replace("\\", "", $new_str);
  25.        
  26.         return $new_str;
  27. }
  28.  
  29. //create the upload form
  30. function upload_form($errors = array()) {
  31.         if (sizeof($errors) > 0) {
  32.                 foreach ($errors as $error) {
  33.                         print $error . '<br />';
  34.                 }
  35.         }
  36.        
  37.         print '<form action = "'.$_SERVER['PHP_SELF'].'" method = "post" enctype = "multipart/form-data">
  38.         <table border = "0">
  39.                 <tr>
  40.                         <td>Upload File:</td>
  41.                         <td><input type = "file" name = "file" size = "40" /></td>
  42.                 </tr>
  43.                 <tr>
  44.                         <td></td>
  45.                         <td><input type = "submit" name = "submit" value = "Upload" /></td>
  46.                 </tr>
  47.         </table>
  48.         </form>';
  49. }
  50.  
  51. //make a function that processes the actual upload
  52. function process_upload($tmp_name, $filename, $upload_dir) {
  53.         //clean the file of special characters
  54.         $clean_filename = string_clean($filename);
  55.         //concat the upload directory to the cleaned filename
  56.         $upload_filename = $upload_dir . $clean_filename;
  57.        
  58.         //now upload this biatch!!!!
  59.         if (move_uploaded_file($tmp_name, $upload_filename)) {
  60.                 print 'Upload Successful! <a href = "'.$_SERVER['PHP_SELF'].'">Back to form</a>';
  61.         } else {
  62.                 print 'Upload Failed!';
  63.         }
  64.        
  65.         //display the contents of the upload directory anyways
  66.         list_uploads($upload_dir);
  67. }
  68.  
  69. //make a function the lists all files in the upload directory
  70. function list_uploads($dir) {
  71.         $listed_dir = opendir($dir);
  72.        
  73.         print '<br /><br /><u>Files in '.$dir.'</u>
  74.         <ul>';
  75.         while ($file = readdir($listed_dir)) {
  76.                 if ($file != '.' && $file != '..') {
  77.                         print '<li>'.$file.'</li>';
  78.                 }
  79.         }
  80.         print '</ul>';
  81.        
  82.         closedir($listed_dir);
  83. }
  84.  
  85. //headers
  86. print '<h2>File Uploader</h2>';
  87.  
  88. //for now we are going to make the program submit to itself...
  89. if (!isset($_POST['submit'])) {
  90.         //print the upload form
  91.         upload_form();
  92. } elseif (isset($_POST['submit'])) {
  93.         //start form validation
  94.         $error_array = array();
  95.        
  96.         if (empty($_FILES['file']['name'])) {
  97.                 //add to the error array
  98.                 $error_array[] = 'ERROR: File name is empty.';
  99.         }
  100.        
  101.         if (!in_array($_FILES['file']['type'], $allowed_types)) {
  102.                 //add to the error array
  103.                 $error_array[] = 'ERROR: Invalid file type.';
  104.         }
  105.        
  106.         if (sizeof($error_array) < 1) {
  107.                 process_upload($_FILES['file']['tmp_name'], $_FILES['file']['name'], $upload_dir);
  108.         } else {
  109.                 //print upload form
  110.                 upload_form($error_array);
  111.         }
  112. }
  113.  
  114. ?>

Now the break down...

We start off by setting the allowed file types and we specify what directory we upload files to. For the allowed type we are specifying them by mime types. You can find a full list of mime types here.

  1. <?php
  2. //ok we start by setting the allowed file types to be uploaded
  3. //lets do... txt and a few image files by listing them by mime type
  4. $allowed_types = array('text/plain', 'image/jpeg', 'image/gif', 'image/png');
  5.  
  6. //now we specify what upload directory we want our files to upload to
  7. $upload_dir = 'uploads/';
  8. ?>

Next create a function that cleans up your file upload string to get rid of special characters.

  1. <?php
  2. //now we can make a function that parses through the file string and gets rid of special characters
  3. function string_clean($str) {
  4.         $new_str = str_replace(" ", "-", $str);
  5.         $new_str = str_replace("//", "", $new_str);
  6.         $new_str = str_replace("/", "", $new_str);
  7.         $new_str = str_replace(":", "", $new_str);
  8.         $new_str = str_replace("*", "", $new_str);
  9.         $new_str = str_replace("?", "", $new_str);
  10.         $new_str = str_replace("<", "", $new_str);
  11.         $new_str = str_replace(">", "", $new_str);
  12.         $new_str = str_replace("|", "", $new_str);
  13.         $new_str = str_replace("'", "", $new_str);
  14.         $new_str = str_replace("\"", "", $new_str);
  15.         $new_str = str_replace("\\", "", $new_str);
  16.        
  17.         return $new_str;
  18. }
  19. ?>

Now we create the uploading form for the user to enter the local file from their system. We build the form to display errors if any. Then we build the form processing function that actually performs the upload from local machine to remote machine.

  1. <?php
  2. //create the upload form
  3. function upload_form($errors = array()) {
  4.         if (sizeof($errors) > 0) {
  5.                 foreach ($errors as $error) {
  6.                         print $error . '<br />';
  7.                 }
  8.         }
  9.        
  10.         print '<form action = "'.$_SERVER['PHP_SELF'].'" method = "post" enctype = "multipart/form-data">
  11.         <table border = "0">
  12.                 <tr>
  13.                         <td>Upload File:</td>
  14.                         <td><input type = "file" name = "file" size = "40" /></td>
  15.                 </tr>
  16.                 <tr>
  17.                         <td></td>
  18.                         <td><input type = "submit" name = "submit" value = "Upload" /></td>
  19.                 </tr>
  20.         </table>
  21.         </form>';
  22. }
  23.  
  24. //make a function that processes the actual upload
  25. function process_upload($tmp_name, $filename, $upload_dir) {
  26.         //clean the file of special characters
  27.         $clean_filename = string_clean($filename);
  28.         //concat the upload directory to the cleaned filename
  29.         $upload_filename = $upload_dir . $clean_filename;
  30.        
  31.         //now upload this biatch!!!!
  32.         if (move_uploaded_file($tmp_name, $upload_filename)) {
  33.                 print 'Upload Successful! <a href = "'.$_SERVER['PHP_SELF'].'">Back to form</a>';
  34.         } else {
  35.                 print 'Upload Failed!';
  36.         }
  37.        
  38.         //display the contents of the upload directory anyways
  39.         list_uploads($upload_dir);
  40. }
  41.  
  42. //make a function the lists all files in the upload directory
  43. function list_uploads($dir) {
  44.         $listed_dir = opendir($dir);
  45.        
  46.         print '<br /><br /><u>Files in '.$dir.'</u>
  47.         <ul>';
  48.         while ($file = readdir($listed_dir)) {
  49.                 if ($file != '.' && $file != '..') {
  50.                         print '<li>'.$file.'</li>';
  51.                 }
  52.         }
  53.         print '</ul>';
  54.        
  55.         closedir($listed_dir);
  56. }
  57. ?>

Now we are at the part we start getting down to business. We want the form to submit to itself so we use $_SERVER['PHP_SELF'] in the form (refer to the upload_form()). First we have to check if the submit button is submitted and set, if its not we display the upload form, or if it is set we then start validating the form. Then if the form passed through validation we then process the file upload. Simple!

  1. //headers
  2. print '<h2>File Uploader</h2>';
  3.  
  4. //for now we are going to make the program submit to itself...
  5. if (!isset($_POST['submit'])) {
  6.         //print the upload form
  7.         upload_form();
  8. } elseif (isset($_POST['submit'])) {
  9.         //start form validation
  10.         $error_array = array();
  11.        
  12.         if (empty($_FILES['file']['name'])) {
  13.                 //add to the error array
  14.                 $error_array[] = 'ERROR: File name is empty.';
  15.         }
  16.        
  17.         if (!in_array($_FILES['file']['type'], $allowed_types)) {
  18.                 //add to the error array
  19.                 $error_array[] = 'ERROR: Invalid file type.';
  20.         }
  21.        
  22.         if (sizeof($error_array) < 1) {
  23.                 process_upload($_FILES['file']['tmp_name'], $_FILES['file']['name'], $upload_dir);
  24.         } else {
  25.                 //print upload form
  26.                 upload_form($error_array);
  27.         }
  28. }

Its pretty simple, but there are more sophisticated ways of doing file uploads such as displaying friendly information (progress bars, percentages, etc.).

A more challenging step is to edit apache and/or edit your php.ini file to set higher limits on $_POST and file upload data limits. Your PHP's default for file uploading size should be 8M. So you can either try ini_set('upload_max_filesize', '[to whatever you want]') or directly through the php.ini file or someway with apache's configuration files.

Thats all...

Have fun,
Rashaud Teague