How to Get Full Path of Uploaded File in Php

Read Time: eleven mins Languages:

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

Configure the PHP Settings

There are a couple of PHP configuration settings that yous'll want to bank 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 yous're not sure where to detect yourphp.ini file, you can use thephp_ini_loaded_file() to locate it. Just create a PHP file on your server with the following line, and open information technology from the browser.

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

The Key Settings

file_uploads

The value of thefile_uploads directive should be ready toOn to allow 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 you tin override this setting using the.htaccess file likewise. Two megabytes isn't very much past today'southward standards, so you might accept to increase this. If you get an fault thatfile exceeds upload_max_filesize when you try to upload a file, you need to increase this value. If yous do, be certain to likewise increasepost_max_size (see below).

upload_tmp_dir

Sets a temporary directory which volition be used to shop uploaded files. In most cases, you don't need to worry near this setting. If you lot don't fix it, the organisation default temp directory will exist used.

post_max_size

Thepost_max_size directive allows you to configure the maximum size of Mail service information. Since files are uploaded with POST requests, this value must exist greater than what you've set for theupload_max_filesize directive. For example, if yourupload_max_filesize is16M (16 megabytes), you might want to gear uppost_max_size to20M.

max_file_uploads

It allows you to fix the maximum number of files that tin exist uploaded at a time. The default is20, a sensible amount.

max_input_time

It'southward the maximum number of seconds a script is allowed to parse the input data. You should set up it to a reasonable value if you lot're dealing with large file uploads.lx (lx seconds) is a good value for nearly apps.

memory_limit

Thememory_limit directive indicates the maximum amount of memory a script tin consume. If you're facing issues when uploading big files, you need to make sure that the value of this directive is greater than what you've gear up for the post_max_size directive. The default value is128M (128 megabytes), so unless y'all have a very largepost_max_size andupload_max_filesize, you lot don't need to worry about this.

max_execution_time

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

Now let's build a real-world case to demonstrate file upload in PHP.

Create the HTML Form

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

Our GitHub repo has some sample code which I'g going to discuss throughout this article. And so, if you lot want to follow forth, go ahead and download it from GitHub.

Nosotros're going to create 2 PHP files:index.php andupload.php. Thealphabetize.php file holds code which is responsible for displaying the file upload form. On the other hand, theupload.php file is responsible for uploading a file to the server.

As well, a file will be uploaded in theuploaded_files directory, then you need to brand sure that this folder exists and is writable by thespider web-server user.

In this department, nosotros'll go through the key parts of theindex.php file.

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

Yous can use the following CSS to give the class a more than appealing wait.

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

Although it may wait similar a typical PHP form, there'due south an important deviation in the value of theenctype attribute of the<course> tag. It needs to be set tomultipart/form-data since the class contains the file field.

Theenctype aspect specifies the type of encoding which should be used when the form is submitted, and it takes one of the post-obit three values:

  • application/ten-www-course-urlencoded: This is the default value when yous don't set the value of theenctype aspect 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 theenctype attribute.
  • multipart/class-information: When y'all utilise themultipart/grade-data value for theenctype aspect, it allows you to upload files using the Mail method. Also, information technology makes sure that the characters are not encoded when the form is submitted.
  • text/plain: This is generally non 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 calculator.

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 theupload.php script. We'll look more than at this in the next section.

So that sums up theindex.php file. In the next department, we'll run across how to handle the uploaded file on the server side.

Create the Upload Logic

In the previous department, we created the HTML class which is displayed on the client side and allows you to upload a file from your reckoner. In this section, we'll see the server-side counterpart which allows y'all to handle the uploaded file.

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

In theupload.php file, we've checked whether it's a valid Mail service 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 incorporate the following information for successful file upload.

  • tmp_name : The temporary path where the file is uploaded is stored in this variable.
  • proper noun : The bodily 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 fault message. In the example of successful file upload, it contains 0, which you can compare by using theUPLOAD_ERR_OK constant.

After validating the POST request, nosotros 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 proper name of the file field, and the second element has the information about the uploaded file, every bit nosotros've but discussed to a higher place.

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

In the above snippet, we've also figured out the extension of the uploaded file and stored information technology in the$fileExtension variable.

As the uploaded file may incorporate spaces and other special characters, information technology's better to sanitize the filename, and that's exactly we've done in the post-obit snippet.

Information technology's important that you restrict the blazon of file which can be uploaded to certain extensions and don't allow everything using the upload class. Nosotros've washed that past checking the extension of the uploaded file with a set of extensions that we want to allow for uploading.

Finally, we utilize themove_uploaded_file function to motility the uploaded file to the specific location of our choice.

Themove_uploaded_file office takes two arguments. The beginning argument is the filename of the uploaded file, and the second argument is the destination path where yous want to move the file.

Finally, we redirect the user to theindex.php file. Also, we set up the appropriate message in the session variable, which volition be displayed to users later redirection in theindex.php file.

How It All Works Together

Don't forget to create theuploaded_files directory and get in writable by theweb-server user. Next, get ahead 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 theScan button—that should open a dialog box which allows you to select a file from your calculator. Select a file with i of the extensions allowed in our script, and click on theUpload button.

That should submit the form, and if everything goes well, you should see the uploaded file in theuploaded_files directory. Y'all could also try uploading other files with extensions that are non immune, and cheque if our script prevents such uploads.

Resolving Common Errors

A lot of things can go wrong during a file upload which might outcome in errors. You lot can cheque the exact error that occurred during the upload using$_FILES['uploadedFile']['error']. Here is the explanation of those errors:

File Is Too Big

UPLOAD_ERR_INI_SIZE andUPLOAD_ERR_FORM_SIZE occur when the size of an uploaded file is more than the value specified in php.ini or the HTML form respectively. You can get rid of this mistake by increasing the upload size limits or letting users know about them beforehand.

Temporary Folder Is Missing

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

Partial Upload or Tin't Write to Disk

You lot will getUPLOAD_ERR_PARTIAL if the file could merely exist uploaded partially andUPLOAD_ERR_CANT_WRITE if the file could non be written to the deejay.

A PHP Extension Stopped the File Upload

Sometimes, you volition go the errorUPLOAD_ERR_EXTENSION because some extension stopped the file upload. This one will require more than investigation past you to figure out which extension caused the problem.

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

Learn PHP With a Free Online Class

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

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

In this course, you'll larn the fundamentals of PHP programming. You lot'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then yous'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a risk to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Did you find this post useful?

duffyraltals.blogspot.com

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

0 Response to "How to Get Full Path of Uploaded File in Php"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel