file uploading validation in php

First thing comes to our mind , why we need validation in File uploading .

  • To allow only valid file format/extension to be uploaded to the server (Like allow only jpeg,png and doc file format)
  • To allow only limited file size ( file size more than 4Mb should not allowed by the server)
  • To allow file those having proper content (Virus files may content harmful contents)

All uploaded file can be handled by using superglobal veriable called $_FILES ,its a associative array like $_POST and $_GET.

Suppose we have a input type file HTML element named as myFirstFile, so to access all the information about the file we can go in the following way like follows

$_FILES[‘myFirstFile’][‘name’] (will give the uploaded file name, if an user in uploading a file called myresume.doc ,then this line will give p/p as myresume.doc)

$_FILES[‘myFirstFile’][‘size’] (This will give the uploaded file size in byte like 24byte)

$_FILES[‘myFirstFile’][‘type’] (If some user upload a png file ,then this line will give output as image/png)

$_FILES[‘myFirstFile’][‘tmp_name’] (This is the uploaded file itself,the real file stored in tmp folder)

Types of file uploading validation goes in following manner

1.Blank file validation using php

In this type of validation we will check file name as well as the file size like follows

1
2
3
4
if($_FILES['myFirstFile']['name'] == '' || $_FILES['myFirstFile']['size'] == 0)
{
        echo "Please upload the file";
}

 

2.File Size limit validation using php

Suppose we want our file size should not exceed more then 4 mb, if we convert 4mb to byte then the size is 4194304.

1
2
3
4
if($_FILES['myFirstFile']['size'] >4194304)
{
    echo "file size should not exceed 4mb";
}

3.File Type/extension/format validation using php

Suppose we want to allow only image files of extension as png,jpeg,jpg,gif .Then our script will be like something

1
2
3
4
5
6
7
if($_FILES['myFirstFile']['type'] != 'image/jpeg'
&&  $_FILES['myFirstFile']['type'] != 'image/jpg'
&&  $_FILES['myFirstFile']['type'] != 'image/gif'
&& $_FILES['myFirstFile']['type'] != 'image/png')
{
     echo "Please upload only Image file;
}

4.Allow only PDF file to be uploaded

If some one is uploading file of type .pdf then the $_FILES superglobal variable TYPE value will give output something like applicaton/pdf.

If some one is uploading file of type .doc then the $_FILES superglobal variable TYPE value will give output something like applicaton/doc.

If some one is uploading file of type .jpeg then the $_FILES superglobal variable TYPE value will give output something like image/jpeg.

1
2
3
4
if($_FILES['myFirstFile']['type'] != 'application/pdf' )
{
    echo "Please upload the file";
}

Using all the above methods you can go further with your lovely Script for more and more validation. So Guys Keep Coding.