A Script That Upload File to Server

Read Time: 11 mins Languages:

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

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 selection in regards to PHP file upload. These options can be configured in the php.ini file.

If you lot're not sure where to notice yourphp.ini file, you can use thephp_ini_loaded_file() to locate information technology. Just create a PHP file on your server with the following line, and open information technology from the browser.

Here's an extract from a setup file with some useful defaults.

The Key Settings

file_uploads

The value of thefile_uploads directive should be set toOn to permit file uploads. The default value of this directive isOn.

upload_max_filesize

Theupload_max_filesize directive allows you to configure the maximum size of the uploaded file. By default, it'south set to2M (two megabytes), and yous tin can override this setting using the.htaccess file as well. Two megabytes isn't very much past today'south standards, so yous might accept to increase this. If you go an error thatfile exceeds upload_max_filesize when yous try to upload a file, you need to increment this value. If you do, be sure to too increasepost_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 lot don't set it, the system default temp directory will be used.

post_max_size

Thepost_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 theupload_max_filesize directive. For example, if yourupload_max_filesize is16M (16 megabytes), y'all might desire to setpost_max_size to20M.

max_file_uploads

It allows yous to set the maximum number of files that tin exist uploaded at a fourth dimension. The default istwenty, a sensible corporeality.

max_input_time

It'southward the maximum number of seconds a script is allowed to parse the input information. 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

Thememory_limit directive indicates the maximum amount of retention a script can consume. If you're facing problems when uploading big files, y'all demand to make sure that the value of this directive is greater than what you've prepare for the post_max_size directive. The default value is128M (128 megabytes), then unless you lot take a very largepost_max_size andupload_max_filesize, you don't need to worry almost this.

max_execution_time

It'due south the maximum number of seconds a script is immune to run. If you're facing issues when uploading large files, you tin consider increasing this value. xxx (30 seconds) should work well for most apps.

Now allow's build a real-world example to demonstrate file upload in PHP.

Create the HTML Form

Once you've configured the PHP settings, you lot're fix 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 forth, become ahead and download it from GitHub.

We're going to create two PHP files:index.php andupload.php. Theindex.php file holds code which is responsible for displaying the file upload course. On the other hand, theupload.php file is responsible for uploading a file to the server.

Also, a file will be uploaded in theuploaded_files directory, so you need to brand sure that this folder exists and is writable past theweb-server user.

In this section, we'll go through the fundamental parts of theindex.php file.

Let'south take a look at theindex.php file on GitHub:

You can utilise the following CSS to give the form a more than appealing look.

The CSS basically hides the original fileinput and styles its accompanyingspan andcharacterization elements.

Although information technology may look like a typical PHP class, there's an important deviation in the value of theenctype attribute of the<course> tag. Information technology needs to be set tomultipart/course-data since the form contains the file field.

Theenctype attribute specifies the type of encoding which should exist used when the grade is submitted, and it takes one of the following three values:

  • application/ten-www-form-urlencoded: This is the default value when you don't set the value of theenctype aspect explicitly. In this case, characters are encoded before information technology's sent to the server. If you lot don't have the file field in your form, you should apply this value for theenctype attribute.
  • multipart/form-data: When yous apply themultipart/course-information value for theenctype attribute, information technology allows you to upload files using the POST method. Too, it makes sure that the characters are not encoded when the form is submitted.
  • text/patently: This is generally not used. With this setting, the data is sent unencoded.

Next, we output the file field, which allows you lot 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 condition of the file upload, and information technology'll be set in a session variable by theupload.php script. We'll await more at this in the next section.

And then that sums up thealphabetize.php file. In the next section, nosotros'll see how to handle the uploaded file on the server side.

Create the Upload Logic

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

Pull in the lawmaking from theupload.php file on GitHub. We'll go through the of import parts of that file.

In theupload.php file, we've checked whether it's a valid POST asking in the first identify.

In PHP, when a file is uploaded, the$_FILES superglobal variable is populated with all the information well-nigh the uploaded file. It's initialized as an array and may incorporate the following data for successful file upload.

  • tmp_name : The temporary path where the file is uploaded is stored in this variable.
  • name : The bodily name of the file is stored in this variable.
  • size : Indicates the size of the uploaded file in bytes.
  • blazon : 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 y'all tin can compare by using theUPLOAD_ERR_OK abiding.

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

You can run into that the$_FILES variable is a multi-dimensional array, the first element is the name of the file field, and the 2nd element has the data virtually the uploaded file, as nosotros've just discussed to a higher place.

If the file upload is successful, nosotros initialize a few variables with information nigh 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.

Every bit the uploaded file may incorporate spaces and other special characters, information technology's amend to sanitize the filename, and that'due south exactly nosotros've done in the following snippet.

It's important that you restrict the blazon of file which can exist uploaded to certain extensions and don't let everything using the upload grade. Nosotros'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 themove_uploaded_file function to movement the uploaded file to the specific location of our selection.

Themove_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 thealphabetize.php file. Also, we ready the advisable message in the session variable, which will be displayed to users subsequently redirection in thealphabetize.php file.

How Information technology All Works Together

Don't forget to create theuploaded_files directory and brand it writable by thespider web-server user. Next, go alee and run theindex.php file, which should display the file upload form which looks like this:

File Upload UI File Upload UI File Upload UI

Click on theBrowse 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 immune in our script, and click on theUpload button.

That should submit the course, and if everything goes well, you should encounter the uploaded file in theuploaded_files directory. You lot could too endeavor uploading other files with extensions that are not immune, and check if our script prevents such uploads.

Resolving Common Errors

A lot of things can go wrong during a file upload which might result in errors. You tin check the verbal error that occurred during the upload using$_FILES['uploadedFile']['error']. Here is the caption of those errors:

File Is Too Large

UPLOAD_ERR_INI_SIZE andUPLOAD_ERR_FORM_SIZE occur when the size of an uploaded file is more than than the value specified in php.ini or the HTML class respectively. You can become rid of this fault past increasing the upload size limits or letting users know nearly them beforehand.

Temporary Folder Is Missing

UPLOAD_ERR_NO_TMP_DIR is reported when the temporary binder to upload the file is missing.UPLOAD_ERR_NO_FILE is reported when there is no file to upload.

Partial Upload or Tin can't Write to Disk

You lot will getUPLOAD_ERR_PARTIAL if the file could only be uploaded partially andUPLOAD_ERR_CANT_WRITE if the file could not be written to the disk.

A PHP Extension Stopped the File Upload

Sometimes, you lot will get the faultUPLOAD_ERR_EXTENSION because some extension stopped the file upload. This ane will require more investigation by you to effigy out which extension caused the problem.

Here is the total code fromupload.php which volition show users a bulletin on the upload folio in case of success or failure of the upload. The information almost the success or failure of the upload is stored in the$_SESSION['message'].

Learn PHP With a Gratuitous Online Course

Today, we discussed the nuts of file upload in PHP. In the starting time half of the article, we discussed the different configuration options that need to exist in identify for file upload to piece of work. And then we looked at a real-globe example which demonstrated how file upload works in PHP.

If you lot want to learn more PHP, check out our complimentary online course on PHP fundamentals!

In this course, you'll learn the fundamentals of PHP programming. Y'all'll offset with the basics, learning how PHP works and writing simple PHP loops and functions. Then yous'll build upwardly to coding classes for simple object-oriented programming (OOP). Along the manner, you'll acquire all the most important skills for writing apps for the web: y'all'll go a chance to practise responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Did you observe this post useful?

lauerhaffee66.blogspot.com

Source: https://code.tutsplus.com/tutorials/how-to-upload-a-file-in-php-with-example--cms-31763

0 Response to "A Script That Upload File to Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel