i

PHP Tutorial

PHP File Upload

You can allow the users to upload a file using PHP forms. Uploading a file is easy in PHP and is required many times when we create your web application where a document is required in the form of a file.

First you need to configure the “php.ini” file to ensure that your php is allowed for file uploads and you need to set file_uploads directive to on as below:

file_uploads = On

To upload the file, you need to create an HTML form to let users upload a file such as an image.

Choose an image to upload:

You should use POST method in the form and also include the enctype attribute to specify what content type to use while submitting the form.

Now, we need to create php script for file_upload.php that will have the code for uploading a file.

$destination_dir = "Uploaded_images/";
$destination_file = $destination_dir . basename($_FILES["Upload_File"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($destination_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["Upload_File"]["temporary_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

In the above script, $destination_dir specifies the directory where the file has to be placed. $destination_file specifies the path to upload the file. $imageFileType holds the extension of the file.

We can also do various check on the files as below.

To check the file is already existing in the Uploaded_images folder and if it is present then display an error message, write the below php script.

if (file_exists($destination_file) {

            echo “ File already exists”;

            $uploadOk = 0;

}

If you want to display an error message when file is above 700KB, you can write the below script.

if ($_FILES [“Uploaded_images”] [“size”] > 700000){

            echo “ File is too large to upload”;

            $uploadOk = 0;

}

You can also limit the type of files you want the users to upload. For example, if you need only JPEG, PNG, JPG, GIF files to be uploaded, you can write the below script.

if ($imageFileType != “jpeg” && $imageFileType != “png” && $imageFileType != “jpg” && $imageFileType != “gif”)

{

            echo “ Please enter a valid format file”;

            $uploadOk = 0;

}