Upload And Files With Php

Posted By admin On 10.01.20

In this article, I’ll explain the basics of file upload in PHP. Firstly, we’ll go through the PHP configuration options that need to be in place for successful file uploads. Following that, we’ll develop a real-world example of how to upload a file.

Configure 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 each and every option which is important in regards to PHP file upload. These options can be configured in the php.ini file.

I create a lot of websites that allow administrators to upload files to their own website. Since allowing user customization has become more and more important on websites these days, I thought I'd share how easy it is to handle file uploads in PHP. 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.

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.

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

The Key Settings

file_uploads

Upload file with php codeigniter

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.

Download ElanTech Touchpad Driver 8.0.7.0. OS support: Windows XP/Vista/7. Category: Input Devices. Free Download Samsung NP-R540-JA04US Elantech Touchpad Driver 7.0.7.0 for Windows 7 (Keyboard & Mouse). The package provides the installation files for Samsung Elan TouchPad Input Device Driver version 11.7.32.4. If the driver is already installed on your system, updating (overwrite-installing) may fix various issues, add new functions, or just upgrade to the available version. Elantech touchpad driver windows 7. Solved touchpad, Elantech, Elan not working or responsive issues. It usually happens after Windows 10 upgrade. You just need to update its driver to fix it. Download ElanTech Touchpad Driver 11.5.0.9 for Windows 7 32-bit. OS support: Windows 7. Category: Input Devices.

memory_limit

The memory_limit directive indicates the maximum amount of memory a script can consume. If you're facing issues during upload of 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 during upload of 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.

Create the HTML Form

Once you’ve configured the PHP settings, you're ready to try out the PHP file upload capabilities.

Our GitHub repo has some sample code which I'm going to discuss throughout this article. So, if you want to follow along, go ahead and download it from GitHub.

We’re going to create two PHP files: index.php and upload.php. The index.php file holds code which is responsible for displaying the file upload form. On the other hand, the upload.php file is responsible for uploading a file to the server.

Also, a file will be uploaded in the uploaded_files directory, so you need to make sure that this folder exists and is writable by the web-server user.

In this section, we’ll go through the key parts of the index.php file.

Let’s take a look at the index.php file on GitHub:

Although it may look like a typical PHP form, there’s an important difference in the value of the enctype attribute of the <form> tag. It needs to be set to multipart/form-data since the form contains the file field.

The enctype attribute specifies the type of encoding which should be used when the form is submitted, and it takes one of the following three values:

  • application/x-www-form-urlencoded: This is the default value when you don’t set the value of the enctype attribute explicitly. In this case, characters are encoded before it’s sent to the server. If you don’t have the file field in your form, you should use this value for the enctype attribute.
  • multipart/form-data: When you use the multipart/form-data value for the enctypeattribute, it allows you to upload files using the POST method. Also, it makes sure that the characters are not encoded when the form is submitted.
  • text/plain: This is generally not used. With this setting, the data is sent unencoded.

Next, we output the file field, which allows you to select a file from your computer.

Apart from that, we’ve displayed a message at the top of the form. This message shows the status of the file upload, and it’ll be set in a session variable by the upload.php script. We’ll look more at this in the next section.

So that sums up the index.php file. In the next section, we’ll see how to handle the uploaded file on the server side.

Create the Upload Logic

In the previous section, we created the HTML form which is displayed on the client side and allows you to upload a file from your computer. In this section, we’ll see the server-side counterpart which allows you to handle the uploaded file.

Pull in the code from the upload.php file on GitHub. We’ll go through the important parts of that file.

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

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.

  • tmp_name: The temporary path where the file is uploaded is stored in this variable.
  • name: The actual name of the file is stored in this variable.
  • size: Indicates the size of the uploaded file in bytes.
  • type: Contains the mime type of the uploaded file.
  • error: If there’s an error during file upload, this variable is populated with the appropriate error message. 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.

You can see that 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, as we’ve just discussed above.

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

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.

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.

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

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.

Finally, we redirect the user to the index.php file. Also, we set the appropriate message in the session variable, which will be displayed to users after redirection in the index.php file.

How It All Works Together

Don't forget to create the uploaded_files directory and make it writable by the web-server user. Next, go ahead and run the index.php file, which should display the file upload form which looks like this:

Click on the Browse button—that should open a dialog box which allows you to select a file from your computer. Select a file with one of the extensions allowed in our script, and click on the Upload button.

That should submit the form, and if everything goes well, you should see the uploaded file in the uploaded_files directory. You could also try uploading other files with extensions that are not allowed, and check if our script prevents such uploads.

Conclusion

Today, we discussed the basics of file upload in PHP. In the first half of the article, we discussed the different configuration options that need to be in place for file upload to work. Then we looked at a real-world example which demonstrated how file upload works in PHP.

I hope you’ve enjoyed this article, and feel free to post your queries and suggestions below!

Active2 months ago

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.

This is my HTML part:

and this is my JS jquery script:

There is a folder named 'uploads' in the root directory of the website, with change permissions for 'users' and 'IIS_users'.

When I select a file with the file-form and press the upload button, the first alert returns '[object FormData]'. the second alert doesn't get called and the'uploads' folder is empty too!?

Can someone help my finding out whats wrong?

Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.

user2355509user2355509
7182 gold badges8 silver badges11 bronze badges

How To Open Files With Php

6 Answers

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.

Your HTML is fine, but update your JS jQuery script to look like this:

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that runs on the server and directs the file to the uploads directory:

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

bloodyKnucklesbloodyKnuckles
7,6953 gold badges19 silver badges33 bronze badges
AzharAzhar
Hasib KamalHasib Kamal

and this is the php file to receive the uplaoded files

Mr.Web
3,2666 gold badges31 silver badges63 bronze badges
kavehmbkavehmb
6,1111 gold badge12 silver badges20 bronze badges

Use pure js

The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending

Kamil KiełczewskiKamil Kiełczewski
20.7k8 gold badges98 silver badges115 bronze badges

Best File Upload Using Jquery Ajax With MaterialiseClick Here to Download

Upload Multiple Files With Php

When you select image the image will be Converted in base 64 and you can store this in to database so it will be light weight also.

Bin File Upload Php

Urshit ShethUrshit Sheth

protected by CommunityNov 13 '15 at 22:11

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?

Upload Files With Php

Not the answer you're looking for? Browse other questions tagged javascriptphpjqueryajaxupload or ask your own question.