submitted by:

PHP: Upload File

Simple example that shows how to upload a file using PHP. Both the form and the data processer are on the same page. Configure the upload path and the max file size as per your requirements.


code snippet:
<?php
// basic php file upload example
// http://php.snippetdb.com

if ($_POST['upload']){ //process uploaded file
    
$uploadDir '/path/to/upload/directory/'//file upload path
    
$uploadFile $uploadDir $_FILES['uploadfile']['name'];
    echo 
"<pre>";
    if (
move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadFile) )
    {
        echo 
"File is valid, and was successfully uploaded. ";
        echo 
"Here's some more debugging info:\n";
    }
    else
    {
        echo 
"ERROR!  Here's some debugging info:\n";
        echo 
"remember to check valid path, max filesize\n";
    }
    
var_dump($_FILES);
    echo 
"</pre>";
    
} else { 
//display upload form
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['SCRIPT_NAME']?>" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1024000">
    <br>
  <input name="uploadfile" type="file">
    <br>
    <input name= "upload" type="submit" value="Upload File">
</form>
<?php
}
?>

notes:
PHP stores all the uploaded file information in the $_FILES autoglobal array. $_FILES['userfile']['name'] The original name of the file on the client machine. $_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". $_FILES['userfile']['size'] The size, in bytes, of the uploaded file. $_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server. $_FILES['userfile']['error'] The error code associated with this file upload. ['error'] was added in PHP 4.2.0. Files will by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. Use move_uploaded_file() to store an uploaded file somewhere permanently. --from http://www.netspade.com/articles/php/uploading.xml