In this tutorial, You will learn to create the image upload rest API using PHP & MySQL which will be very useful to integrate with frontend languages such as react js, angular js & more.
The Custom PHP Image Upload API will be used for uploading a single image at a time to the folder & MySQL Database. So, You can use it for the user profile image, image gallery & content image.
Step to Create a Custom Image Upload Restful Api using PHP & MySQL
Now, Let’s start coding with the given some simple steps –
1. Create a folder structure
First of all, Create the following folder structure in your system.
- public/image – It is a directory to upload images
- database.php – This file is created for the database connection
- api.php – This file is created for the API request such as post.
- ImageUploadApi.php – This file is created for writing the image uploading script.
myproject/rest/ |__public/images/ |__database.php |__api.php |__ImageUploadApi.php |
Create MySQL Database & table
Now, Write the PHP code to connect to the MySQL database.
- $host – assign your database hostname
- $user – assign your database username
- $password – assign your database password
- $database – assign your database name
File Name – database.php
<?php $host = "localhost"; $user = "root"; $password = ""; $database = "phprestapi"; $conn = new mysqli($host, $user, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
Create Image Upload API
The code defines a PHP class named ImageUploadApi
with a constructor setting database connection and image table properties.
The uploadImage
method handles file uploads, checks for allowed file types, and provides information about the upload, returning an associative array.
The create
method, designed for handling POST requests, utilizes the uploadImage
method and inserts file details into the specified database table, returning a JSON response indicating success or failure.
File Name – ImageUploadApi.php
<?php class ImageUploadApi { private $conn; private $imageTable; public function __construct($conn) { $this->conn = $conn; $this->imageTable = 'imageupload'; } public function uploadImage() { $error = false; $msg = null; $uploadTo = "public/images/"; $allowFileType = array('jpg','png','jpeg'); $fileName = $_FILES['image']['name']; $tempPath = $_FILES["image"]["tmp_name"]; $basename = basename($fileName); $originalPath = $uploadTo.$basename; $fileType = pathinfo($originalPath, PATHINFO_EXTENSION); if(!empty($fileName)){ if(in_array($fileType, $allowFileType)){ if(!move_uploaded_file($tempPath, $originalPath)){ $msg = 'Image Not uploaded ! try again'; $error = true; } }else{ $msg = 'Image type is not allowed'; $error = true; } } else { $msg = 'Image is required'; $error = true; } $imageInfo = [ "error" => $error, "msg" => $msg, "filename" => $fileName, "filepath" => $originalPath ]; return $imageInfo; } public function create() { header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST"); header("Content-Type: application/json"); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_FILES['image'])) { $uploadImage = $this->uploadImage(); $success = false; if (!$uploadImage['error']) { // table name for admin profiles $query = "INSERT INTO " . $this->imageTable; $query .= " (filename, filepath) VALUES (?,?)"; $stmt = $this->conn->prepare($query); $stmt->bind_param("ss", $uploadImage['filename'], $uploadImage['filepath']); if ($stmt->execute()) { $success = true; $stmt->close(); } } $data = [ 'Errormsg' => $uploadImage['msg'] ?? '', 'success' => $success ]; return json_encode($data); } } } } ?>
- The class
ImageUploadApi
is declared, encapsulating functionality related to image uploads in PHP. - Private properties,
$conn
for the database connection, and$imageTable
representing the image table name are declared within the class. - The constructor
__construct
initializes the class instance with a provided database connection and sets the image table name. - The
uploadImage
method manages the file upload process:- Variables like
$error
,$msg
,$uploadTo
, and$allowFileType
are set for error tracking, messages, target directory, and allowed file types. - Information about the uploaded file, such as its name, temporary path, and file type, is retrieved.
- Conditions are checked to ensure a non-empty file name, an allowed file type, and successful file movement, updating error messages and flags accordingly.
- An associative array,
$imageInfo
, is constructed with error status, messages, filename, and file path, and it is returned.
- Variables like
- The
create
method is intended for handling POST requests:- HTTP headers are set to allow cross-origin requests and specify allowed methods and response content type.
- Checks if the request method is POST and if an image file is present.
- Calls
uploadImage
to obtain details about the uploaded image. - If the upload is successful, constructs an SQL query to insert the image details into the specified database table.
- Returns a JSON-encoded response indicating any error messages and the success status.
Call Image Upload API
This PHP code initiates a script that utilizes a database connection established in the ‘database.php’ file and an ‘ImageUploadAPI’ class defined in ‘ImageUploadAPI.php’.
It then creates an instance of the ‘ImageUploadAPI’ class with the provided database connection, and echoes the result of calling the ‘create’ method of the ‘ImageUploadAPI’ class, suggesting that it likely performs an operation related to image uploads within the associated database.
File Name – index.php
<?php require_once 'database.php'; require_once 'ImageUploadAPI.php'; $api = new ImageUploadAPI($conn); echo $api->create(); ?>
Call PHP Rest API
Now, You can call the following endpoint URL in your frontend language to upload a single image at a time to folder and the database
http://localhost/myproject/rest/upload-image/api.php