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.
<?php echo php_ini_loaded_file(); ?>
Here's an excerpt from a setup file with some useful defaults.
; Whether to allow HTTP file uploads. file_uploads = On ; Temporary directory for HTTP uploaded files. ; Will use organization default if not ready. ;upload_tmp_dir = ; Maximum allowed size for uploaded files. upload_max_filesize = 16M ; Maximum number of files that tin can be uploaded via a unmarried asking max_file_uploads = xx ; Maximum size of Post data that PHP will have. post_max_size = 20M max_input_time = 60 memory_limit = 128M max_execution_time = 30
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:
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>PHP File Upload</title> </head> <body> <?php if (isset($_SESSION['message']) && $_SESSION['bulletin']) { echo '<p course="notification">'.$_SESSION['bulletin']).'</p>'; unset($_SESSION['bulletin']); } ?> <form method="Mail" action="upload.php" enctype="multipart/form-information"> <div form="upload-wrapper"> <span course="file-name">Choose a file...</bridge> <label for="file-upload">Browse<input type="file" id="file-upload" name="uploadedFile"></label> </div> <input type="submit" proper name="uploadBtn" value="Upload" /> </class> </body> </html> Yous can use the post-obit CSS to requite the form a more than highly-seasoned look.
div.upload-wrapper { color: white; font-weight: bold; display: flex; } input[type="file"] { position: absolute; left: -9999px; } input[type="submit"] { border: 3px solid #555; color: white; background: #666; margin: 10px 0; border-radius: 5px; font-weight: bold; padding: 5px 20px; cursor: pointer; } input[type="submit"]:hover { groundwork: #555; } label[for="file-upload"] { padding: 0.7rem; brandish: inline-block; background: #fa5200; cursor: pointer; border: 3px solid #ca3103; border-radius: 0 5px 5px 0; border-left: 0; } label[for="file-upload"]:hover { background: #ca3103; } bridge.file-name { padding: 0.7rem 3rem 0.7rem 0.7rem; white-space: nowrap; overflow: hidden; background: #ffb543; color: black; edge: 3px solid #f0980f; edge-radius: 5px 0 0 5px; border-right: 0; } 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 theenctypeaspect 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 theenctypeattribute. -
multipart/class-data: When you apply themultipart/form-datavalue for theenctypeaspect, 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.
<input type="file" name="uploadedFile" />
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.
<?php if (isset($_SESSION['message']) && $_SESSION['message']) { echo '<p form="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?> 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.
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload') { ... } 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_OKconstant.
After validating the POST request, we check that the file upload was successful.
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['fault'] === UPLOAD_ERR_OK) { ... } 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.
// get details of the uploaded file $fileTmpPath = $_FILES['uploadedFile']['tmp_name']; $fileName = $_FILES['uploadedFile']['name']; $fileSize = $_FILES['uploadedFile']['size']; $fileType = $_FILES['uploadedFile']['type']; $fileNameCmps = explode(".", $fileName); $fileExtension = strtolower(end($fileNameCmps)); 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.
$newFileName = md5(fourth dimension() . $fileName) . '.' . $fileExtension;
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.
$allowedfileExtensions = array('jpg', 'gif', 'png', 'zero', 'txt', 'xls', 'md'); if (in_array($fileExtension, $allowedfileExtensions)) { ... } Finally, we use themove_uploaded_file part to move the uploaded file to the specific location of our choice.
// directory in which the uploaded file volition be moved $uploadFileDir = './uploaded_files/'; $dest_path = $uploadFileDir . $newFileName; if(move_uploaded_file($fileTmpPath, $dest_path)) { $bulletin ='File is successfully uploaded.'; } else { $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.'; } 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:
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'].
<?php session_start(); $message = ''; if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload') { if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK) { // get details of the uploaded file $fileTmpPath = $_FILES['uploadedFile']['tmp_name']; $fileName = $_FILES['uploadedFile']['name']; $fileSize = $_FILES['uploadedFile']['size']; $fileType = $_FILES['uploadedFile']['type']; $fileNameCmps = explode(".", $fileName); $fileExtension = strtolower(end($fileNameCmps)); // sanitize file-proper name $newFileName = md5(time() . $fileName) . '.' . $fileExtension; // check if file has one of the post-obit extensions $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc'); if (in_array($fileExtension, $allowedfileExtensions)) { // directory in which the uploaded file will be moved $uploadFileDir = './uploaded_files/'; $dest_path = $uploadFileDir . $newFileName; if(move_uploaded_file($fileTmpPath, $dest_path)) { $message ='File is successfully uploaded.'; } else { $message = 'There was some mistake moving the file to upload directory. Please make sure the upload directory is writable by spider web server.'; } } else { $message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions); } } else { $message = 'There is some error in the file upload. Please check the following fault.<br>'; $message .= 'Error:' . $_FILES['uploadedFile']['error']; } } $_SESSION['bulletin'] = $message; header("Location: index.php"); 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?
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