How do I check to see if file loaded is a picture?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
New php-forum User
New php-forum User
Posts: 14
Joined: Mon Apr 22, 2013 4:00 am

Thu Apr 25, 2013 4:50 am

<form enctype="multipart/form-data" method="POST" action="ads.php" />
Name:<input type="text" name ="name" /><br />
Book:<input type="text" name ="book" /><br />
Subject:<input type="text" name ="subject" /><br />
Price (CAN):<input type="text" name ="price" /><br />
Description: <br /><textarea cols="40" rows="5" name="description">

</textarea><br />
Click to upload:<input type="file" name="pix" /><br />
<input type="submit" name="Upload" value="Upload Picture" />

I want this form to only submit if the pictures are either gif, jpeg, or png.

I want to have protection against blank entries, incomplete entries. duplicate entries

Would that require an IF statement? Or something more advanced like JQuery / AJAX?

New php-forum User
New php-forum User
Posts: 20
Joined: Tue Mar 06, 2012 11:05 pm

Thu Apr 25, 2013 5:19 am


I am not sure whether you want this in client end or in server end. However here is the description with javascript:

1. First you can check the emptiness by using regular expression.
2. If the the field is not empty, find the extension of the entered file by the following code.

Code: Select all

var file = $('#pix'); //considers the id of the input field is 'pix'
    var parts = file.split('.');
    var ext = parts[parts.length - 1];
3. Now compare the extension with your required one like below:

Code: Select all

    switch (ext.toLowerCase()) {
    case 'jpg':
        alert('Right Image');
    case 'gif':
         alert('Right Image');
    case 'png':
        alert('Right Image');
        alert('Wrong Image');
If you want to do it in php, you can use filetype() function.


php-forum Fan User
php-forum Fan User
Posts: 974
Joined: Mon Oct 01, 2012 12:32 pm

Thu Apr 25, 2013 7:39 am

filetype() won't give you the information that you're looking for, and you should NEVER rely on the extension of a file to tell you what it is. For a long time people were able to execute code on visitor machines by writing javascript and vbscript into files that they saved with photo extensions. Then visitors browsers would open the file based on its contents rather than its extension and execute the code. This doesn't work any more for modern browsers but it's still a teachable moment. use fileinfo to get a better idea of file type

Post Reply