How to Upload Only Image Files Using PHP?

I am trying to implement an image upload system, where users can upload only images.

<form action="upload.php" method="post" enctype="multipart/form-data">
    <h2>Upload Images</h2>
    <label for="image-file">Filename:</label>
    <input type="file" name="image_file" id="image-file" accept="image/*">
    <input type="submit" name="submit" value="Upload">
    <p>Only .jpg, .jpeg, .gif, and .png formats are allowed.</p>
</form>

I know I can set accept="image/*" to allow only image selection but the user can easily bypass it. so I want to verify from my server side with PHP.

<?php
if ( isset($_FILES["image_file"]) ) {
    move_uploaded_file($_FILES["image_file"]["tmp_name"], "upload/" . $_FILES["image_file"]["name"] );
    echo "Your image uploaded successfully.";
}
?>

Here how can I check the file is an image?

You can store your desired format in an array and then use the in_array() function to check if the uploading file type is listed in the array.

$allowed = array("image/jpeg", "image/gif", "image/png");
if ( in_array( $_FILES["image_file"]["type"], $allowed ) ){
    // do something
}

So your code should look something like this.

if( isset($_FILES["image_file"]) && $_FILES["image_file"]["error"] == 0 ){
    $allowed    = array("image/jpeg", "image/gif", "image/png");
    $filename   = $_FILES["image_file"]["name"];
    if( in_array( $_FILES["image_file"]["type"], $allowed ) ){
        if(file_exists("upload/" . $filename)){
            echo $filename . " already exists.";
        } else{
            move_uploaded_file($_FILES["image_file"]["tmp_name"], "upload/" . $filename );
            echo "Your image uploaded successfully.";
        }
    }
    else{
        echo "Error: only image files are allowed!";
    }
}

I didn’t test the code but it should work.