Uploading Files using PHP

PHP provides built-in function move_uploaded_file() for uploading files to a directory. This function requires two parameters, those are the source file and the destination for the moved file. This function will check if the uploaded file is posted via HTTP POST method to protect the file data. The is_uploaded_file is used to check if the file is uploaded via HTTP POST method.

In this tutorial, we are going to upload files using an HTML form. This form should contain the attributes as method=’post’ and enctype=’multipart/form-data’ to support file upload. It helps to bundle the form-data and the binary-data to post it to the server side PHP file. In PHP code, it will read the uploaded file information by using $_FILES superglobal. It will check that the $_FILES array not empty and the uploaded file is posted via HTTP POST method and then executes the file upload script.

Create HTML form

The code shows the form with method=’post’ and enctype=’multipart/form-data’  attributes to upload files. It contains a file type input field to select the file to be uploaded. On submitting this form, the form-data and the file binary-data will be bundled and posted to the PHP file.

<form action="" enctype="multipart/form-data" method="POST" name="frm_user_file">
<input type="file" name="myfile" /> 
<input type="submit" name="submit" value="Upload" />
</form>

PHP File Upload Code

This PHP code validates that the uploaded file is not empty and it is posted via the HTTP_POST method. Then, it specifies the source and destination file path to the move_uploaded_file() function to move the source file to the target as specified. 

$targetDir = "D:\phppot_uploads";
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['myfile']['tmp_name'])) {
if(move_uploaded_file($_FILES['myfile']['tmp_name'],"$targetDir/".$_FILES['myfile']['name'])) {
echo "File uploaded successfully";
}
}
}

Download PHP File Upload Source Code

This PHP code tutorial was published on May 2, 2013.

↑ Back to Top