In this tutorial we will see how to to upload files to the server.

Steps for Uploading PHP File Upload

PHP file upload features allows you to upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executable files and a wide range of other file types.

Step 1: Creating an HTML form

<!DOCTYPE html>

<form action="uploadfile.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="Upload_File" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">


Follow these two rules for the HTML form above:
1. When we use to a file-select field the upload form must use method=”post”.
2. Always contain an enctype=”multipart/form-data” attribute.
The form which we created above sends data to a file called “uploadfile.php”, which we will create next.

Step 2: Create The Upload File PHP Script

The “uploadfile.php” file contains the following code for uploading a file:


  $folder_dir = "uploads/";
$folder_file = $target_dir . basename($_FILES["Upload_File"]["name"]);
$uploadfile = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["Upload_File"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadfile = 1;
    } else {
        echo "File is not an image.";
        $uploadfile = 0;

PHP code explained:

  • $folder_dir = “uploads/” – specifies the directory where the file is going to be placed
  • $folder_file specifies the path of the file to be uploaded
  • $uploadfile=1 is not used yet (will be used later)
  • $imageFileType holds the file extension of the file (in lower case)
  • Next, check if the image file is an actual image or a fake image

Use move_uploaded_file() function for uploading files

This function used to moves the uploaded file to a new location. The move_uploaded_file() function checks first internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the POST request.

$folder_dir = "uploads/";
$folder_file = $target_path.basename( $_FILES['Upload_File']['name']);   
if(move_uploaded_file($_FILES['Upload_File']['tmp_name'], $target_path)) {  
    echo "File uploaded successfully!";  
} else{  
    echo "Sorry, file not uploaded, please try again!";  

Pin It on Pinterest

Share This