How to Upload Images Using PHP

Posted on - Last Modified on

PHP stands for the recursive backronym “PHP: Hypertext Preprocessor." It is a server-side scripting language and acts as a widely used tool for creating powerful, dynamic webpages. In this article, you'll learn how to use PHP for creating an image file upload form that stores the file in the server. You'll also find out how you can set the limit for the file upload size and also the file type extension criteria for the uploaded file.

In order for the upload process to be activated in the server, you need to set the configuration file of the PHP with a certain parameter value. Change the php.ini file to hold the value of file_upload to be on file_upload= On;. Now the server is set and ready for the uploading process. 

You shall now learn how the different functional segments of the code performs the different criteria checking process. First, create the basic HTML document, which will hold the form that holds the form elements for the file upload and a submit option for the form to submit the uploaded file to the upload_image.php file (which you will see in further levels of the learning process).

<!DOCTYPE html>
<html>
<body>

<form action="upload_image.php" method="post" enctype="multipart/form-data">
    Select the image file :
    <input type="file" name="imagefile" id="imagefile">
    <input type="submit" value="Upload file " name="submit">
</form>

</body>
</html>

Now save this in an HTML document and execute in your server. You'll see the HTML page with a file upload element and a submit button to submit to the upload_image.php file for processing and uploading the image uploaded by the user.
 
You'll see that initially there is “No file Chosen” message displayed in the front end. Selecting the file will display the base name of the file next to the form component.
 
After selecting the file to be uploaded, click on the “Upload file” submit button to initiate the upload of the document by the user by forwarding the form components values to the server. Then create a php file named as “upload_image.php” and save it in the same directory level as the html file in the server.

<?php
$target_upload_dir = "upload_directory/";
$target_file_upload = $target_upload_dir . basename($_FILES["imagefile"]["name"]);
$uploadOkflg = 1;
$uploadimageFileType = pathinfo($target_file_upload,PATHINFO_EXTENSION);
// Check criteria
if(isset($_POST["submit"])) {
    $check_size = getimagesize($_FILES["imagefile"]["tmp_name"]);
    if($check_size !== false) {
        echo "File is of type image - " . $check_size["mime"] . ".";
        $uploadOkflg = 1;
    } else {
        echo "File is not an image.";
        $uploadOkflg = 0;
    }
}

if (file_exists($target_file_upload)) {
    echo "Sorry, filename  already exists , please change your file name and try upload.";
    $uploadOkflg = 0;
}

if ($_FILES["imagefile"]["size"] > 1000000) {
    echo "Sorry, File size exceeded our limits.";
    $uploadOkflg = 0;
}

if($uploadimageFileType != "jpg" && $uploadimageFileType != "png" && $uploadimageFileType != "jpeg"&& $uploadimageFileType != "gif" ) {
    echo "Sorry, this extension of image files is not supported by us.";
    $uploadOkflg = 0;
}

if ($uploadOkflg == 0) {
    echo "Sorry, file upload failed because of above error.";

} else {
    if (move_uploaded_file($_FILES["imagefile"]["tmp_name"], $target_upload_file)) {
        echo "File uploaded successfull.";
    } else {
        echo "Sorry, there is some server issue while uploading your file .Please try again.";
    }
}
?>

Now check on how each segment of the “upload_image.php” file works to accomplish the task of uploading the image by looking at the criteria to be satisfied by the user’s uploaded image file. Then you should define the upload directory where the image should be uploaded and check if the file under same base name as the file uploaded by the user already exists in the directory with the following code segment. You should also maintain an flg variable to check for the match of all the criteria by the file uploaded. 

<?php
$target_upload_dir = "upload_directory/";
$target_file_upload = $target_upload_dir . basename($_FILES["imagefile"]["name"]);
$uploadOkflg = 1;

Obtain the file type of the uploaded file by the user using the following line:

$uploadimageFileType = pathinfo($target_file_upload,PATHINFO_EXTENSION);

Now proceed with the different criteria-checking processes and set your flg variable based on the value satisfied by the file. Then check if the uploaded file is of type mime using the following code snippet.

// Check criteria
if(isset($_POST["submit"])) {
    $check_size = getimagesize($_FILES["imagefile"]["tmp_name"]);
    if($check_size !== false) {
        echo "File is of type image - " . $check_size["mime"] . ".";
        $uploadOkflg = 1;
    } else {
        echo "File is not an image.";
        $uploadOkflg = 0;
    }
}

Then check if the file under same base name as the new file uploaded by the user already exists.

if (file_exists($target_file_upload)) {
    echo "Sorry, filename  already exists , please change your file name and try upload.";
    $uploadOkflg = 0;
}

Next, check for the file size limit criteria to match and display the respective message to the front-end.

if ($_FILES["imagefile"]["size"] > 1000000) {
    echo "Sorry, File size exceeded our limits.";
    $uploadOkflg = 0;
}

Then check the file type extension if it matches the requirements.

if($uploadimageFileType != "jpg" && $uploadimageFileType != "png" && $uploadimageFileType != "jpeg"&& $uploadimageFileType != "gif" ) {
    echo "Sorry, this extension of image files is not supported by us.";
    $uploadOkflg = 0;
}

If the flag is unset during the above process, display the failed error message else you try to move the new file uploaded to the upload directory specified. If it raises any error during the upload, the error message is generated using the following code lines.

if ($uploadOkflg == 0) {
    echo "Sorry, file upload failed because of above error.";

} else {
    if (move_uploaded_file($_FILES["imagefile"]["tmp_name"], $target_upload_file)) {
        echo "File uploaded successfull.";
    } else {
        echo "Sorry, there is some server issue while uploading your file .Please try again.";
    }
}
?>

if ($uploadOkflg == 0) {
    echo "Sorry, file upload failed because of above error.";

} else {
    if (move_uploaded_file($_FILES["imagefile"]["tmp_name"], $target_upload_file)) {
        echo "File uploaded successfull.";
    } else {
        echo "Sorry, there is some server issue while uploading your file .Please try again.";
    }
}
?>

 

Posted 9 December, 2014

Rajhees

DN INFOWAY - WEB DESIGN AND DEVELOPMENT EXPERTS

************ TOP 5 WOMEN FREELANCERS *********************** https://www.freelancer.com/community/articles/women-s-day-special-5-freelancers-who-found-success About ME ************* DN Infoway is an offshore outsourcing company providing round-the-clock services to customers. We are a small team of 10 people, 7 coders and 3 designers. We offer round the clock services in web design and developmen...

Next Article

How to Password Protect a Page or Directory on Your Site