PHP File Upload example.

This page discusses how to do File Uploads with an HTML post form using the $_FILES array in PHP. There may be other ways to do this with additional packages. Check out the HTTP as a possibility.

 

 

This example is when you have an HTML form that asks the user to do a file upload using the following input tag named userfile:

<form name="imgform" method="POST" action="ReadFile.php" enctype="multipart/form-data">
      <input type="hidden" name="userfilename" id="userfilename">
      <input type="file" name="userfile" id="userfile" size="64"  maxlength="256"
     onChange="javascript:top.document.imgform.userfilename.value=top.imgform.userfi
     le.value">
   <br>
   <input type="submit" value="upload">
   </form>

 
   

Then, the following script, ReadFile.php, can be used to access this uploaded info:

<?php
     $fileName = $_FILES['userfile']['name'];
     $tmpName  = $_FILES['userfile']['tmp_name'];
     $fileSize = $_FILES['userfile']['size'];
     $fileType = $_FILES['userfile']['type'];
     $error = $_FILES['userfile']['error'];
   
if($error)
     echo "problem uploading file";
     else
     {
     echo "contents of file $fileName uploaded to temp directory with size $fileSize
   <br>";
     moveFile();
     }
   
function moveFile(){
 $uploaddir = '/home/faculty/grewe/public_html/PHP/filedir/';
     $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
     echo 'moving to new location'. $uploadfile;
 echo '<pre>';
     if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
     echo "<br>File is valid, and was successfully moved.\n";
     } else {
     echo "<br>Problem with either upload or move!\n";
     }
 echo '<br>Here is some more debugging info:';
     print_r($_FILES);
 print "</pre>";
}
?>

PROBLEM: THIS IS NOT SECURE!!!

© Lynne Grewe