Where Is the Default Temp Directory for Php File Uploads
Read Fourth dimension: 11 mins Languages:
In this article, 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. Post-obit that, nosotros'll develop a real-world example of how to upload a file.
Configure the PHP Settings
In that location are a couple of PHP configuration settings that you'll want to check beforehand for successful file uploads. In this section, we'll get through every important selection in regards to PHP file upload. These options can exist configured in the php.ini file.
If you're not sure where to find yourphp.ini file, y'all tin 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(); ?>
Hither'south 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 apply system default if not gear up. ;upload_tmp_dir = ; Maximum allowed size for uploaded files. upload_max_filesize = 16M ; Maximum number of files that can be uploaded via a single asking 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 = xxx
The Key Settings
file_uploads
The value of thefile_uploads
directive should be gear up 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's set up to2M
(2 megabytes), and y'all tin override this setting using the.htaccess file as well. 2 megabytes isn't very much by today's standards, so y'all might have to increase this. If yous get an error thatfile exceeds upload_max_filesize
when y'all try to upload a file, you demand to increment this value. If you do, exist sure to too incrementpost_max_size
(see below).
upload_tmp_dir
Sets a temporary directory which will exist used to shop uploaded files. In most cases, you don't demand to worry well-nigh 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 information. Since files are uploaded with Mail service requests, this value must be greater than what you lot've set for theupload_max_filesize
directive. For example, if yourupload_max_filesize
is16M
(16 megabytes), you might want to setpost_max_size
to20M
.
max_file_uploads
Information technology allows you lot to set the maximum number of files that can be uploaded at a time. The default istwenty
, 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 y'all're dealing with big file uploads.threescore
(60 seconds) is a good value for near apps.
memory_limit
Thememory_limit
directive indicates the maximum amount of retentiveness a script can consume. If you lot're facing problems when uploading large files, you need to make sure 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 y'all accept a very largepost_max_size
andupload_max_filesize
, y'all don't need to worry about this.
max_execution_time
Information technology's the maximum number of seconds a script is allowed to run. If you're facing issues when uploading big files, you tin consider increasing this value. xxx
(xxx seconds) should work well for nigh apps.
At present let's build a real-globe instance to demonstrate file upload in PHP.
Create the HTML Grade
In one case you've configured the PHP settings, y'all're prepare to try out the PHP file upload capabilities.
Our GitHub repo has some sample code which I'yard going to hash out throughout this commodity. Then, if you want to follow along, go alee and download it from GitHub.
Nosotros're going to create two PHP files:index.php andupload.php. Theindex.php file holds code which is responsible for displaying the file upload form. On the other paw, theupload.php file is responsible for uploading a file to the server.
Also, a file will exist uploaded in theuploaded_files directory, and so you demand to brand sure that this binder exists and is writable by thespider web-server
user.
In this section, nosotros'll go through the primal parts of thealphabetize.php file.
Let's have 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['message']) { echo '<p class="notification">'.$_SESSION['bulletin']).'</p>'; unset($_SESSION['message']); } ?> <grade method="Mail service" action="upload.php" enctype="multipart/form-data"> <div class="upload-wrapper"> <span form="file-name">Cull a file...</span> <label for="file-upload">Browse<input type="file" id="file-upload" name="uploadedFile"></label> </div> <input type="submit" name="uploadBtn" value="Upload" /> </course> </body> </html>
Y'all can utilize the following CSS to requite the form a more highly-seasoned expect.
div.upload-wrapper { colour: white; font-weight: bold; display: flex; } input[type="file"] { position: absolute; left: -9999px; } input[type="submit"] { border: 3px solid #555; colour: white; background: #666; margin: 10px 0; border-radius: 5px; font-weight: bold; padding: 5px 20px; cursor: pointer; } input[blazon="submit"]:hover { background: #555; } label[for="file-upload"] { padding: 0.7rem; display: inline-block; background: #fa5200; cursor: pointer; border: 3px solid #ca3103; border-radius: 0 5px 5px 0; border-left: 0; } label[for="file-upload"]:hover { groundwork: #ca3103; } span.file-proper name { padding: 0.7rem 3rem 0.7rem 0.7rem; white-space: nowrap; overflow: hidden; background: #ffb543; color: black; edge: 3px solid #f0980f; border-radius: 5px 0 0 5px; edge-right: 0; }
The CSS basically hides the original fileinput
and styles its accompanyingbridge
andlabel
elements.
Although it may wait like a typical PHP form, there'southward an important deviation in the value of theenctype
aspect of the<class>
tag. Information technology needs to be set tomultipart/class-data
since the form contains the file field.
Theenctype
attribute specifies the blazon of encoding which should be used when the form is submitted, and it takes one of the following three values:
-
application/ten-www-class-urlencoded
: This is the default value when you don't set up the value of theenctype
attribute explicitly. In this case, characters are encoded before it'due south sent to the server. If yous don't accept the file field in your course, you should use this value for theenctype
attribute. -
multipart/form-data
: When you lot utilise themultipart/form-data
value for theenctype
attribute, it allows you lot to upload files using the Mail method. Besides, it makes sure that the characters are not encoded when the form is submitted. -
text/plainly
: This is generally non used. With this setting, the data is sent unencoded.
Next, nosotros output the file field, which allows you to select a file from your figurer.
<input type="file" proper name="uploadedFile" />
Apart from that, nosotros've displayed a message at the top of the class. This message shows the status of the file upload, and it'll be prepare in a session variable by theupload.php script. We'll look more than at this in the side by side section.
<?php if (isset($_SESSION['message']) && $_SESSION['message']) { echo '<p class="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?>
And then that sums up theindex.php file. In the adjacent section, we'll run into how to handle the uploaded file on the server side.
Create the Upload Logic
In the previous section, we created the HTML class which is displayed on the client side and allows you to upload a file from your computer. In this department, nosotros'll see the server-side counterpart which allows you to handle the uploaded file.
Pull in the code from theupload.php file on GitHub. Nosotros'll go through the important parts of that file.
In theupload.php file, we've checked whether information technology'due south a valid Mail service 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'due south initialized as an array and may contain the post-obit 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 type of the uploaded file. -
error
: If there's an error during file upload, this variable is populated with the appropriate error message. In the case of successful file upload, it contains 0, which you can compare past using theUPLOAD_ERR_OK
constant.
After validating the Mail request, nosotros check that the file upload was successful.
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['fault'] === UPLOAD_ERR_OK) { ... }
You lot can see that the$_FILES
variable is a multi-dimensional assortment, the get-go chemical element is the proper noun of the file field, and the second element has the information about the uploaded file, as nosotros've simply discussed above.
If the file upload is successful, nosotros initialize a few variables with data 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(terminate($fileNameCmps));
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 contain spaces and other special characters, it's better 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 lot restrict the blazon of file which can exist uploaded to certain extensions and don't allow everything using the upload form. Nosotros've done that past checking the extension of the uploaded file with a set of extensions that we want to allow for uploading.
$allowedfileExtensions = array('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 will 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 spider web server.'; }
Themove_uploaded_file
function takes two arguments. The start argument is the filename of the uploaded file, and the second argument is the destination path where you want to motion the file.
Finally, we redirect the user to theindex.php file. Also, nosotros set the appropriate message in the session variable, which volition be displayed to users after redirection in theindex.php file.
How Information technology All Works Together
Don't forget to create theuploaded_files directory and brand it writable by thespider web-server user. Next, become ahead and run theindex.php file, which should display the file upload form which looks like this:
Click on theBrowse push—that should open up a dialog box which allows you lot to select a file from your figurer. 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. Y'all could too attempt uploading other files with extensions that are not allowed, and check if our script prevents such uploads.
Resolving Common Errors
A lot of things can go wrong during a file upload which might result in errors. You can check the exact error 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 than than the value specified in php.ini or the HTML course respectively. You tin go rid of this error past 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 binder to upload the file is missing.UPLOAD_ERR_NO_FILE
is reported when in that location is no file to upload.
Partial Upload or Can't Write to Disk
You will becomeUPLOAD_ERR_PARTIAL
if the file could only exist uploaded partially andUPLOAD_ERR_CANT_WRITE
if the file could non be written to the disk.
A PHP Extension Stopped the File Upload
Sometimes, you will get the mistakeUPLOAD_ERR_EXTENSION
because some extension stopped the file upload. This i will require more investigation by you lot to effigy out which extension caused the problem.
Here is the total lawmaking fromupload.php which will show users a message on the upload page in example of success or failure of the upload. The information about 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-name $newFileName = md5(time() . $fileName) . '.' . $fileExtension; // check if file has one of the post-obit extensions $allowedfileExtensions = array('jpg', 'gif', 'png', 'nothing', '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 { $bulletin = 'There was some error moving the file to upload directory. Please make 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. Delight check the following error.<br>'; $message .= 'Mistake:' . $_FILES['uploadedFile']['mistake']; } } $_SESSION['message'] = $bulletin; header("Location: alphabetize.php");
Learn PHP With a Free Online Course
Today, we discussed the basics of file upload in PHP. In the outset one-half of the article, nosotros discussed the different configuration options that need to be in identify 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 than PHP, check out our free online class on PHP fundamentals!
In this grade, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. And so you'll build upwardly to coding classes for simple object-oriented programming (OOP). Forth the way, yous'll larn all the nearly important skills for writing apps for the web: you'll get a gamble to practice responding to Go and POST requests, parsing JSON, authenticating users, and using a MySQL database.
Did y'all 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 "Where Is the Default Temp Directory for Php File Uploads"
Post a Comment