PHP File Upload

File uploading a very common thing if you are working on a web application. So in this chapter we will explain everything in details about file uploading but before that we want to tell you about few common functions which will be used in file uploading.

basename() function in PHP

basename() function accepts one parameter and  is used to get the file name from a link or URL. You can understand this with the following example:

pathinfo() function in PHP

This function accepts two parameter and returns a value with the type of the file.

getimagesize() function in PHP

This function accepts one parameter and returns the image dimensions (height/width) along with the type of file.

file_exists() function in PHP

This function accepts one parameter as a file name and will check if any file or directory with the same name exists or not in the same folder. It will returns TRUE if the file exists, else FALSE.

move_uploaded_file() function in PHP

This is is used to move a file to a new location or simply we can say that this file will be used to upload the file on server. This function accepts two parameter (filename, file location) and if the file is not uploaded because of any reason then it will returns FALSE else there will be no action.

As we have already explained all the functions which will be used in file uploading, so now it will be easy for you to understand the complete process.

NOTE: If you are creating an HTML form for the purpose of file uploading then you need to know the three main important points as mentioned below:

  1. Form Method: If you are trying to upload a file then the form method should be “POST” because the “GET” method is not going to work for file uploading because we can send only limited values using GET method. So always use POST method while file uploading.
  2. enctype attribute: You also have to add the enctype attribute in the form tag because only this tag will specify that which content type will be used while uploading the file.
  3. File attribute of input type: The file attribute of the input type should be “file”. Normally, we use input type attribute as “text” but in case of file upload, the input type attribute should be “file” because this will create the option to browse a file.

Step 1: Create an HTML Form

Step 2: Upload file in PHP

Check the file size in PHP

The following script is used to check the file size:

Check the file format in PHP

Check the file exist or not in PHP




Leave a Reply

Your email address will not be published.