As a developer, you’ve probably faced challenges when implementing a file upload feature in PHP.
It’s not just about getting it to work – it’s about ensuring the process is secure and efficient. A poorly handled file upload can open up security vulnerabilities. Without proper validation, you could end up with a server full of junk data.
That’s where this blog post comes in to help you navigate these challenges.
I’ll show you how to add a file upload feature in PHP using jQuery and AJAX. It’s time to roll up our sleeves and dive into the nitty-gritty of efficient and secure file transfers. This is going to save you so much time down the line. Let’s get started!
Why Use PHP, jQuery, and AJAX?
PHP makes file uploads easy. You can upload text or binary files with a few lines of code. PHP gives you full control over the uploaded files through its authentication and file operation functions.
Before uploading a file, checking its type, size, and dimensions is important. This is called data validation. PHP stores details like the file’s name, size, and temporary location in the $_FILES[“image_file”] array.
The move_uploaded_file function in PHP makes uploading files even easier. It uses the $_FILES array data to upload the file. When you use PHP with jQuery AJAX, you can upload files asynchronously. This makes your website faster and gives users a better experience.
Setting up Development Environment
For this PHP file upload example, you’ll need a few prerequisites. Here’s what I’m using:
- PHP 8: for our server-side logic.
- MySQL: to store and manage our data.
- JQuery/Ajax file: to make asynchronous requests to the server.
I’ve hosted my PHP application on Cloudways to avoid getting sidetracked by server-related issues. You can also try Cloudways for free without providing credit card details. With the configurations all set, the next step is to work on the File Uploading Script.
Take Action Now and Focus on What You Do Best – Coding!
Try Cloudways for a seamless PHP hosting experience, tailored to meet your development needs and say goodbye to server-related issues in one swift move!
Creating a File Using PHP
The first step is to set up an HTML form. This is what users will interact with to submit their data. To make the form work with file uploads, you need to set the form’s method to POST. This is because the GET method can’t send files to servers.
Next, you must set the form’s enctype attribute to multipart/form-data. This specifies how the form data should be encoded when submitting it to the server.
Finally, you must set the file input type attribute to the file. This allows users to select files to upload.
Once you’ve set up your form, create a file named index.php in your PHP project and add your code there.
<!doctype html> <html> <head lang="en"> <meta charset="utf-8"> <title>Ajax File Upload with jQuery and PHP</title> <link rel="stylesheet" href="style.css" type="text/css" /> <script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script> <script type="text/javascript" src="js/script.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8"> <h1><a href="#" target="_blank"><img src="logo.png" width="80px"/>Ajax File Uploading with Database MySql</a></h1> <hr> <form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="name">NAME</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required /> </div> <div class="form-group"> <label for="email">EMAIL</label> <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required /> </div> <input id="uploadImage" type="file" accept="image/*" name="image" /> <div id="preview"><img src="filed.png" /></div><br> <input class="btn btn-success" type="submit" value="Upload"> </form> <div id="err"></div> <hr> <p><a href="https://www.cloudways.com" target="_blank">www.Cloudways.com</a></p> </div> </div> </div></body></html>
This form uses Bootstrap classes for styling. The form’s action attribute points to ajaxupload.php, which is the script that will handle the file upload.
Uploading a File With jQuery AJAX
I’ll use jQuery and AJAX for data submission and file uploads. The initial step involves integrating the jQuery library into our project.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> $(document).ready(function (e) { $("#form").on('submit',(function(e) { e.preventDefault(); $.ajax({ url: "ajaxupload.php", type: "POST", data: new FormData(this), contentType: false, cache: false, processData:false, beforeSend : function() { //$("#preview").fadeOut(); $("#err").fadeOut(); }, success: function(data) { if(data=='invalid') { // invalid file format. $("#err").html("Invalid File !").fadeIn(); } else { // view uploaded file. $("#preview").html(data).fadeIn(); $("#form")[0].reset(); } }, error: function(e) { $("#err").html(e).fadeIn(); } }); })); });
The $ajax() method in our code is used to transmit data to PHP. We also make sure that the data transmission is successful, or we identify if any errors have occurred during the process.
Connecting MySQL Database With PHP
The next step involves configuring and connecting the MySQL database.
Go to the Cloudways Database Manager and construct a table labeled as uploading. This table comprises fields such as name, email, and file_name. You also have the option to utilize the given SQL query:
CREATE TABLE `uploading` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Next, create db.php to connect the database with the PHP application. Paste the following code snippet in the file:
<?php //DB details $dbHost = 'localhost'; $dbUsername = 'fkmc'; $dbPassword = ''; $dbName = 'fkc'; //Create connection and select DB $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); if($db->connect_error){ die("Unable to connect database: " . $db->connect_error); }
Create a PHP Script for File Uploading
When a user interacts with this form, the file is uploaded to a temporary folder. All the file’s details are stored in a multidimensional array called $_FILES. The key index of this array is the name attribute on the <input type=”file” name=”image”> field.
$_FILES[“image”] is the index name in this case. Additional file information is stored in the following indexes:
- $img = $_FILES[“image”][“name”]; // Stores the original filename from the client
- $tmp = $_FILES[“image”][“tmp_name”]; // Stores the name of the designated temporary file
- $errorimg = $_FILES[“image”][“error”]; // Stores any error code resulting from the transfer
After the file is uploaded to the temporary folder and all its information is saved in the array, the move_uploaded_file() function moves the file from its current temporary location to a permanent location. The file upload process is as follows:
- Check for any errors in the upload.
- Verify if the file type is allowed.
- Ensure that the file is under the set file size limit.
- Validate the filename (if it contains a ‘/’, it will affect the destination path).
- Confirm that the file doesn’t already exist at the target location (based on its name).
- Finally, upload the file.
Now, let’s create a PHP script to handle file uploading functionality. Create a new file named ajaxupload.php and insert the provided code into it.
<?php $valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp' , 'pdf' , 'doc' , 'ppt'); // valid extensions $path = 'uploads/'; // upload directory if(!empty($_POST['name']) || !empty($_POST['email']) || $_FILES['image']) { $img = $_FILES['image']['name']; $tmp = $_FILES['image']['tmp_name']; // get uploaded file's extension $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION)); // can upload same image using rand function $final_image = rand(1000,1000000).$img; // check's valid format if(in_array($ext, $valid_extensions)) { $path = $path.strtolower($final_image); if(move_uploaded_file($tmp,$path)) { echo "<img src='$path' />"; $name = $_POST['name']; $email = $_POST['email']; //include database configuration file include_once 'db.php'; //insert form data in the database $insert = $db->query("INSERT uploading (name,email,file_name) VALUES ('".$name."','".$email."','".$path."')"); //echo $insert?'ok':'err'; } } else { echo 'invalid'; } } ?>
Once all the checks are completed, we’ll transfer the uploaded file from the temporary folder to the upload folder.
To do this, first, create an upload folder in the project directory. This is where the uploaded images will be stored. The built-in function pathinfo() is used here, which returns the filename and extension in separate indexes.
Testing the File Creation and Upload
Insert the following code to inspect the uploaded file for any errors. If the error count exceeds zero, it indicates that an issue has occurred during the process.
if($errorimg > 0){ die('<div class="alert alert-danger" role="alert"> An error occurred while uploading the file </div>'); }
Testing File Size Is Under the Set File Size Limit
The file size is measured in bytes. Therefore, if the file size limit is set at 500kb, the file size should be less than 500,000 bytes.
if($myFile['size'] > 500000){ die('<div class="alert alert-danger" role="alert"> File is too big </div>'); }
In the PHP Script for File Uploading, move_uploaded_file is the function that relocates the file from $myFile[“tmp_name”] (the temporary location) to upload/. $name (the permanent location). It also verifies the record that will be inserted into the database table.
Configuring reCAPTCHA in Contact Form
reCAPTCHA safeguards forms from spam and abusive submissions. It serves as an extra layer operating in the background to deter spam by distinguishing between human users and bots, presenting them with a challenge to solve.
To use reCAPTCHA in your PHP website, you’ll need to use a library that interfaces with the reCAPTCHA API. You can download the reCAPTCHA PHP Library and subsequently use the file recaptchalib.php.
Insert the following code in the <form> tag where you wish to position your reCAPTCHA:
require_once('recaptchalib.php'); $publickey = "your_public_key"; //you got this from the signup page echo recaptcha_get_html($publickey);
To verify if users have provided correct answers, you need to create a file named verify.php and set it as the action parameter in the <form> tag. Here’s the code for that:
<?php require_once('recaptchalib.php'); $privatekey = "your_private_key"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); } else { // Your code here to handle a successful verification } ?>
Troubleshooting Common Issues
During a file upload, different issues can arise, leading to errors. To identify the specific error that occurred during the upload, use $_FILES[‘uploadedFile’][‘error’]. Here are some common errors you might encounter while uploading a file:
1. File Size Is Too Large
The UPLOAD_ERR_FORM_SIZE and UPLOAD_ERR_INI_SIZE errors occur when the file size exceeds the limit specified in php.ini or the HTML form. You can resolve this error by increasing the upload size limits or informing users about the maximum file size they can upload.
2. Temporary Folder Is Missing
The UPLOAD_ERR_NO_TMP_DIR error is triggered when the transfer file is missing, and UPLOAD_ERR_NO_FILE is reported when there’s no file to transfer.
3. Partial Upload or Can’t Write to Disk
You’ll encounter the UPLOAD_ERR_PARTIAL error when the file can only be partially uploaded and UPLOAD_ERR_CANT_WRITE if the file cannot be written to the disk.
4. A PHP Extension Stopped the File Upload
Occasionally, you may encounter the UPLOAD_ERR_EXTENSION error because an extension halted the file upload. This issue will require further investigation by the developer to identify which extension caused the problem.
Summary
We’ve successfully added a file upload feature to your website using PHP, jQuery, AJAX, and MySQL. This new feature enhances your website’s functionality and provides a seamless file upload process for an improved user experience.
This article has equipped you with the practical skills to implement a secure and efficient file upload system, a crucial step in mastering PHP development. Remember, every new feature brings you closer to creating a robust and user-friendly website.
Power-Up Your PHP Applications With Cloudways’ Managed Hosting!
Experience the Next Level of Performance with Our Managed PHP Hosting! Elevate Your Web Projects Today. Get Started Now!
A) In PHP, all temporary files, including uploaded files, are stored in the temporary files directory as specified in php.ini. It’s important to note that for uploads, these files may be deleted as soon as the script the file was uploaded to is terminated (so unless you delay that script, you probably won’t see the uploaded file).
Q) Which is the best PHP library for file uploading?
A) Several file-uploading PHP libraries are available, but the HTML5 File Upload library is considered one of the best. It’s user-friendly and popular among developers because it simplifies file uploading and validation quickly.
Q) Where can I download the PHP file upload script?
A) You can download the file-uploading script from phpfileuploader.com. This site offers an advanced and easy-to-use file-uploading script that accurately uploads files to the server without refreshing the page. With this script, you can easily upload multiple and new additional files during the upload process.
Q) How do you move uploaded files in PHP?
A) The move_uploaded_file() function can be used to move the uploaded file to a new path/directory. This function allows us to easily relocate files to a new location, even if they are newly uploaded. If the transfer is successful, it returns TRUE; if there’s any exception, it returns FALSE.
Inshal Ali
Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.