Working with File Uploads in PHP

Working with File Uploads in PHP 

  • A PHP script can be used with an HTML form to allow users to upload files to the server. 
  • Initially, files are uploaded into a temporary directory and then relocated to a target destination by a PHP script. 
  • Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize.
  • These parameters are set into the PHP configuration file php.ini

The process of uploading a file follows these steps −

  • The user opens the page containing an HTML form featuring text files, a browse button, and a submit button.
  • The user clicks the browse button and selects a file to upload from the local PC.
  • The full path to the selected file appears in the text filed then the user clicks the submit button.
  • The selected file is sent to the temporary directory on the server.
  • The PHP script that was specified as the form handler in the form's action attribute checks that the file has arrived and then copies the file into an intended directory.
  • The PHP script confirms the success of the user.

As usual, when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. 

If either is set to be read-only then the process will fail.

An uploaded file could be a text file or image file or any document. 


Creating an upload script

  • There is one global PHP variable called $_FILES.
  • This variable is an associate double dimension array and keeps all the information related to the uploaded file. 
  • So if the value assigned to the input's name attribute in the uploading form was file, then PHP would create the following five variables −

  • $_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.
  • $_FILES['file']['name'] − the actual name of the uploaded file.
  • $_FILES['file']['size'] − the size in bytes of the uploaded file.
  • $_FILES['file']['type'] − the MIME type of the uploaded file.
  • $_FILES['file']['error'] − the error code associated with this file upload.

Configure The "php.ini" File

First, ensure that PHP is configured to allow file uploads.

In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On


The Key Settings

file_uploads

The value of the file_uploads directive should be set to On to allow file uploads.

The default value of this directive is On.

upload_max_filesize

The upload_max_filesize the directive allows you to configure the maximum size of the uploaded file.

By default, it's set to 2M (two megabytes), and you can override this setting using the .htaccess file as well. Two megabytes isn't very much by today's standards, so you might have to increase this. If you get an error that file exceeds upload_max_filesize when you try to upload a file, you need to increase this value. 

If you do, be sure to also increase post_max_size .

upload_tmp_dir

Sets a temporary directory that will be used to store uploaded files.

In most cases, don't need to worry about this setting.

If you don't set it, the system default temp directory will be used.

post_max_size

The post_max_size directive allows you to configure the maximum size of POST data. Since files are uploaded with POST requests, this value must be greater than what you've set for the  upload_max_filesize directive.  

For example, if your upload_max_filesize is 16M (16 megabytes), you might want to   set post_max_size to 20M.

max_file_uploads

It allows you to set the maximum number of files that can be uploaded at a time. 

The default is 20, a sensible amount.

max_input_time

It's the maximum number of seconds a script is allowed to parse the input data. You should set it to a reasonable value if you're dealing with large file uploads. 60 (60 seconds) is a good value for most apps.

memory_limit

The memory_limit directive indicates the maximum amount of memory a script can consume.

If you're facing issues when uploading large files, you need to make sure that the value of this directive is greater than you've set for the post_max_size directive.

The default value is 128M (128 megabytes), so unless you have a very  large post_max_size and upload_max_filesize.

max_execution_time

It's the maximum number of seconds a script is allowed to run. 

If you're facing issues when uploading large files, you can consider increasing this value. 

30 (30 seconds) should work well for most apps.


Create the Upload Logic

In the upload.php file, we've checked whether it’s a valid POST request in the first place.


1 2 3if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload') { ... }

In PHP, when a file is uploaded, the $_FILES superglobal variable is populated with all the information about the uploaded file. 

It’s initialized as an array and may contain the following information for successful file upload such as tmp_name, name, size, type and error.

In the case of successful file upload, it contains 0, which you can compare by using the UPLOAD_ERR_OK constant.

After validating the POST request, we check that the file upload was successful.


1 2 3if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK) { ... }

The $_FILES variable is a multi-dimensional array, the first element is the name of the file field, and the second element has the information about the uploaded file.

If the file upload is successful, we initialize a few variables with information about the uploaded file.


1 2 3 4 5 6 7// get details of the uploaded file $fileTmpPath = $_FILES['uploadedFile']['tmp_name']; $fileName = $_FILES['uploadedFile']['name']; $fileSize = $_FILES['uploadedFile']['size']; $fileType = $_FILES['uploadedFile']['type']; $fileNameCmps = explode(".", $fileName); $fileExtension = strtolower(end($fileNameCmps));

In the above snippet, we’ve also figured out the extension of the uploaded file and stored it in the $fileExtension variable.

As the uploaded file may contain spaces and other special characters, it’s better to sanitize the filename, and that’s exactly we’ve done in the following snippet.


1$newFileName = md5(time() . $fileName) . '.' . $fileExtension;

It’s important that you restrict the type of file which can be uploaded to certain extensions and don’t allow everything using the upload form. 

We’ve done that by checking the extension of the uploaded file with a set of extensions that we want to allow for uploading.


1 2 3 4$allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc'); if (in_array($fileExtension, $allowedfileExtensions)) { ... }

Finally, we use the move_uploaded_file function to move the uploaded file to the specific location of our choice.


                   // directory in which the uploaded file will be moved $uploadFileDir = './uploaded_files/'; $dest_path = $uploadFileDir . $newFileName;   if(move_uploaded_file($fileTmpPath, $dest_path)) {   $message ='File is successfully uploaded.'; } else {   $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.'; }

The move_uploaded_file function takes two arguments. The first argument is the filename of the uploaded file, and the second argument is the destination path where you want to move the file.

move_uploaded_file() function

The move_uploaded_file() function moves the uploaded file to a new location. 

The move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. 

It moves the file if it is uploaded through the POST request.

Syntax

bool move_uploaded_file ( string $filename , string $destination )  

Windows users would use a path including the drive letter, such as the following:

$file_dir = “C:\Users\You\Desktop”;

PHP File Upload Example:-

File: uploadform.html

<form action="uploader.php" method="post" enctype="multipart/form-data">  

   Select File:  

 <input type="file" name="fileToUpload"/>  

  <input type="submit" value="Upload Image" name="submit"/>  

</form>  

File: uploader.php

<?php  

$target_path = "e:/";  

$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);   

if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {  

    echo "File uploaded successfully!";  

else{  

    echo "Sorry, file not uploaded, please try again!";  

}  

?>  





Post a Comment

0 Comments