PHP File Uploading Restrictions

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

Providing the facility to upload files is a very important and useful part of web. But every user is not much aware of the pitfalls of it and the consequences of what will happen if a file of large size is uploaded or a file of undesired format is uploaded. So the programmers need to keep a check on what type of file can be uploaded and what size.

We can imply restrictions on users through code like this. The user may only upload .gif or .jpeg files and the file size must be under 20 kb:

    <?php
    if ((($_FILES["file"]["type"] == “image/gif”)
    || ($_FILES["file"]["type"] == “image/jpeg”)
    || ($_FILES["file"]["type"] == “image/pjpeg”))
    && ($_FILES["file"]["size"] < 20000))
    {
    if ($_FILES["file"]["error"] > 0)
    {
    echo “Error: ” . $_FILES["file"]["error"] . “<br />”;
    }
    else
    {
    echo “Upload: ” . $_FILES["file"]["name"] . “<br />”;
    echo “Type: ” . $_FILES["file"]["type"] . “<br />”;
    echo “Size: ” . ($_FILES["file"]["size"] / 1024) . ” Kb<br />”;
    echo “Stored in: ” . $_FILES["file"]["tmp_name"];
    }
    }
    else
    {
    echo “Invalid file format or size”;
    }
    ?>

Note: IE recognizes jpg files as pjpeg, and FireFox recognizes it by jpeg.

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.