Saturday, October 8, 2016

How to Allow a Visitor Upload Image Files on Your Web Server

This post is based on this tutorial with some minor modifications.

If you want to let a visitor upload an image file to your web server, here is how to do. I will assume that you have a http and php server running on your system. If not, please refer to this post.

First, create a simple upload.html file:
    <form action="upload.php" method="post" enctype="multipart/form-data">
            Select image to upload:
                <input type="file" name="fileToUpload" id="fileToUpload">
                <input type="submit" value="Upload Image" name="submit">

Next, create upload.php file:
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".<br>";
        $uploadOk = 1;
    } else {
        echo "File is not an image.<br>";
        $uploadOk = 0;
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
    echo "Sorry, your file is too large.<br>";
    $uploadOk = 0;
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "webp" && $imageFileType != "jxr" ) {
    echo "Sorry, only jpg, jpeg, png, webp, jxr, & gif files are allowed. Also, the extension must be all LOWER case!<br>";
    $uploadOk = 0;
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.<br>";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<br>";
        echo "<br>http://SERVER_IP/" . $target_dir . basename( $_FILES["fileToUpload"]["name"]) . "<br>";
    } else {
        echo "Sorry, there was an error uploading your file.<br>";

Make sure to replace SERVER_IP with your server's IP address. Now, you can browse to your upload.html file, choose an image file, and upload to the server.

Make sure that the target directory is owned by www-data, the web werver.
$ sudo chown www-data:www-data /var/www/html/upload

Make sure to implement more security checks. You surely don't want any random visitor upload random files on the server!

No comments:

Post a Comment