PHP REST API Multiple Files Upload

REST API Multiple Files Upload

In this tutorial I am going to show you an example how to upload multiple files using REST (Representational State Transfer) API. I will also create a client program to upload multiple files through REST API. I am not using any Postman or SOAP UI tool to test the file upload functionality, so I am going to create a client program.

I am going to use HTTP POST method for file upload functionality and the uploaded files will be stored in a specific destination folder.

Related Post:

Prerequisites

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-multiple-files-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 each file size to be maximum of 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 with an array of files 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 for all files that are to be uploaded.

<?php

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
		
if(empty($_FILES['sendfile']['name'][0])) {
	echo json_encode(array("message" => "please select a file"));	
} else {
	$upload_path = 'upload/'; // set upload folder path 
	
	// valid file extensions
	$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'pdf', 'docx', 'txt');
	
	$total = count($_FILES['sendfile']['name']);
	
	$msg = array();
	
	for( $i=0 ; $i < $total ; $i++ ) {
		$fileName  =  $_FILES['sendfile']['name'][$i];
		$tempPath  =  $_FILES['sendfile']['tmp_name'][$i];
		$fileSize  =  $_FILES['sendfile']['size'][$i];
	
		$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); // get file extension
		
		// 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
						$msg[$i] = "File Uploaded Successfully: " . $fileName;
					} else {
						$msg[$i] = "File couldn't be uploaded: " . $fileName;
					}
				} else {
					$msg[$i] = "Sorry, your file is too large, please upload up to 5 MB in size: " . $fileName;
				}
			} else {
				$msg[$i] = "Sorry, file already exists check upload folder: " . $fileName;
			}
		} else {
			$msg[$i] = "Sorry, only JPG, JPEG, PNG, GIF, PDF, DOCX &amp; TEXT files are allowed: " . $fileName;
		}
	}

	echo json_encode($msg);
}

REST Client

I am writing a client program or a REST client to test the multiple files 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 multiple files. I am using CURL to upload files.

Even you can use any one of the commented code snippets to upload multiple files from the below source code.

<?php
    
/*$data = array('sendfile[0]' =>
		curl_file_create('C:\MyDocs\java-math-round-issue.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'Word-doc.docx'),
		'sendfile[1]' => curl_file_create('C:\MyDocs\myphoto.jpg', 'image/jpeg', 'mine.jpg'));*/
		
/*$data = array('sendfile[0]' =>
		new cURLFile('C:\MyDocs\java-math-round-issue.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'Word-doc.docx'),
		'sendfile[1]' => new cURLFile('C:\MyDocs\myphoto.jpg', 'image/jpeg', 'mine.jpg'));*/

$data = array();
$data['sendfile[0]'] = curl_file_create('C:\MyDocs\java-math-round-issue.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'Word-doc.docx');
$data['sendfile[1]'] = curl_file_create('C:\MyDocs\myphoto.jpg', 'image/jpeg', 'mine.jpg');

$ch = curl_init();     
curl_setopt($ch, CURLOPT_URL, 'http://localhost/php-rest-api-files-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);
curl_close($ch);

The above client program will upload multiple files in the specified destination.

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

Source Code

Download

Leave a Reply

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