A Script That Upload File to Server
Read Time: 11 mins Languages:
In this commodity, I'll explain the basics of file upload in PHP. Firstly, nosotros'll go through the PHP configuration options that need to exist in place for successful file uploads. Following that, nosotros'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 can be configured in the php.ini file.
If you lot're not sure where to notice yourphp.ini file, you can use thephp_ini_loaded_file()
to locate information technology. Just create a PHP file on your server with the following line, and open information technology from the browser.
<?php echo php_ini_loaded_file(); ?>
Here's an extract from a setup file with some useful defaults.
; Whether to permit HTTP file uploads. file_uploads = On ; Temporary directory for HTTP uploaded files. ; Will utilize organization default if non set. ;upload_tmp_dir = ; Maximum immune size for uploaded files. upload_max_filesize = 16M ; Maximum number of files that can be uploaded via a unmarried request max_file_uploads = 20 ; Maximum size of POST information that PHP will accept. post_max_size = 20M max_input_time = lx memory_limit = 128M max_execution_time = thirty
The Key Settings
file_uploads
The value of thefile_uploads
directive should be set toOn
to permit 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'south set to2M
(two megabytes), and yous tin can override this setting using the.htaccess file as well. Two megabytes isn't very much past today'south standards, so yous might accept to increase this. If you go an error thatfile exceeds upload_max_filesize
when yous try to upload a file, you need to increment this value. If you do, be sure to too increasepost_max_size
(see below).
upload_tmp_dir
Sets a temporary directory which will be used to store uploaded files. In most cases, you don't need to worry about this setting. If you lot 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've set for theupload_max_filesize
directive. For example, if yourupload_max_filesize
is16M
(16 megabytes), y'all might desire to setpost_max_size
to20M
.
max_file_uploads
It allows yous to set the maximum number of files that tin exist uploaded at a fourth dimension. The default istwenty
, a sensible corporeality.
max_input_time
It'southward the maximum number of seconds a script is allowed to parse the input information. You should set it to a reasonable value if you're dealing with large file uploads.60
(60 seconds) is a good value for most apps.
memory_limit
Thememory_limit
directive indicates the maximum amount of retention a script can consume. If you're facing problems when uploading big files, y'all demand to make sure that the value of this directive is greater than what you've prepare for the post_max_size
directive. The default value is128M
(128 megabytes), then unless you lot take a very largepost_max_size
andupload_max_filesize
, you don't need to worry almost 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 large files, you tin consider increasing this value. xxx
(30 seconds) should work well for most apps.
Now allow's build a real-world example to demonstrate file upload in PHP.
Create the HTML Form
Once you've configured the PHP settings, you lot're fix to try out the PHP file upload capabilities.
Our GitHub repo has some sample code which I'm going to discuss throughout this article. So, if you want to follow forth, become ahead and download it from GitHub.
We're going to create two 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, so you need to brand sure that this folder exists and is writable past theweb-server
user.
In this section, we'll go through the fundamental parts of theindex.php file.
Let'south take a look at theindex.php file on GitHub:
<?php session_start(); ?> <!DOCTYPE html> <html> <caput> <title>PHP File Upload</title> </head> <body> <?php if (isset($_SESSION['message']) && $_SESSION['message']) { echo '<p class="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?> <grade method="POST" action="upload.php" enctype="multipart/form-data"> <div class="upload-wrapper"> <span class="file-name">Choose a file...</span> <label for="file-upload">Browse<input type="file" id="file-upload" name="uploadedFile"></label> </div> <input type="submit" proper name="uploadBtn" value="Upload" /> </course> </body> </html>
You can utilise the following CSS to give the form a more than appealing 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; edge-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 { background: #ca3103; } span.file-name { padding: 0.7rem 3rem 0.7rem 0.7rem; white-space: nowrap; overflow: hidden; background: #ffb543; color: blackness; edge: 3px solid #f0980f; border-radius: 5px 0 0 5px; border-correct: 0; }
The CSS basically hides the original fileinput
and styles its accompanyingspan
andcharacterization
elements.
Although information technology may look like a typical PHP class, there's an important deviation in the value of theenctype
attribute of the<course>
tag. Information technology needs to be set tomultipart/course-data
since the form contains the file field.
Theenctype
attribute specifies the type of encoding which should exist used when the grade 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 set the value of theenctype
aspect explicitly. In this case, characters are encoded before information technology's sent to the server. If you lot don't have the file field in your form, you should apply this value for theenctype
attribute. -
multipart/form-data
: When yous apply themultipart/course-information
value for theenctype
attribute, information technology allows you to upload files using the POST method. Too, it makes sure that the characters are not encoded when the form is submitted. -
text/patently
: This is generally not used. With this setting, the data is sent unencoded.
Next, we output the file field, which allows you lot 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 information technology'll be set in a session variable by theupload.php script. We'll await more at this in the next section.
<?php if (isset($_SESSION['message']) && $_SESSION['bulletin']) { echo '<p form="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?>
And then that sums up thealphabetize.php file. In the next section, nosotros'll see 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 lot to upload a file from your computer. In this department, we'll see the server-side analogue which allows you to handle the uploaded file.
Pull in the lawmaking from theupload.php file on GitHub. We'll go through the of import parts of that file.
In theupload.php file, we've checked whether it's a valid POST asking in the first identify.
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload') { ... }
In PHP, when a file is uploaded, the$_FILES
superglobal variable is populated with all the information well-nigh the uploaded file. It's initialized as an array and may incorporate the following data for successful file upload.
-
tmp_name
: The temporary path where the file is uploaded is stored in this variable. -
name
: The bodily name of the file is stored in this variable. -
size
: Indicates the size of the uploaded file in bytes. -
blazon
: 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 y'all tin can compare by using theUPLOAD_ERR_OK
abiding.
Afterward validating the POST request, we check that the file upload was successful.
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK) { ... }
You can run into that the$_FILES
variable is a multi-dimensional array, the first element is the name of the file field, and the 2nd element has the data virtually the uploaded file, as nosotros've just discussed to a higher place.
If the file upload is successful, nosotros initialize a few variables with information nigh 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, we've also figured out the extension of the uploaded file and stored it in the$fileExtension
variable.
Every bit the uploaded file may incorporate spaces and other special characters, information technology's amend to sanitize the filename, and that'due south exactly nosotros've done in the following snippet.
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
It's important that you restrict the blazon of file which can exist uploaded to certain extensions and don't let everything using the upload grade. Nosotros've done that by 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 movement the uploaded file to the specific location of our selection.
// directory in which the uploaded file volition 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. Delight brand sure the upload directory is writable by spider web server.'; }
Themove_uploaded_file
function takes two arguments. The first argument is the filename of the uploaded file, and the second argument is the destination path where you want to move the file.
Finally, we redirect the user to thealphabetize.php file. Also, we ready the advisable message in the session variable, which will be displayed to users subsequently redirection in thealphabetize.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, go alee and run theindex.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 one of the extensions immune in our script, and click on theUpload button.
That should submit the course, and if everything goes well, you should encounter the uploaded file in theuploaded_files directory. You lot could too endeavor uploading other files with extensions that are not immune, 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 tin check the verbal error that occurred during the upload using$_FILES['uploadedFile']['error']
. Here is the caption 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 class respectively. You can become rid of this fault past increasing the upload size limits or letting users know nearly 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 there is no file to upload.
Partial Upload or Tin can't Write to Disk
You lot 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 will get the faultUPLOAD_ERR_EXTENSION
because some extension stopped the file upload. This ane will require more investigation by you to effigy out which extension caused the problem.
Here is the total code fromupload.php which volition show users a bulletin on the upload folio in case of success or failure of the upload. The information almost 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']['blazon']; $fileNameCmps = explode(".", $fileName); $fileExtension = strtolower(finish($fileNameCmps)); // sanitize file-name $newFileName = md5(time() . $fileName) . '.' . $fileExtension; // check if file has i of the following extensions $allowedfileExtensions = array('jpg', 'gif', 'png', 'cypher', '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 = 'At that place was some fault moving the file to upload directory. Delight make sure the upload directory is writable by web server.'; } } else { $message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions); } } else { $message = 'At that place is some error in the file upload. Please check the following mistake.<br>'; $message .= 'Fault:' . $_FILES['uploadedFile']['error']; } } $_SESSION['bulletin'] = $message; header("Location: index.php");
Learn PHP With a Gratuitous Online Course
Today, we discussed the nuts of file upload in PHP. In the starting time half of the article, we discussed the different configuration options that need to exist in identify for file upload to piece of work. And then we looked at a real-globe example which demonstrated how file upload works in PHP.
If you lot want to learn more PHP, check out our complimentary online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. Y'all'll offset with the basics, learning how PHP works and writing simple PHP loops and functions. Then yous'll build upwardly to coding classes for simple object-oriented programming (OOP). Along the manner, you'll acquire all the most important skills for writing apps for the web: y'all'll go a chance to practise responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
Did you observe this post useful?
Source: https://code.tutsplus.com/tutorials/how-to-upload-a-file-in-php-with-example--cms-31763
0 Response to "A Script That Upload File to Server"
Post a Comment