Hello, How are you today?
Today we are going to upload a file using PHP and save it in the server.
When we upload a file it will be uploaded as a temporary file to the server. If we do not save this uploaded file in another directory in the server it will get deleted after the session is over.
First of all let's create the HTML form that helps us to upload the file.
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadedFile" />
<input type="submit"/>
</form>
When creating the HTML form you have to keep two things in your mind.
- Type of the input field should be file.
- Form must have an enctype attribute set as enctype="multipart/form-data".
Now we have created the HTML form. Let's see how upload the file and save it using PHP.
PHP has a global variable called $_FILE to access the information of the uploaded file. This global variable has a two dimensional array which stores all the information about the uploaded file.
$_FILE has following variables:-
- $_FILE['uploadedFile'][temp_name''] - This gives the name of the temporary file which has been created in the server.
- $_FILE['uploadedFile']['error'] - This returns the error codes which occurred and associated with the file.
- $_FILE['uploadedFile']['name'] - This returns the actual name of the uploaded file.
- $_FILE['uploadedFile']['size'] - This returns the size of the uploaded file.
- $_FILE['uploadedFile']['type'] - This returns the MIME type of the uploaded file.
Now let's upload and save the file in the server.
if(isset($_FILES['uploadedFile'])){
$file_name = $_FILES['uploadedFile']['name'];
$file_size = $_FILES['uploadedFile']['size'];
$file_tmp = $_FILES['uploadedFile']['tmp_name'];
$file_type = $_FILES['uploadedFile']['type'];
//getting the actual file extention
$file_ext=strtolower(end(explode('.',$_FILES['uploadedFile']['name'])));
//checking whether the file is an excel file
if(!($file_ext=="xlsx" || $file_ext=="xls")){
$newName = "CTNS.".$file_ext;
//saving the file in new location called upload
move_uploaded_file($file_tmp,'upload/'.$newName);
}
}
Well now we have uploaded the file and saved in a new location in the server. Hope you can understand!
See you from another tutorial.
Comment box is open for Questions, Suggestions, Complaints and Comments.
Past Topics :-