Web Info and IT Lessons Blog...

Thursday 26 February 2015

How to upload a file in PHP?

The previous lesson of PHP Lesson Series was about Simple Login System in PHP and in this lesson we will learn to upload a file in PHP.

Upload File in PHP

To upload a file in PHP the first thing we need is an html form with a choose file button and an upload button. The html code of form is given below:


<form action="index.php" method="POST" enctype="multipart/form-data">
    Choose Image:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>


You can see in the above html code the type of first input form element is file which means that this button will let you browse your computer and choose a file to upload. The second button in the form is submit button which is used to send form data through POST method.

Two other things worth mentioning about the above form are:

1. Always use form POST method for file uploading in PHP. File uploading can not be done through GET method.
2. Do not forget to mention enctype="multipart/form-data" in the html form when uploading files in PHP.

That was the html part of the code, let us come to the PHP part now. The complete PHP code that will get the job done for us is given below:


if(isset($_POST['submit'])){
   $upload_dir = "uploadDir/";
   $file = $upload_dir . basename($_FILES["fileToUpload"]["name"]);
   $imageFileType = pathinfo($file,PATHINFO_EXTENSION);
 
   if (!file_exists($file)) {
     if ($_FILES["fileToUpload"]["size"] < 500000) {
        if($imageFileType == 'jpg'){
           if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $file))
           {
              echo basename( $_FILES["fileToUpload"]["name"])." is uploaded.";
           } else {
              echo "Sorry could not upload the file!";
           }
        }else{
          echo 'The file extension is not .jpg';
        }
   
     }else{
       echo 'Sorry the file size is too large.';
     }
   }else{
     echo 'The file already exists or no file selected.';
   }
}


Now let me explain the above PHP code. The first line of the above code checks if the POST array is set which happens when the form submit button is clicked. If the submit button is clicked, this means that the user has chosen the file and wants to upload it. Then we have set the upload directory where the uploaded image will be be saved through this code:


$upload_dir = "uploadDir/";

Then we have this code given below:


$file = $upload_dir . basename($_FILES["fileToUpload"]["name"]);

In the above line of code basename($_FILES["fileToUpload"]["name"]) gives us the name of the file which then is appended to the upload directory to save the complete path of the upload image in the variable $file.

The next line i.e


$imageFileType = pathinfo($file,PATHINFO_EXTENSION);

reads the extension of the file to be uploaded. If the file is an image (JPG) file, the extension of the file will be .jpg which will be saved in the variable $imageFileType.

The next condition in the if statement i.e (!file_exists($file)) checks if the file does not exist already in the upload folder and if so, then we check the size of file to be uploaded through this statement:


$_FILES["fileToUpload"]["size"] < 500000

If the size of the file is not greater than 500000 (i.e 500kb), we go further with the upload process else we echo an error message.

The next line of code checks if the extension of the file to be uploaded is (jpg). I have done this because I wanted to limit the upload to JPG files only, if you want to upload every type of file, just get rid of the if statement given below:


if($imageFileType == 'jpg')

In the end we have a last if statement i.e:


if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $file))

The above if statement checks if the file is uploaded successfully to the destined location, show the success message else show error message.

So that was the explanation of the above code and that's all for this lesson.

For more lessons about PHP subscribe on InformationBitz.com

No comments:

Post a Comment