Example of Uploading Files in PHP


An Example of Uploading Files in PHP is shown here.

Applications and Use of Uploading Files in PHP

Because many dynamic applications provide features for users to upload files, it is one of the most essential functions of a web application. Significantly, many CMS (Content Management Systems) allow administrators to upload images as well as other types of files such as PDF, Doc, or CSV. Here, we discuss uploading files in PHP and how to restrict the files being uploaded.

The following code shows a form that we are going to use for uploading a file. In the form, we have an input field of file type and a submit button. When a user clicks on the button, the PHP script in the file should execute.

   <title>File Upload Example</title>
   <form name="myform" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
     Select a File: <input type="file" name="t1"/><br><br>
      <input type="submit" name="submit" value="Upload"/>
HTML Form for Uploading Files in PHP

Role of $ _FILES in File Upload

In fact, PHP offers a superglobal variable $ _FILES that we use to retrieve the properties of a file. When we upload a file on the server, we need some properties of the file to check before uploading. Accordingly, the $ _FILES superglobal variable, which is basically an associative array has the following fields:

$ FILES[‘name’] It represents the file name. This is the actual name of the file that we are uploading.

$ FILES[‘temp_name’] Before the file is uploaded to the server, it gets a temporary address. Therefore, ‘tmp_name’ represents the name of that temporary address.

$ _FILES[‘type’] The type represents the file extension. Hence, we can use this field to restrict the upload of the file to specific extensions.

$ _FILES[‘size’] Basically, it is the size of the file in bytes.

$ _FILES[‘error’] In fact, a file may encounter certain errors during upload. So, this field represents the errors encountered during upload.

Apart from the $ _FILES array, we need to use certain library functions in the PHP script to upload a file. These functions are discussed here. (https://www.programmingempire.com/php-library-functions-for-uploading-files/)

Also, a discussion on move_uploaded_file () is given here. (https://www.programmingempire.com/a-brief-description-of-move_uploaded_file-function-in-php/)

Click here to find a complete example on uploading files in PHP. https://www.programmingempire.com/an-example-of-uploading-files-in-php/

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP




Please enter your comment!
Please enter your name here