Php Script for File Uploading

PHP Script for File Insertion is a unique tool that can upload huge number of files while supporting up to 500MB /file and with high performance, even more, you do not need to worry about the file size. The script can be used in CGI, PHP or Perl. With this script, you can upload and process long-term large numbers of files, moreover the user interface is clear and friendly. You need not to install any program for this script.

PHP Script for File Uploading has the ability to upload files up to multiple megabytes. Upload speed can be set as fast or as slow as needed.

Configure the PHP Settings

There are a couple of PHP configuration settings that you’ll want to check beforehand for successful file uploads. In this section, we’ll go through every important option in regards to PHP file upload. These options can be configured in the php.ini file.

If you’re not sure where to find your php.ini file, you can use the php_ini_loaded_file() to locate it. Just create a PHP file on your server with the following line, and open it from the browser.

1<?php echo php_ini_loaded_file(); ?>

Here’s an excerpt from a setup file with some useful defaults.

01020304050607080910111213141516171819; Whether to allow HTTP file uploads.file_uploads = On ; Temporary directory for HTTP uploaded files.; Will use system default if not set.;upload_tmp_dir =  ; Maximum allowed size for uploaded files.upload_max_filesize = 16M ; Maximum number of files that can be uploaded via a single requestmax_file_uploads = 20 ; Maximum size of POST data that PHP will accept.post_max_size = 20M max_input_time = 60memory_limit = 128Mmax_execution_time = 30

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 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 (see below).

upload_tmp_dir

Sets a temporary directory which will be used to store uploaded files. In most cases, you 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 what 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, you don’t need to worry about this.

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.

Now let’s build a real-world example to demonstrate file upload in PHP.

The PHP File Upload Script

Next, we’ll handle the backend of the file upload. First, in the same directory, create a new directory called uploads. This will be where our script will save the files.

Then, in the same directory as index.html, create a file called fileUploadScript.php. Notice that this is the same name as the action attribute in the form. Then add this code:

<?php
    $currentDirectory = getcwd();
    $uploadDirectory = "/uploads/";

    $errors = []; // Store errors here

    $fileExtensionsAllowed = ['jpeg','jpg','png']; // These will be the only file extensions allowed 

    $fileName = $_FILES['the_file']['name'];
    $fileSize = $_FILES['the_file']['size'];
    $fileTmpName  = $_FILES['the_file']['tmp_name'];
    $fileType = $_FILES['the_file']['type'];
    $fileExtension = strtolower(end(explode('.',$fileName)));

    $uploadPath = $currentDirectory . $uploadDirectory . basename($fileName); 

    if (isset($_POST['submit'])) {

      if (! in_array($fileExtension,$fileExtensionsAllowed)) {
        $errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
      }

      if ($fileSize > 4000000) {
        $errors[] = "File exceeds maximum size (4MB)";
      }

      if (empty($errors)) {
        $didUpload = move_uploaded_file($fileTmpName, $uploadPath);

        if ($didUpload) {
          echo "The file " . basename($fileName) . " has been uploaded";
        } else {
          echo "An error occurred. Please contact the administrator.";
        }
      } else {
        foreach ($errors as $error) {
          echo $error . "These are the errors" . "\n";
        }
      }

    }
?>

A couple things to note:

  • The key used to access the file from the $_FILES object matches the name attribute used in the form
  • $fileName = $<em>FILES['the</em>file']['name']; – This is the name of the actual file
  • $fileSize = $<em>FILES['the</em>file']['size']; – This is the size of the file in bytes
  • $fileTmpName = $<em>FILES['the</em>file']['tmp_name']; – This is the a temporary file that resides in the tmp directory of the server
  • $fileExtension = strtolower(end(explode('.',$fileName))); – This gets the file extension from the file name
  • $uploadPath = $currentDir . $uploadDirectory . basename($fileName); – This is where the files will be stored on the server. In the script above, it is set to the current working directory

Also note that in the code above, we validate the file upload by checking both the file type and size. (Only png and jpeg files that are less than 4MB)

Now there are a couple final steps before we can start uploading files:

  • Go to your uploads/ directory and make it writable by running: chmod 0755 uploads/
  • Make sure your php.ini file is correctly configured to handle file uploads (Tip: to find your php.ini file, run php --ini):
max_file_uploads = 20
upload_max_filesize = 2M
post_max_size = 8M

Finally, if you now start the PHP server and go to localhost:1234, then upload a file, you should see it save in the uploads folder!

Keep in mind that the all of the code above requires additional security precautions before being released in production. For example, there are currently no checks to see if the user has uploaded a virus disguised as an image. To learn more, check out this article which describes various ways to handle secure file uploads.

Conclusion

This script can be used to upload file in various servers. It supports all types of browsers like IE, Firefox and Opera.

0 Comments

No Comment.