How to Get File Name of Upload Php

Read Time: 11 mins Languages:

In this commodity, 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 the PHP Settings

There are a couple of PHP configuration settings that you lot'll desire to check beforehand for successful file uploads. In this department, nosotros'll go through every important choice in regards to PHP file upload. These options tin can be configured in the php.ini file.

If yous're not sure where to find 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.

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

The Key Settings

file_uploads

The value of thefile_uploads directive should exist gear up toOn to let file uploads. The default value of this directive isOn.

upload_max_filesize

Theupload_max_filesize directive allows yous to configure the maximum size of the uploaded file. By default, it'southward prepare to2M (two megabytes), and yous can override this setting using the.htaccess file as well. Two megabytes isn't very much by today's standards, and so you might have to increment this. If y'all get an error thatfile exceeds upload_max_filesize when you try to upload a file, you need to increase this value. If you do, exist sure to also incrementpost_max_size (see below).

upload_tmp_dir

Sets a temporary directory which will be used to store uploaded files. In about cases, you don't need to worry almost this setting. If you 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 lot've set for theupload_max_filesize directive. For case, if yourupload_max_filesize is16M (xvi megabytes), yous might desire to preparepost_max_size to20M.

max_file_uploads

Information technology allows y'all to gear up the maximum number of files that tin be uploaded at a time. The default is20, 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 yous're dealing with large file uploads.60 (sixty seconds) is a skilful value for most apps.

memory_limit

Thememory_limit directive indicates the maximum amount of retention a script can consume. If you're facing bug when uploading big files, you demand to brand sure that the value of this directive is greater than what you lot've fix for the post_max_size directive. The default value is128M (128 megabytes), so unless you have a very bigpost_max_size andupload_max_filesize, you don't need to worry about 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 big files, you can consider increasing this value. 30 (30 seconds) should work well for most apps.

Now allow'southward build a real-globe instance to demonstrate file upload in PHP.

Create the HTML Class

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

Our GitHub repo has some sample code which I'one thousand going to hash out throughout this article. So, if you lot desire to follow along, go ahead and download information technology from GitHub.

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

As well, a file volition be uploaded in theuploaded_files directory, so you need to make sure that this folder exists and is writable by theweb-server user.

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

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

You tin use the following CSS to give the course a more than appealing look.

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

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

Theenctype attribute specifies the type of encoding which should be used when the form is submitted, and it takes ane of the post-obit iii values:

  • application/ten-world wide web-course-urlencoded: This is the default value when you don't set up the value of theenctype attribute explicitly. In this instance, characters are encoded earlier it's sent to the server. If you don't accept the file field in your form, you should use this value for theenctype attribute.
  • multipart/grade-data: When you lot apply themultipart/form-data value for theenctype attribute, it allows yous to upload files using the Postal service method. Also, it makes certain that the characters are not encoded when the form is submitted.
  • text/patently: This is generally non 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.

Autonomously from that, nosotros've displayed a message at the top of the course. 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 look more at this in the next section.

And then that sums up theindex.php file. In the adjacent section, we'll see how to handle the uploaded file on the server side.

Create the Upload Logic

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

Pull in the lawmaking from theupload.php file on GitHub. Nosotros'll get through the important parts of that file.

In theupload.php file, nosotros've checked whether it's a valid Post asking in the get-go 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 blazon of the uploaded file.
  • error : If there'southward an mistake during file upload, this variable is populated with the advisable error message. In the case of successful file upload, it contains 0, which you can compare by using theUPLOAD_ERR_OK constant.

Later validating the POST request, nosotros cheque that the file upload was successful.

You lot can see that the$_FILES variable is a multi-dimensional assortment, the outset element is the name of the file field, and the second element has the information about the uploaded file, as we've just discussed to a higher place.

If the file upload is successful, we initialize a few variables with data 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 comprise spaces and other special characters, it'due south ameliorate to sanitize the filename, and that'due south exactly we've washed in the following snippet.

Information technology'southward important that you restrict the blazon of file which tin can exist uploaded to certain extensions and don't let everything using the upload form. Nosotros've done that by checking the extension of the uploaded file with a set of extensions that nosotros want to allow for uploading.

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

Themove_uploaded_file part takes two arguments. The starting time argument is the filename of the uploaded file, and the second statement is the destination path where you desire to motion the file.

Finally, we redirect the user to theindex.php file. Also, nosotros fix the advisable message in the session variable, which will exist displayed to users after redirection in theindex.php file.

How It All Works Together

Don't forget to create theuploaded_files directory and make it writable by theweb-server user. Next, get ahead and run thealphabetize.php file, which should display the file upload grade 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 allowed in our script, and click on theUpload button.

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

Resolving Mutual Errors

A lot of things can get incorrect during a file upload which might result in errors. You can check the exact error that occurred during the upload using$_FILES['uploadedFile']['error']. Here is the explanation 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 the value specified in php.ini or the HTML form respectively. You lot can get rid of this fault past increasing the upload size limits or letting users know about them beforehand.

Temporary Binder 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 can't Write to Disk

Yous 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 volition become the errorUPLOAD_ERR_EXTENSION because some extension stopped the file upload. This one will require more than investigation by you to figure out which extension acquired the problem.

Here is the total code fromupload.php which will evidence users a message on the upload page 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 Course

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

If you lot want to learn more PHP, cheque out our free online grade on PHP fundamentals!

In this course, you'll learn the fundamentals of PHP programming. Y'all'll showtime with the basics, learning how PHP works and writing simple PHP loops and functions. And so you'll build upwards to coding classes for simple object-oriented programming (OOP). Forth the way, you'll learn all the most of import skills for writing apps for the web: you'll become a gamble to exercise responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Did you find this mail service useful?

mooreknorted.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 File Name of Upload Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel