Uploading Files using PHP

by Vincy. Last modified on July 1st, 2022.

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 = "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

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Uploading Files using PHP”

Leave a Reply

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

↑ Back to Top

Share this page