How to upload file using rest API in PHP

Webs Codex
5 min readOct 10, 2023

In this tutorial you will learn how to upload files using REST API in PHP web application. We don’t use a framework, just PHP. 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.

File uploading is a common feature that must be implemented in many web applications. This guide will show you step by step how to create a PHP application that shares the /uploads file. PHP endpoint that accepts POST requests with multipart data/forms containing file data.

Project Directory

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

 // How-to-upload-file-using-rest-API-PHP/
|__ index.php
|__ config.php

Create Database and Table by SQL query

We need to create database and table, so here I create webscodex database and table. table_images table holds the records which will be save in table_images table and Upload file in REST API using PHP. You can simply create table as following SQL query.

-- Database: `webscodex`
-- --------------------------------------------------------
-- Table structure for table `table_images`
--

CREATE TABLE `table_images` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`image` varchar(100) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

INSERT INTO `table_images` (`id`, `image`, `created_at`) VALUES
(1, 'WC-652286926d395.png', '2023-10-08 10:37:27'),
(2, 'WC-652286f3d0b6f.png', '2023-10-08 10:39:47');

Create Database Configuration

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create config.php file on your project and put bellow code:

config.php

<?php

// Database configuration
define('DBSERVER', 'localhost');
define('DBUSERNAME', 'root');
define('DBPASSWORD', '');
define('DBNAME', 'webscodex');

// Create database connection
$con = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);

// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}

?>

REST API File Upload Code

In the header I have configured the origin from which the request is allowed, so here I allow any origin. I am using HTTP POST method to upload the file. I also allowed a few other attributes in the HTTP header.

  1. I only allow files smaller than 2 MB to be uploaded to the server. You can change the file size according to your needs.
  2. The input file key name in the client request is file. The file is uploaded to the downloads folder on the server.
  3. I only allow certain file types to be uploaded, and you can change it to any file type you want to upload.
  4. Upload image file in table in using REST API in PHP.

index.php

<?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");

$fileName = $_FILES['file']['name'];
$tempPath = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];

$requertMethod = $_SERVER['REQUEST_METHOD'];

if ($requertMethod == 'POST') {

if(!empty($fileName)) {

$upload_path = 'uploads/'; // set upload folder path
$server_url = "http://localhost/BlogPost/How-to-upload-file-using-rest-API-PHP/uploads";

// Generate random file name
$fileExt = explode('.', $fileName);
$fileActExt = strtolower(end($fileExt));
$fileName = "WC-".uniqid().".".$fileActExt;

// valid file extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');

// Include database connection file
include("config.php");

// allow valid file formats
if(in_array($fileActExt, $valid_extensions)) {
//check file does not exist in the upload folder path
if(!file_exists($upload_path . $fileName)) {
// check file size '2MB'
if($fileSize < 2000000 && $fileError == 0) {
// move file from system temporary path to the upload folder path
if(move_uploaded_file($tempPath, $upload_path . $fileName)) {
// Insert Into table in database
$query = "INSERT INTO table_images (image) VALUES('$fileName')";
if ($con->query($query)) {
$response = [
'status' => true,
'message' => 'File Uploaded Successfully',
"url" => $server_url."/".$fileName
];
}
} else {
$response = [
'status' => false,
'message' => "File couldn't be uploaded",
];
}
} else {
$response = [
'status' => false,
'message' => "Your file is too large, please upload 2 MB size",
];
}
} else {
$response = [
'status' => false,
'message' => "File already exists check upload folder",
];
}
} else {
$response = [
'status' => false,
'message' => "Only JPG, JPEG, PNG, GIF, PDF, DOCX &amp; TEXT files are allowed",
];
}

}else {
$response = [
'status' => false,
'message' => "Please select a file",
];
}
}else{
$response = [
'status' => false,
'message' => $requertMethod . ' Method now allowed',
];
}

echo json_encode($response);

Let us test the PHP API using Postman, open the Postman and use the following URL and click on the Send button to check the output.

METHOD POST

URL NAME http://localhost/BlogPost/How-to-upload-file-using-rest-API-PHP/index.php

Frequently Asked Questions

How to upload file using REST API?

I want to upload file using REST Api. As per my reserch there are two ways for this.
1.
by passing base64 encoded string into form-data
2. by passing file upload parameter into form-data

How to upload a file in PHP API?

1. I only allow files smaller than 2 MB to be uploaded to the server. You can change the file size according to your needs.
2. The input file key name in the client request is file. The file is uploaded to the downloads folder on the server.
3. I only allow certain file types to be uploaded, and you can change it to any file type you want to upload.
4. Upload image file in table in using REST API in PHP.

Can you upload a file in an API?

There are three ways to upload files to an API: As the only content. As part of a multipart/form-data payload, mixed with other “normal” data. As part of a multipart/mixed payload, mixed with other multiple uploads.

Conclusion

In this article, I have explain the process of How to upload file using REST API using PHP with MySqli. I have tried to very simple way to implement to upload file in database. You can easily extend the functionality according to your needs.

You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions or problems about this tutorial, please comment on the form below.😊

--

--

Webs Codex

Webs Codex is programming and web development blog