PHP file Upload- Using AJAX

Handling PHP files and directories is an important component of PHP programming. If you want to make an application where you want users to upload some documents and save in the server, then you can create the PHP file upload using AJAX.

In this article you will learn step by step process of uploading some specific type of files. You can always replace the types of files with the types that you desire to allow through your application.

Step 1- Create an interface

The first step is to create an HTML interface which you will give to your users for PHP file upload. You need to use the INPUT TYPE ‘FILE’ to create a file Upload Button. When this button is clicked a dialog box is displayed asking users to select a file to upload.

<HTML>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<BODY>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

function sendFile(str) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
</script>
<div class="container">
<div class="row">
	<div class="col">
	<form method="post" action="upload.php" enctype="multipart/form-data">
	Select a File 
	<div class="form-group">
			<br><label for="exampleFormControlFile1">Report File(allowed formats .pdf, .docx,.xlsx,.pptx)</label>
			<input type="file" name="fileControl" class="form-control-file" id="fileControl">
	</div>	
	<br><br><center><button class="btn btn-success"  name="submit" id="exampleSubmit" value="Submit" onclick="sendFile()" style="border-color:rgb(7, 109, 175);background-color:rgb(7, 109, 175);">Submit</button></center>
	</form>
</div>
</div>
</div>
</BODY>

This code uses AJAX XMLHttpRequest to communicate with server without the need to refresh the page after a user has initiated an event. The event can like clicking a button.

Interface PHP file upload
File-Selected-for-upload

Step 2- Create a Folder in PHP Application folder to store uploaded files

The second step is to define the target folder in your application folder. We have created a folder named docs in c:\xampp\htdocs\upload. The upload folder in this path is the PHP project folder.

Step 3- Create the PHP file that uploads a file selected by a User

In the third and last step copy the following php code and save as upload.php  in folder c:\xampp\htdocs\upload.

<?php
session_start();
$fName=$_FILES['fileControl'];
$save_dir = "docs/";
$save_file = $save_dir.basename($fName["name"]);
$uploadStatus = 1;
$FileType = strtolower(pathinfo($save_file,PATHINFO_EXTENSION));

// Check if duplicate file being uploaded
if (file_exists($save_file)) {
    echo "Sorry, file already exists.";
    $uploadStatus = 0;
}

// Restrict file formats to be uploaded. Change the file types for your need
if($FileType != "pdf" && $FileType != "xlsx" && $FileType != "docx"
&& $FileType != "pptx" ) {
    echo "<script>alert('Sorry, only pdf, xlsx, docx & pptx files are allowed.');</script>";
    $uploadStatus = 0;
}
// Check the $uploadStatus. If it is 0 display the error message
if ($uploadStatus == 0) {
    echo "<script>alert('Sorry, your file was not uploaded.');</script>";
	header('refresh:0;url=uploadfile.php');
// Upload file when no error happened
} else {
    if (move_uploaded_file($fName["tmp_name"], $save_file)) {
        echo "<script>alert( 'The file ". basename( $fName["name"]). " has been uploaded.');</script>";
    } else {
         echo "<script>alert('Sorry, there was an error in file uploaded.');</script>";
		 header('refresh:0;url=uploadfile.php');
    }
}
?>

This script accepts a file name from the uploadfile.php and checks whether the file already exists in the target folder or not. It also checks for the allowed file type of the file being uploaded. If any of these things goes wrong the PHP file upload process is terminated giving the error message to the user.

PHP File Uploaded Successfully
Allowed File Types
message file not upload

After executing the application in browser, if everything is right, you will be able to see the selected and uploaded file in  c:\xampp\htdocs\upload\docs folder.

Final Words

So, you can see that it is very easy to create a web interface for your clients to upload a file, image or video on your website. It has been implemented as PHP file upload using HTML file tag, Bootstrap CSS and a little bit of AJAX.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *