File Uploading is a common feature in today’s PHP applications. You will first have to understand the basics concept of file uploading in PHP.
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.
First, ensure that PHP is configured to allow file uploads or not.
In your “php.ini” file, search for the file_uploads directive and check file_uploads set On or not:
file_uploads = On
Create an HTML form that allow users to choose the file they want to upload:
Note: for upload any file form enctype attribute value should be enctype=”multipart/form-data” and make sure the form method should be post method=”post”.
<!DOCTYPE html> <html> <body> <form action="uploadfile.php" method="post" enctype="multipart/form-data"> Select file to upload: <input type="file" name="fileUpload" id="fileUpload"> <input type="submit" value="Click Me Upload File" name="submit"> </form> </body> </html>
The “uploadfile.php” file contains the code for uploading a file:
There we are using a global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input’s name attribute in uploading form was file, then PHP would create following five variables −
<?php if(isset($_FILES['fileUpload'])) { $file_name = $_FILES>['fileUpload']['name']; $file_size = $_FILES['fileUpload']['size']; $file_tmp = $_FILES['fileUpload']['tmp_name']; $file_type = $_FILES['fileUpload']['type']; $file_ext = strtolower(end(explode('.',$_FILES['fileUpload']['name']))); move_uploaded_file($file_tmp, "uploads/".$file_name); echo "File has been uploaded!"; } ?>
Here we are checking if the uploading file already exists in the “uploads” folder. If it is, than display the error message otherwise display success message.
<?php if(isset($_FILES['fileUpload'])) { $file_name = $_FILES>['fileUpload']['name']; $file_tmp = $_FILES['fileUpload']['tmp_name']; // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists!"; } else { move_uploaded_file($file_tmp, "uploads/".$file_name); echo "Yes, File has been uploaded!"; } } ?>