PHP File upload step by step with example

0

Nowadays, PHP is a highly used language for Web development. So, Today we are going to learn PHP file upload functionality. PHP file upload functionality is very easy and almost every application must have an image upload functionality. So, let see how to upload a file using PHP programming.

PHP File upload

First of all, We are going to create the HTML form. So, let’s create the index.php HTML file. Then write the following code.

<!DOCTYPE html>
<html>
    <head>
        <title>TryVary - PHP File Upload</title>
    </head>
    <body>

    	<?php if( isset($_REQUEST['status']) && $_REQUEST['status'] == 'error' ){ ?>
    	<p style="color : red"><?php print $_REQUEST['message']; ?></p>
    	<?php } ?>

    	<?php if( isset($_REQUEST['status']) && $_REQUEST['status'] == 'success' ){ ?>
    	<p style="color : green"><?php print $_REQUEST['message']; ?></p>
    	<?php } ?>

        <form action="fileupload.php" method="POST" enctype="multipart/form-data">
            <p>
                Select File to upload:
            </p>
            <p>
                <input type="file" name="fileupload" id="fileupload">
            </p>
            <input type="submit" value="Upload Image" name="submit">
        </form>
        <br><br>
        <?php if( isset($_REQUEST['image']) ){ ?>
    	<img src="uploads/<?php print $_REQUEST['image']; ?>"/>
    	<?php } ?>
    </body>
</html>

We are ready with the HTML form. Now, let’s create the PHP code for handling the uploaded file and store it into the directory. First of all, create the fileupload.php PHP file. Then write the following PHP code.

<?php
    if( $_POST['submit'] ){
        $file_name = $_FILES['fileupload']['name'];
        
        $fileinfo = @getimagesize($_FILES['fileupload']["tmp_name"]);
        $width = $fileinfo[0];
        $height = $fileinfo[1];
        
        $allowed_image_extension = array(
            "png",
            "jpg",
            "jpeg"
        );

        // Get image file extension
        $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

        // Validate file input to check if is not empty
        if (! file_exists($_FILES["fileupload"]["tmp_name"])) {
            $response = array(
                "status" => "error",
                "message" => "Please select any file."
            );
            $failString = http_build_query($response);
            header("Location: http://localhost/tryvary/index.php?".$failString);
            exit;
        }    // Validate file input to check if is with valid extension
        else if (! in_array($file_extension, $allowed_image_extension)) {
            $response = array(
                "status" => "error",
                "message" => "Please Upload valid image. Only PNG and JPEG are allowed."
            );
            $failString = http_build_query($response);
            header("Location: http://localhost/tryvary/index.php?".$failString);
            exit;
        }    // Validate image file size
        else if (($_FILES["fileupload"]["size"] > 2000000)) {
            $response = array(
                "status" => "error",
                "message" => "Image size exceeds 2MB"
            );
            $failString = http_build_query($response);
            header("Location: http://localhost/tryvary/index.php?".$failString);
            exit;
        }    // Validate image file dimension
        else if ($width > "800" || $height > "600") {
            $response = array(
                "status" => "error",
                "message" => "Image dimension should be within 800x600"
            );
            $failString = http_build_query($response);
            header("Location: http://localhost/tryvary/index.php?".$failString);
            exit;
        }

        // commenth below code if you don't want to change the file name
        $fileNames = explode(".",$file_name);
        $file_name = time().".".$fileNames[count($fileNames) - 1];

        $file_upload = move_uploaded_file($_FILES['fileupload']['tmp_name'],"uploads/".$file_name);
        if( $file_upload ) {
            $response = array(
                "status" => "success",
                "message" => "Image uploaded successfully",
                "image" => $file_name
            );
            $failString = http_build_query($response);
            header("Location: http://localhost/tryvary/index.php?".$failString);
            exit;
        } else {
            $response = array(
                "status" => "error",
                "message" => $_FILES["file"]["error"]
            );
            $failString = http_build_query($response);
            header("Location: http://localhost/tryvary/index.php?".$failString);
            exit;
        }
    }
?>

Finally, We are ready with the PHP code. Before, Run the PHP code please create the uploads directory at the root folder of your project. Then select a file and upload it and check the file is stored on uploads directory. If file upload successfully it will display the image on the browser.

If you face any issue after following the code please write the comment below. We are always ready for help.

Share.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.