content type of the uploaded file in PHP?
Read Time: eleven mins Languages:
In this commodity, I'll explicate the nuts of file upload in PHP. Firstly, we'll get through the PHP configuration options that need to be in place for successful file uploads. Post-obit that, we'll develop a real-globe example of how to upload a file.
Configure the PHP Settings
There are a couple of PHP configuration settings that you lot'll want to 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 you'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 it from the browser.
<?php echo php_ini_loaded_file(); ?>
Here'south an excerpt from a setup file with some useful defaults.
; Whether to let HTTP file uploads. file_uploads = On ; Temporary directory for HTTP uploaded files. ; Will use organisation default if not gear up. ;upload_tmp_dir = ; Maximum allowed size for uploaded files. upload_max_filesize = 16M ; Maximum number of files that tin be uploaded via a single request max_file_uploads = 20 ; Maximum size of POST data that PHP will accept. 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 be set 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, information technology'southward set to2M
(two megabytes), and you tin override this setting using the.htaccess file also. Ii megabytes isn't very much by today's standards, and so yous might have to increment this. If you get an error thatfile exceeds upload_max_filesize
when you try to upload a file, you demand to increase this value. If you do, be sure to besides increasepost_max_size
(run across below).
upload_tmp_dir
Sets a temporary directory which will be used to store uploaded files. In nearly cases, you don't need to worry about this setting. If you don't set it, the organisation default temp directory volition be used.
post_max_size
Thepost_max_size
directive allows yous 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 case, if yourupload_max_filesize
is16M
(16 megabytes), y'all might want to setpost_max_size
to20M
.
max_file_uploads
Information technology allows you to set the maximum number of files that tin exist uploaded at a time. The default is20
, a sensible amount.
max_input_time
It'south the maximum number of seconds a script is allowed to parse the input data. You should set information technology to a reasonable value if you lot're dealing with large file uploads.60
(60 seconds) is a good value for most apps.
memory_limit
Thememory_limit
directive indicates the maximum corporeality of memory a script tin consume. If you're facing problems when uploading large files, y'all need to brand sure that the value of this directive is greater than what y'all've set for the post_max_size
directive. The default value is128M
(128 megabytes), so unless you have a very largepost_max_size
andupload_max_filesize
, you don't need to worry about this.
max_execution_time
It's the maximum number of seconds a script is allowed to run. If you lot're facing issues when uploading large files, yous can consider increasing this value. 30
(30 seconds) should work well for most apps.
Now let's build a real-earth instance to demonstrate file upload in PHP.
Create the HTML Form
Once you've configured the PHP settings, you're prepare to try out the PHP file upload capabilities.
Our GitHub repo has some sample lawmaking which I'm going to discuss throughout this article. So, if y'all want to follow along, become ahead and download it from GitHub.
We're going to create ii 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, then you demand to make sure that this binder exists and is writable past theweb-server
user.
In this section, we'll get through the key parts of thealphabetize.php file.
Let's take a await at theindex.php file on GitHub:
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <championship>PHP File Upload</title> </head> <trunk> <?php if (isset($_SESSION['message']) && $_SESSION['message']) { echo '<p class="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?> <class method="Postal service" action="upload.php" enctype="multipart/form-information"> <div grade="upload-wrapper"> <span class="file-proper noun">Choose a file...</bridge> <label for="file-upload">Browse<input type="file" id="file-upload" name="uploadedFile"></characterization> </div> <input blazon="submit" name="uploadBtn" value="Upload" /> </form> </body> </html>
You can utilize the following CSS to give the form a more appealing look.
div.upload-wrapper { color: white; font-weight: bold; display: flex; } input[type="file"] { position: absolute; left: -9999px; } input[type="submit"] { edge: 3px solid #555; colour: white; background: #666; margin: 10px 0; border-radius: 5px; font-weight: bold; padding: 5px 20px; cursor: arrow; } input[blazon="submit"]:hover { background: #555; } label[for="file-upload"] { padding: 0.7rem; display: inline-block; groundwork: #fa5200; cursor: arrow; edge: 3px solid #ca3103; border-radius: 0 5px 5px 0; border-left: 0; } characterization[for="file-upload"]:hover { groundwork: #ca3103; } span.file-name { padding: 0.7rem 3rem 0.7rem 0.7rem; white-space: nowrap; overflow: hidden; groundwork: #ffb543; color: black; border: 3px solid #f0980f; border-radius: 5px 0 0 5px; border-correct: 0; }
The CSS basically hides the original fileinput
and styles its accompanyingspan
andlabel
elements.
Although it may look like a typical PHP form, in that location'south an important departure in the value of theenctype
aspect of the<form>
tag. It needs to be set tomultipart/form-information
since the form contains the file field.
Theenctype
aspect specifies the blazon of encoding which should be used when the grade is submitted, and it takes 1 of the following three values:
-
application/ten-world wide web-grade-urlencoded
: This is the default value when you don't set the value of theenctype
attribute explicitly. In this instance, characters are encoded before it'southward sent to the server. If you don't accept the file field in your form, you should use this value for theenctype
aspect. -
multipart/course-data
: When you use themultipart/form-information
value for theenctype
attribute, information technology allows you lot to upload files using the POST method. Too, it makes certain that the characters are non encoded when the form is submitted. -
text/plain
: This is more often than not not used. With this setting, the information is sent unencoded.
Next, nosotros output the file field, which allows you to select a file from your computer.
<input type="file" proper name="uploadedFile" />
Apart from that, we've displayed a message at the top of the class. This bulletin shows the status of the file upload, and information technology'll be set in a session variable past theupload.php script. We'll look more than at this in the next department.
<?php if (isset($_SESSION['message']) && $_SESSION['bulletin']) { echo '<p class="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?>
So that sums up theindex.php file. In the next department, we'll encounter 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 to upload a file from your computer. In this section, we'll see the server-side analogue 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, nosotros've checked whether information technology's a valid Mail 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 data about the uploaded file. It'southward initialized as an assortment 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 proper name of the file is stored in this variable. -
size
: Indicates the size of the uploaded file in bytes. -
blazon
: Contains the mime blazon of the uploaded file. -
error
: If in that location'south an error during file upload, this variable is populated with the appropriate error bulletin. In the instance of successful file upload, it contains 0, which y'all can compare past using theUPLOAD_ERR_OK
constant.
After validating the POST request, we check that the file upload was successful.
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['fault'] === UPLOAD_ERR_OK) { ... }
You can see that the$_FILES
variable is a multi-dimensional array, the start element is the name of the file field, and the 2d element has the information almost the uploaded file, equally nosotros've just discussed above.
If the file upload is successful, nosotros initialize a few variables with information most the uploaded file.
// go 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, we've also figured out the extension of the uploaded file and stored it in the$fileExtension
variable.
Every bit the uploaded file may contain spaces and other special characters, information technology'south amend to sanitize the filename, and that's exactly we've done in the following snippet.
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
Information technology's important that you restrict the type of file which can exist uploaded to certain extensions and don't allow everything using the upload form. We've done that past checking the extension of the uploaded file with a set up of extensions that we want to allow for uploading.
$allowedfileExtensions = assortment('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc'); if (in_array($fileExtension, $allowedfileExtensions)) { ... }
Finally, we use themove_uploaded_file
function to move the uploaded file to the specific location of our choice.
// directory in which the uploaded file volition exist 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 error moving the file to upload directory. Please make sure the upload directory is writable by web server.'; }
Themove_uploaded_file
function takes ii arguments. The first argument is the filename of the uploaded file, and the 2d argument is the destination path where yous want to move the file.
Finally, we redirect the user to thealphabetize.php file. As well, we set the appropriate message in the session variable, which will be displayed to users later on redirection in theindex.php file.
How It All Works Together
Don't forget to create theuploaded_files directory and brand it writable by theweb-server user. Adjacent, go ahead and run thealphabetize.php file, which should display the file upload form which looks like this:
Click on theBrowse button—that should open a dialog box which allows you to select a file from your computer. Select a file with 1 of the extensions immune in our script, and click on theUpload button.
That should submit the form, and if everything goes well, you lot should see the uploaded file in theuploaded_files directory. You could also try uploading other files with extensions that are not allowed, and check if our script prevents such uploads.
Resolving Common Errors
A lot of things tin can go incorrect during a file upload which might upshot in errors. You lot tin bank check the exact mistake that occurred during the upload using$_FILES['uploadedFile']['error']
. Hither 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 the value specified in php.ini or the HTML form respectively. You lot can go rid of this mistake by 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.
Fractional Upload or Can't Write to Disk
You will getUPLOAD_ERR_PARTIAL
if the file could only exist 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 get the errorUPLOAD_ERR_EXTENSION
because some extension stopped the file upload. This one volition crave more investigation by you to effigy out which extension caused the problem.
Here is the full lawmaking fromupload.php which will testify users a message on the upload page in instance of success or failure of the upload. The information about the success or failure of the upload is stored in the$_SESSION['message']
.
<?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(finish($fileNameCmps)); // sanitize file-name $newFileName = md5(time() . $fileName) . '.' . $fileExtension; // check if file has i of the post-obit extensions $allowedfileExtensions = array('jpg', 'gif', 'png', 'goose egg', '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 error moving the file to upload directory. Please brand certain the upload directory is writable by web server.'; } } else { $bulletin = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions); } } else { $message = 'There is some error in the file upload. Please bank check the following error.<br>'; $bulletin .= 'Fault:' . $_FILES['uploadedFile']['error']; } } $_SESSION['message'] = $message; header("Location: index.php");
Learn PHP With a Complimentary Online Form
Today, nosotros 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. So we looked at a real-world instance which demonstrated how file upload works in PHP.
If you want to learn more PHP, check out our free online course on PHP fundamentals!
In this course, yous'll acquire the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing elementary PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll acquire all the most important skills for writing apps for the web: you'll get a risk to do responding to Go and POST requests, parsing JSON, authenticating users, and using a MySQL database.
Did you find this post useful?
Source: https://code.tutsplus.com/tutorials/how-to-upload-a-file-in-php-with-example--cms-31763
0 Response to "content type of the uploaded file in PHP?"
Post a Comment