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 the HTTP POST method to protect the file data. The is_uploaded_file is used to check if the file is uploaded via the 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 is not empty and the uploaded file is posted via the HTTP POST method and then executes the file upload script. Refer to my earlier article for PHP AJAX image upload.

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 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.

<?php
$targetDir = "uploads";
if (isset($_FILES['myfile']) && 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

Photo of Vincy, PHP developer
Written by Vincy Last updated: October 23, 2025
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

17 Comments on "Uploading Files using PHP"

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore topics
Need PHP help?