How to Add an Upload Field to Php Page
Read Time: 11 mins Languages:
In this commodity, I'll explain the basics of file upload in PHP. Firstly, nosotros'll become through the PHP configuration options that need to be in place 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 y'all'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 tin be configured in the php.ini file.
If yous're not sure where to find yourphp.ini file, you lot tin utilise thephp_ini_loaded_file()
to locate it. Simply create a PHP file on your server with the post-obit line, and open up it from the browser.
<?php echo php_ini_loaded_file(); ?>
Hither's an extract 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 system default if not fix. ;upload_tmp_dir = ; Maximum immune size for uploaded files. upload_max_filesize = 16M ; Maximum number of files that can be uploaded via a single request max_file_uploads = 20 ; Maximum size of Postal service information that PHP will have. post_max_size = 20M max_input_time = 60 memory_limit = 128M max_execution_time = 30
The Fundamental Settings
file_uploads
The value of thefile_uploads
directive should be set up toOn
to let file uploads. The default value of this directive isOn
.
upload_max_filesize
Theupload_max_filesize
directive allows you lot to configure the maximum size of the uploaded file. By default, it's prepare to2M
(2 megabytes), and you tin can override this setting using the.htaccess file too. Two megabytes isn't very much by today's standards, so you might take to increase this. If you go an error thatfile exceeds upload_max_filesize
when y'all try to upload a file, you need to increase this value. If you exercise, be sure to also 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 don't set information technology, the arrangement default temp directory volition be used.
post_max_size
Thepost_max_size
directive allows you to configure the maximum size of Postal service data. Since files are uploaded with Mail requests, this value must be greater than what you've set up for theupload_max_filesize
directive. For example, if yourupload_max_filesize
is16M
(16 megabytes), you might desire to preparepost_max_size
to20M
.
max_file_uploads
It allows you to ready the maximum number of files that can be uploaded at a time. The default is20
, a sensible amount.
max_input_time
It's the maximum number of seconds a script is allowed to parse the input data. You should prepare information technology to a reasonable value if you're dealing with large file uploads.60
(lx seconds) is a good value for most apps.
memory_limit
Thememory_limit
directive indicates the maximum amount of retentivity a script can eat. If you lot're facing issues when uploading large files, yous demand to make sure that the value of this directive is greater than what yous've ready for the post_max_size
directive. The default value is128M
(128 megabytes), and then 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 yous're facing bug when uploading big files, you lot can consider increasing this value. 30
(30 seconds) should work well for most apps.
Now let'south build a real-world instance to demonstrate file upload in PHP.
Create the HTML Form
One time you've configured the PHP settings, you're ready to try out the PHP file upload capabilities.
Our GitHub repo has some sample code which I'thousand going to discuss throughout this commodity. So, if you desire to follow along, go ahead and download it from GitHub.
We're going to create two PHP files:alphabetize.php andupload.php. Theindex.php file holds lawmaking which is responsible for displaying the file upload form. 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, and so y'all need to make certain that this folder exists and is writable by theweb-server
user.
In this section, we'll get through the central parts of theindex.php file.
Permit's accept a look at theindex.php file on GitHub:
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>PHP File Upload</championship> </head> <body> <?php if (isset($_SESSION['message']) && $_SESSION['message']) { repeat '<p class="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?> <form method="Mail" action="upload.php" enctype="multipart/form-information"> <div grade="upload-wrapper"> <bridge class="file-name">Choose a file...</span> <label for="file-upload">Browse<input type="file" id="file-upload" name="uploadedFile"></characterization> </div> <input type="submit" name="uploadBtn" value="Upload" /> </form> </body> </html>
You can apply the post-obit CSS to give the class a more appealing look.
div.upload-wrapper { color: white; font-weight: bold; display: flex; } input[blazon="file"] { position: absolute; left: -9999px; } input[blazon="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 { background: #555; } label[for="file-upload"] { padding: 0.7rem; display: inline-block; groundwork: #fa5200; cursor: pointer; border: 3px solid #ca3103; edge-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: 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, at that place's an important difference in the value of theenctype
aspect of the<form>
tag. It needs to exist set tomultipart/form-data
since the course contains the file field.
Theenctype
aspect 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-course-urlencoded
: This is the default value when you don't set the value of theenctype
attribute explicitly. In this example, characters are encoded before it'due south sent to the server. If you don't have the file field in your form, you lot should use this value for theenctype
attribute. -
multipart/class-data
: When you lot utilize themultipart/class-data
value for theenctype
aspect, it allows you to upload files using the Postal service method. Likewise, it makes sure that the characters are not encoded when the form is submitted. -
text/manifestly
: 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" proper noun="uploadedFile" />
Apart from that, we've displayed a message at the top of the grade. This message shows the status 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 next section.
<?php if (isset($_SESSION['message']) && $_SESSION['bulletin']) { echo '<p form="notification">'.$_SESSION['message']).'</p>'; unset($_SESSION['message']); } ?>
Then that sums up thealphabetize.php file. In the side by side section, we'll come across how to handle the uploaded file on the server side.
Create the Upload Logic
In the previous department, 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 counterpart which allows you lot to handle the uploaded file.
Pull in the lawmaking from theupload.php file on GitHub. We'll become through the of import parts of that file.
In theupload.php file, nosotros've checked whether it's a valid Mail asking 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. Information technology's initialized every bit an array and may contain 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. -
error
: If there'due south an mistake during file upload, this variable is populated with the advisable fault bulletin. In the case of successful file upload, it contains 0, which you can compare past using theUPLOAD_ERR_OK
abiding.
After validating the POST request, nosotros bank check that the file upload was successful.
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK) { ... }
You tin see that the$_FILES
variable is a multi-dimensional array, the first element is the proper name of the file field, and the second chemical element has the data about the uploaded file, every bit nosotros've just 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, we've also figured out the extension of the uploaded file and stored it in the$fileExtension
variable.
As the uploaded file may incorporate spaces and other special characters, it's better to sanitize the filename, and that's exactly we've done in the post-obit snippet.
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
It'southward important that you lot restrict the type of file which tin be uploaded to certain extensions and don't allow everything using the upload form. We've done that by checking the extension of the uploaded file with a set of extensions that we want to allow for uploading.
$allowedfileExtensions = assortment('jpg', 'gif', 'png', 'nil', 'txt', 'xls', 'doc'); if (in_array($fileExtension, $allowedfileExtensions)) { ... }
Finally, we apply themove_uploaded_file
part to move the uploaded file to the specific location of our choice.
// directory in which the uploaded file will exist 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 2 arguments. The first argument is the filename of the uploaded file, and the second argument is the destination path where y'all want to move the file.
Finally, we redirect the user to theindex.php file. Also, we fix the advisable 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 go far writable by theweb-server user. Side by side, go alee and run thealphabetize.php file, which should display the file upload form which looks like this:
Click on theScan push button—that should open a dialog box which allows you to select a file from your reckoner. Select a file with one of the extensions immune in our script, and click on theUpload push button.
That should submit the form, and if everything goes well, you should see the uploaded file in theuploaded_files directory. You could also try uploading other files with extensions that are non allowed, and bank check if our script prevents such uploads.
Resolving Common Errors
A lot of things can get wrong during a file upload which might result in errors. Yous tin cheque the verbal error that occurred during the upload using$_FILES['uploadedFile']['error']
. Here is the explanation of those errors:
File Is Also Big
UPLOAD_ERR_INI_SIZE
andUPLOAD_ERR_FORM_SIZE
occur when the size of an uploaded file is more than the value specified in php.ini or the HTML class respectively. Yous tin get rid of this error 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 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 Deejay
Yous volition becomeUPLOAD_ERR_PARTIAL
if the file could only be uploaded partially andUPLOAD_ERR_CANT_WRITE
if the file could non exist written to the disk.
A PHP Extension Stopped the File Upload
Sometimes, you will become the mistakeUPLOAD_ERR_EXTENSION
because some extension stopped the file upload. This 1 will require more than investigation by you to effigy out which extension caused the problem.
Here is the total code fromupload.php which will show users a message on the upload page in instance of success or failure of the upload. The data 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-proper name $newFileName = md5(time() . $fileName) . '.' . $fileExtension; // bank check if file has i of the following 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)) { $bulletin ='File is successfully uploaded.'; } else { $bulletin = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.'; } } else { $bulletin = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions); } } else { $bulletin = 'There is some fault in the file upload. Delight check the following error.<br>'; $message .= 'Error:' . $_FILES['uploadedFile']['mistake']; } } $_SESSION['message'] = $message; header("Location: index.php");
Acquire PHP With a Gratis Online Course
Today, we discussed the basics 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 we looked at a real-world example which demonstrated how file upload works in PHP.
If y'all desire to learn more PHP, cheque out our costless online course on PHP fundamentals!
In this course, yous'll learn the fundamentals of PHP programming. You'll beginning with the nuts, learning how PHP works and writing simple PHP loops and functions. And then you lot'll build up to coding classes for simple object-oriented programming (OOP). Along the way, yous'll learn all the most of import skills for writing apps for the web: you'll get a risk to exercise responding to GET and Mail service requests, parsing JSON, authenticating users, and using a MySQL database.
Did you lot discover this mail useful?
Source: https://code.tutsplus.com/tutorials/how-to-upload-a-file-in-php-with-example--cms-31763
0 Response to "How to Add an Upload Field to Php Page"
Post a Comment