PHP can be used to receive files from any RFC-1867 compliant browser. This can be used to upload both text and binary files from browsers. See the file upload html form below:
<form enctype=”multipart/form-data” action=”handle_upload.php” method=”post”>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”30000″>
Select File: <input name=”myfile” type=”file”>
<input type=”submit” value=”Upload”>
</form>
- MAX_FILE_SIZE hidden field restrict the maximum filesize accepted in bytes and must precede the file input field
- enctype=”multipart/form-data” is used to handle file uploads and file will be uploaded as MIME data streams. Otherwise the file upload will not work.
The Variables, in PHP script which receives file upload, differs depending on the PHP version and configuration. The $_FILES exists as of PHP 4.1.0 The $HTTP_POST_FILES array has existed since PHP 4.0.0. These arrays hold uploaded file information. Using $_FILES is preferred.
The contents of $_FILES from above script is as follows.
- $_FILES[‘myfile’][‘name’] The original name of the file on the client machine.
- $_FILES[‘myfile’][‘type’] The mime type of the file, if the browser provided this information. An example would be “image/gif”.
- $_FILES[‘myfile’][‘size’] The size, in bytes, of the uploaded file.
- $_FILES[‘myfile’][‘tmp_name’] The temporary filename of the file in which the uploaded file was stored on the server.
- $_FILES[‘myfile’][‘error’] Since PHP 4.2.0, PHP returns an appropriate following error code along with the file array
UPLOAD_ERR_OK – Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
Uploaded Files will by default be stored in the server’s default temporary directory. Variable $_FILES[‘myfile’][‘tmp_name’] will hold the info about where it is stored. The move_uploaded_file function needs to be used to store the uploaded file to the correct location. See the code below:
$uploaddir = “uploads/”;
$uploadfile = $uploaddir . basename( $_FILES[‘myfile’][‘name’]);
if(move_uploaded_file($_FILES[‘myfile’][‘tmp_name’], $uploadfile))
{
echo “The file has been uploaded successfully”;
}
else
{
echo “There was an error uploading the file”;
}
Posted by V.HPatel