The following code shows An Example of Uploading Files in PHP.

As can be seen in the following code, first of all, we need to create a form. Also, the form tag must have the enctype attribute set to multipart-form-data.

When the clicks on the Upload button, the corresponding PHP script executes. The script has many checks in place before uploading the file. To begin with, it checks whether the user has selected a file or not. In case, the user has clicked on the Upload button without selecting the file, the script exits after producing an error message.

Otherwise, it applies the next check on the file extension. When the chosen file has an extension as one of the values in the array, it proceeds further. Otherwise, it produces an error message and exits.

Similarly, it applies a check on the file size. If the chosen file is bigger than the allowed size, it displays an error message and exits. Lastly, it checks whether the specified directory exists or not. If it exists, it uploads the file and gives a success message. Otherwise, it gives an error message and exits. Furthermore, you can also apply a check on whether to overwrite the existing file or not. Here, in the example, the file is overwritten, if it already exists.

   <title>File Upload Example</title>
   <form name="myform" method="POST" action="fileupload2.php" enctype="multipart/form-data">
     Select a File: <input type="file" name="t1"/><br><br>
      <input type="submit" name="submit" value="Upload"/>
    $myextensions=array('pdf', 'doc', 'docx', 'ppt', 'pptx', 'txt');
    $filetype=pathinfo($_FILES['t1']['name'], PATHINFO_EXTENSION);
    if(!array_search($filetype, $myextensions))
      die("File of type ".$filetype." Can't be uploaded!");

      die("File is too large to upload!");
    $file_extension= $_FILES['t1']['type'];   
            echo 'File Uploaded Successfully!';     
                echo 'Invalid Directory!';
           echo 'No File Selected!';


An Example of Uploading Files in PHP - Select the File
An Example of Uploading Files in PHP – Select the File
File Uploading in PHP
File Uploading in PHP

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP