PHP REST API Single File Upload

REST API File Upload

I am going to show you how to upload single file using REST API in PHP language. The full form of REST is Representational State Transfer. I will use POST method to upload the file. The REST API will get the file content from the client and will store the file content to a specified destination. The destination could be any location that you specify in the server.

Related Post:


PHP 8.2.7

Project Directory

It’s assumed that you have setup PHP in your system.

Now I will create a project root directory called php-rest-api-single-file-upload anywhere in your system. I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project’s root directory.

REST File Upload Code

In the header I have configured origin from where the request is allowed, so here I allow from any origin. I am using HTTP method POST for uploading file. I have also allowed several other attributes in the HTTP header.

I am only allowing a file size less than 5MB to be uploaded in the server. You can change the file size according to your needs.

The name of the key of the input file is sendfile in the client request. The file will be uploaded into the upload folder of the server.

I allow only certain types of files to be uploaded and you can change this to any file types you want to upload.

The appropriate message is shown to the client upon file upload success or failure.


header("Acess-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Acess-Control-Allow-Methods: POST");
header("Acess-Control-Allow-Headers: Acess-Control-Allow-Headers,Content-Type,Acess-Control-Allow-Methods, Authorization");

$data = json_decode(file_get_contents("php://input"), true); // collect input parameters and convert into readable format
$fileName  =  $_FILES['sendfile']['name'];
$tempPath  =  $_FILES['sendfile']['tmp_name'];
$fileSize  =  $_FILES['sendfile']['size'];
if(empty($fileName)) {
	echo json_encode(array("message" => "please select a file", "status" => false));	
} else {
	$upload_path = 'upload/'; // set upload folder path 
	$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); // get file extension
	// valid file extensions
	$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'pdf', 'docx', 'txt'); 
	// allow valid file formats
	if(in_array($fileExt, $valid_extensions)) {
		//check file does not exist in the upload folder path
		if(!file_exists($upload_path . $fileName)) {
			// check file size '5MB'
			if($fileSize < 5000000) {
				if(move_uploaded_file($tempPath, $upload_path . $fileName)) { // move file from system temporary path to the upload folder path
					echo json_encode(array("message" => "File Uploaded Successfully", "status" => true));
				} else {
					echo json_encode(array("message" => "File couldn't be uploaded", "status" => false));
			} else {		
				echo json_encode(array("message" => "Sorry, your file is too large, please upload 5 MB size", "status" => false));
		} else {		
			echo json_encode(array("message" => "Sorry, file already exists check upload folder", "status" => false));
	} else {
		echo json_encode(array("message" => "Sorry, only JPG, JPEG, PNG, GIF, PDF, DOCX &amp; TEXT files are allowed", "status" => false));

REST Client

You need REST client to test the file upload functionality. You can use any REST client tool such as Postman, Talend, SOAP UI, etc. I am not using any REST client tool, so I am writing REST client program in PHP to upload file. I am using CURL to upload file.

$data = array('sendfile' => curl_file_create('C:\java-math-round-issue.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'Word-doc.docx'));

$ch = curl_init();     
curl_setopt($ch, CURLOPT_URL, 'http://localhost/php-rest-api-file-upload.php');
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);

The above client program will upload the file in the destination.

Make sure you run the server side REST API for upload before you execute the client program.

Source Code


Leave a Reply

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