Uploading Files using PHP

Last modified on August 17th, 2018 by Vincy.

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

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

6 Comments to “Uploading Files using PHP”

  • akinsola says:

    hello vincy. thank you for the code. i tried to use this code to create a system where users can upload their pics but it only brings out a blank page with no error of success massage i added to it. i also ensured that i edited the is_uloaded_file to is_uploaded_file.
    i also did not see any uploaded image in my target directory.
    How may i go about making it work for my project as i intend to be refering to each uploaded pic in different users session

  • Bwalya says:

    hi iam new at php and having a hard time writting code, as it stands i want to retrieve images from the database but iam filling , the images are saved as an array

  • Salu says:

    Mam can you pls sent me the code for uploading image with ajax and php?

Leave a Reply

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

↑ Back to Top

Share this Article