Input File Upload of Same Name in Php W3schools

Read Fourth dimension: 11 mins Languages:

In this article, I'll explicate the basics of file upload in PHP. Firstly, we'll become through the PHP configuration options that need to be in identify 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'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 tin can be configured in the php.ini file.

If you're not sure where to find yourphp.ini file, you lot can utilise thephp_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's an excerpt from a setup file with some useful defaults.

The Key Settings

file_uploads

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

upload_max_filesize

Theupload_max_filesize directive allows y'all to configure the maximum size of the uploaded file. By default, information technology'southward ready to2M (two megabytes), and you tin can override this setting using the.htaccess file too. Two megabytes isn't very much by today'south standards, so you might have to increase this. If you get an fault thatfile exceeds upload_max_filesize when you try to upload a file, you need to increment this value. If you lot do, be sure to as well increasepost_max_size (see beneath).

upload_tmp_dir

Sets a temporary directory which will exist used to store uploaded files. In about cases, you don't need to worry virtually this setting. If yous don't set up it, the arrangement default temp directory will be used.

post_max_size

Thepost_max_size directive allows y'all to configure the maximum size of POST data. Since files are uploaded with POST requests, this value must be greater than what you've gear up for theupload_max_filesize directive. For example, if yourupload_max_filesize is16M (16 megabytes), you might desire to set uppost_max_size to20M.

max_file_uploads

It allows yous to ready the maximum number of files that tin can exist uploaded at a fourth dimension. 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. Yous should set it to a reasonable value if you're dealing with large file uploads.60 (60 seconds) is a good value for nearly apps.

memory_limit

Thememory_limit directive indicates the maximum amount of memory a script can consume. If y'all're facing issues when uploading large files, y'all need to make certain that the value of this directive is greater than what you've set for the post_max_size directive. The default value is128M (128 megabytes), so unless yous accept a very largepost_max_size andupload_max_filesize, y'all don't demand to worry about this.

max_execution_time

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

At present let'due south build a real-world example to demonstrate file upload in PHP.

Create the HTML Course

In one case y'all've configured the PHP settings, you lot're set up to attempt out the PHP file upload capabilities.

Our GitHub repo has some sample lawmaking which I'thou going to discuss throughout this commodity. So, if you want to follow along, become alee and download it from GitHub.

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

Too, 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 cardinal parts of theindex.php file.

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

Yous can use the post-obit CSS to requite the form a more than highly-seasoned look.

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

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

Theenctype attribute specifies the type of encoding which should exist used when the form 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 ready the value of theenctype aspect explicitly. In this case, characters are encoded earlier it's sent to the server. If you don't accept the file field in your course, you should employ this value for theenctype attribute.
  • multipart/class-data: When you apply themultipart/form-data value for theenctype aspect, information technology allows you to upload files using the Post method. Also, it makes sure that the characters are non encoded when the class is submitted.
  • text/plain: This is generally non used. With this setting, the information is sent unencoded.

Adjacent, nosotros 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 condition of the file upload, and it'll exist set in a session variable by theupload.php script. We'll look more at this in the side by side section.

So that sums up thealphabetize.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 yous to upload a file from your estimator. In this section, we'll come across the server-side counterpart which allows you 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'southward 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 assortment and may comprise the following data for successful file upload.

  • tmp_name : The temporary path where the file is uploaded is stored in this variable.
  • proper name : The actual proper 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.
  • mistake : If there's an error during file upload, this variable is populated with the appropriate fault message. In the case of successful file upload, information technology contains 0, which y'all tin compare by using theUPLOAD_ERR_OK constant.

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

You lot tin can meet that the$_FILES variable is a multi-dimensional array, the first chemical element is the name of the file field, and the 2nd chemical element has the information most the uploaded file, as we've but discussed above.

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

In the above snippet, nosotros've as well figured out the extension of the uploaded file and stored it in the$fileExtension variable.

Equally the uploaded file may comprise spaces and other special characters, information technology'south better to sanitize the filename, and that'south exactly nosotros've done in the following snippet.

It's important that you lot restrict the type of file which can be uploaded to certain extensions and don't let everything using the upload form. We've done that by checking the extension of the uploaded file with a set up of extensions that nosotros want to let for uploading.

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

Themove_uploaded_file function takes two arguments. The first argument is the filename of the uploaded file, and the second statement is the destination path where you want to move the file.

Finally, we redirect the user to theindex.php file. Likewise, we set the appropriate message in the session variable, which will be 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, become 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 push button—that should open up a dialog box which allows y'all to select a file from your calculator. Select a file with one 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. You lot could besides effort uploading other files with extensions that are not allowed, and check if our script prevents such uploads.

Resolving Mutual Errors

A lot of things tin can go incorrect during a file upload which might outcome in errors. You tin can check the exact error that occurred during the upload using$_FILES['uploadedFile']['fault']. 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 than the value specified in php.ini or the HTML grade respectively. You can become rid of this error by increasing the upload size limits or letting users know most 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 Can't Write to Disk

You volition becomeUPLOAD_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 will go the mistakeUPLOAD_ERR_EXTENSION considering some extension stopped the file upload. This 1 will require more investigation past y'all to figure out which extension caused the problem.

Here is the full lawmaking fromupload.php which will show users a message on the upload page in case of success or failure of the upload. The data almost the success or failure of the upload is stored in the$_SESSION['bulletin'].

Learn PHP With a Complimentary Online Grade

Today, we discussed the nuts 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 nosotros looked at a real-world example which demonstrated how file upload works in PHP.

If you desire to learn more PHP, check out our gratuitous online grade on PHP fundamentals!

In this course, you'll learn the fundamentals of PHP programming. Y'all'll kickoff with the basics, learning how PHP works and writing simple PHP loops and functions. So you'll build upwards to coding classes for simple object-oriented programming (OOP). Along the fashion, you'll learn all the most of import skills for writing apps for the web: you'll become a chance to practice responding to GET and Postal service requests, parsing JSON, authenticating users, and using a MySQL database.

Did you notice this mail service useful?

myerstacept72.blogspot.com

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

0 Response to "Input File Upload of Same Name in Php W3schools"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel