Before getting started you should aware how you can submit a HTML form in PHP. This post will post a simple PHP form which will have 2 input text fields of First name and Last name. Along two text fields one file field name your image. This tutorial restrict users to upload file types of jpg, png, gif and jpeg.
If you want to upload files using PHP like PDF, Zip, or other file types there are some restrictions on server also. For example uploading .exe cannot be permitted and you have to modify server permissions for this. Let’s being our simple image uploading process from HTML to PHP and save that image into server directory and retrieve its Path also in PHP variable.
Things you need to upload file with PHP
- You should have a running server on localhost or online. Which can run and process the PHP.
- Create a directory /form/ and inside that directory create uploads/ directory. Uploads is the Path where we will be saving our uploads. And the form/ can be anything here just for example using /forms/ parent directory.
- Create a file file_process.php and place that inside forms/ directory.
- Now you need another file form.html please place that in same directory you have file_process.php
Note: If you want to place file_process.php file in some other directory make sure the action=”” field in form below is updated accordingly. This work like absolute relative links works. You can also post form’s data via absolute link.
Now create a simple form like below. In your form.html file.
Create Form in HTML File
You can create a HTML form in .html or .php file its upto you. Form below submits data to file_process.php with method post. Let’s try to explain the HTML form line by line.
Note:
Be sure your file upload form has attribute enctype=”multipart/form-data” otherwise the file upload will not work.
Source php.net
For File uploading use only POST method not HEAD or GET methods
As post method is more secure than the GET and HEAD methods. Post method sends data to action file hidden. While get method post data to URL of action location.
You cannot send files via GET method because an URL is roughly limited to 2000 characters. Trying to squeeze an entire file in there isn’t the smartest idea. And can produce problems for you. So always use POST method like we used in form below.
So the form below encrypt data by type multipart/form-data then post it to file_process.php in same director where the form’s file is using method post. Furthermore form creates 2 text fields which have default values null, and placeholders to guide what fields are about.
Email in form below is required field for this form. Means empty email field cannot be sent.
Next field is type file, which is labeled with label HTML tag also. Then submit button of type submit. Remember type submit is required to <button or <input type for form to submit.
<form enctype="multipart/form-data" action="file_process.php" method="post">
<input type="text" name="name" placeholder="Please enter your name…" />
<input type="email" name="email" required required placeholder="enter your email here.." />
<label>Upload Your Image
<input type="file" name="profile_image" />
</label>
<input type="submit" value="Submit Page" />
</form>
Explanation of HTML.
<form enctype=”multipart/form-data” action=”process.php” method=”post”> In this line we are starting form, and we are encrypting form into multipart so our form can submit files as well, in action we are saying where to take or where to post values of our form and method post means we want to take out our values hidden. Get method takes value to next page with url not hidden.
<input type=”text” name=”name” value=”Please enter your name…” /> In this line i am saying create a new text field name it name, and i will access to its value whatever user enter in file_process.php by its name. Email field also doing same.
<input type=”file” name=”profile_image”> This is file type field where users can upload file and its name is prodImg so i can access my file in next page using its name prodImg. This is important to upload image from html form using php.
<input type=”submit” /> This is a button and form knows when this is pressed we have to send entered data and files to process.php or whatever is in form action.
Note: Name attribute in field required as its used to receive data of that field with PHP. You can say name in form’s field is identifier of that field. If you repeat name that will only hold data of last field. If you want to send multiple data with 1 name just use field_name[] this will create array of that name’s all inputs.
What happens when you hit submit button?
After form is submitted http:// or https:// will post hidden values to file_process.php and will take user to file_process.php file with data sent from form behind. We will get values by names there with following code. and we will save file url in $upFile; Variable, name in $name variable, and email in $email variable.
Want to hire PHP coder? We are here to help you.
Processing http html form in php.
<?php
extract($_POST); //Creates names as variable with value of submission
$fileType = $_FILES["profile_image"]["type"];
$fileSize = $_FILES["profile_image"]["size"];
if($fileSize/1024 > "2048") {
//Its good idea to restrict large files to be uploaded.
echo "Filesize is not correct it should equal to 2 MB or less than 2 MB.";
exit();
} //FileSize Checking
if(
$fileType != "image/png" &&
$fileType != "image/gif" &&
$fileType != "image/jpg" &&
$fileType != "image/jpeg" &&
$fileType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" &&
$fileType != "application/zip" &&
$fileType != "application/pdf"
) {
echo "Sorry this file type is not supported we accept only. Jpeg, Gif, PNG, or ";
exit();
} //file type checking ends here.
$upFile = "uploads/".date("Y_m_d_H_i_s").$_FILES["profile_image"]["name"];
if(is_uploaded_file($_FILES["profile_image"]["tmp_name"])) {
if(!move_uploaded_file($_FILES["profile_image"]["tmp_name"], $upFile)) {
echo "Problem could not move file to destination. Please check again later. <a href="index.php">Please go back.</a>";
exit;
}
} else {
echo "Problem: Possible file upload attack. Filename: ";
echo $_FILES["profile_image"]["name"];
exit;
}
$profile_image = $upFile;
echo $profile_image;
Explanation of PHP.
Let’s try to explain now how actually PHP is processing the form.
- You may hire php coders if you need help in PHP.
- Our partners are also offering video annotation outsourcing which may be helpful for your video annotation needs.
What extract($_POST) does?
extract($_POST); When we submit form with post method in http our browser submit POST as an array to next page, and when we get that via php , PHP convert POST into associative array and define keys the names of fields and values as what is saved in that array key. Using extract function we extract everything from POST array and make variables of its keys. Like after extracting post we will have $name variable which holds whatever user inserted in name field. Also we have $email variable which holds whatever user inserted in email field.
So we got 2 variables from extract which have our desired values. $name, and $email.
3) To upload file via php we restrict user to upload file within a specific size, and to upload file types of specific file types. Like we cannot let users upload .exe file or such application files.
How to get uploaded file size in php?
Here how we get uploaded file size in php. $fileSize = $_FILES[‘prodImg’][‘size’]; now $fileSize variable holds size of our file which was sent via prodImg file type field.
How to get uploaded file type in php?
Here how we get uploaded file type in php $fileType = $_FILES[‘profile_image’][‘type’]; now variable $fileType holds the type of our file.
How to calculate file size into KB(Kilobytes) from bytes.
PHP calculate the file size into bytes and we rarely understand how many bytes are actually equal to 2 MB or something, so better we convert then first, As we know 1 KB holds 1024 bytes, that’s why we first devide our fileSize/1024 and this gives us KB file size.
How to check if uploaded file is not more than 2 MB.
$fileType = $_FILES["profile_image"]["type"];
$fileSize = $_FILES["profile_image"]["size"];
if($fileSize/1024 > "2048") {
//Its good idea to restrict large files to be uploaded.
echo "Filesize is not correct it should equal to 2 MB or less than 2 MB.";
exit();
} //FileSize Checking
These lines will check in first line if uploaded file size not greater than 2 MB which are actually 2048 KB if this condition become true our script will produce and echo an error and exit from further processing using exit php function.
How to check if uploaded file type is specific type.
if(
$fileType != "image/png" &&
$fileType != "image/gif" &&
$fileType != "image/jpg" &&
$fileType != "image/jpeg" &&
$fileType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" &&
$fileType != "application/zip" &&
$fileType != "application/pdf"
) {
echo "Sorry this file type is not supported we accept only. Jpeg, Gif, PNG, or ";
exit();
} //file type checking ends here.
Here in first line we are checking if uploaded file is not png, gif, jpg, jpeg, zip pdf, document word, so this means if any file related to our condition exist means, if fileType is not png then this condition for all other too will return false and this if condition inner content will not process, but if all of them become true saying uploaded file is not any type of these files then this if condition will run and will show an error and will exit for further processing.
How to upload file to specific directory via php?
$upFile = "uploads/".date("Y_m_d_H_i_s").$_FILES["profile_image"]["name"];
if(is_uploaded_file($_FILES["profile_image"]["tmp_name"])) {
if(!move_uploaded_file($_FILES["profile_image"]["tmp_name"], $upFile)) {
echo "Problem could not move file to destination. Please check again later. <a href='index.php'>Please go back.</a>";
exit;
}
} else {
echo "Problem: Possible file upload attack. Filename: ";
echo $_FILES["profile_image"]["name"];
exit;
}
$profile_image = $upFile;
echo $profile_image;
in first line i am defining upFile name and directory name where i want to save my file. I have put date and time with file name so that do not get change or replaced with any other upload in future.
How to get uploaded file name via php?
Using $_FILES[‘prodImg’][‘name’] we get uploaded file name and we save it into any variable or whatever we want to do with it.
PHP server saves posted file into temporary directory untill we tell in which directory and with what name we want to save. So here is further processing and we will get our file name as $upFile; this will hold the URL of image.
$upFile = "uploads/".date("Y_m_d_H_i_s").$_FILES["profile_image"]["name"];
if(is_uploaded_file($_FILES["profile_image"]["tmp_name"])) {
if(!move_uploaded_file($_FILES["profile_image"]["tmp_name"], $upFile)) {
echo "Problem could not move file to destination. Please check again later. <a href='index.php'>Please go back.</a>";
exit;
}
} else {
echo "Problem: Possible file upload attack. Filename: ";
echo $_FILES["profile_image"]["name"];
exit;
}
$profile_image = $upFile;
echo $profile_image;
That’s how we upload files via php into server. And how we post html forms with php.
Function to upload files in PHP
Functions are always great pieces of code which you can re use any number of times. Without rewriting them. Here we have created a PHP function which will accept the $_FILES[“file_name”] and upload and return the file URL.
//Define your root directory and change it inside function if your constant is different.
define("ROOT_DIR", dirname(__FILE__));
function wc_upload_image_return_url($image_submit) {
if(empty($image_submit) && $image_submit['error'] != 0) {
return _("Nothing uploaded");
}
$fileType = $image_submit["type"];
$fileSize = $image_submit["size"];
if($fileSize/1024 > "2048") {
//Its good idea to restrict large files to be uploaded.
return _("Filesize is not correct it should equal to 2 MB or less than 2 MB.");
exit();
} //FileSize Checking
if(
$fileType != "image/png" &&
$fileType != "image/gif" &&
$fileType != "image/jpg" &&
$fileType != "image/jpeg" &&
$fileType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" &&
$fileType != "application/zip" &&
$fileType != "application/pdf"
) {
return _("Sorry this file type is not supported we accept only. Jpeg, Gif, PNG");
exit();
} //file type checking ends here.
$filename = date("Y_m_d_H_i_s").$image_submit["name"];
$upFile = ROOT_DIR."/assets/upload/".$filename;
if(is_uploaded_file($image_submit["tmp_name"])) {
if(!move_uploaded_file($image_submit["tmp_name"], $upFile)) {
return _("Problem could not move file to destination.");
exit;
} else {
$return_file = "assets/upload/".$filename;
}
} else {
return _("Problem: Possible file upload attack. Filename: ").$image_submit['name'];
exit;
}
return $return_file;
}
In PHP function above which helps you upload the files to server. Make sure you replace assets/upload/ directory to directory name where you are uploading the files or images.
Using the function is really easy just catch the File variable and pass it through the function. The form should be multipart enctype otherwise file submission wouldn’t work.
if(isset($_FILES["profile_image"])) {
$uploaded_file_url = wc_upload_image_return_url($_FILES["profile_image"]);
}
If the file was submitted then its url is saved to variable $uploaded_file_url variable that’s it. If you have any questions please post in comments.