Every modern web application or store requires a backend responsible for secure data processing, database communication, and sending responses back to clients. PHP has been one of the most popular languages for this purpose for decades, as it is extremely flexible, quick to deploy, and supported on virtually every web hosting platform. In this article, we will look at how to build a simple yet functional PHP backend API.
Role of the Backend Server in Web Architecture
The main task of a PHP backend is to accept incoming requests from a browser or a microcontroller (e.g., ESP32), validate them, and execute the corresponding business logic or database operations.
| Component | System Role | Technology |
|---|---|---|
| Frontend (Client) | UI display and sending requests | HTML, CSS, JavaScript |
| Backend (Server) | Logic processing, security checks, validation | PHP |
| Data Layer | Persistent data storage (users, items) | MySQL / MariaDB (SQL) |
Basic Steps in Building a PHP API
When building a backend that responds to AJAX requests or connects IoT devices, we want PHP to return data in the lightweight and readable JSON format.
- Receiving Data: Read input parameters from the request (in production via `$_GET` or `$_POST`).
- Validation & Logic: Verify data integrity and execute data operations.
- Structure Preparation: Organize data into a PHP array with the appropriate status structure.
- Outputting JSON: Convert the array into a JSON string using the
json_encode()function.
Example of a Simple PHP Backend Script
The example below shows a PHP backend script that validates a product ID and returns price and stock information in JSON format. The code is tailored so you can run it immediately in our online simulator.
<?php
// Setting a test product ID (in live production you would use: $_GET['id'])
$productId = 2;
// Basic validation of product ID
if ($productId <= 0) {
$response = [
'status' => 'error',
'message' => 'Invalid or missing product ID!'
];
} else {
// Mocking database data (in practice, a MySQL query follows here)
$productsDatabase = [
1 => ['name' => 'Arduino Uno R3', 'price' => 22.50, 'stock' => 12],
2 => ['name' => 'ESP32 NodeMCU', 'price' => 8.90, 'stock' => 45],
5 => ['name' => 'DHT22 Sensor', 'price' => 4.20, 'stock' => 0]
];
// Check if the product with given ID exists
if (array_key_exists($productId, $productsDatabase)) {
$response = [
'status' => 'success',
'data' => $productsDatabase[$productId]
];
} else {
$response = [
'status' => 'error',
'message' => 'Product with this ID does not exist.'
];
}
}
// Convert PHP array into JSON format and print
echo json_encode($response, JSON_PRETTY_PRINT);
?>
Try the Code in the Online Simulator
Want to test the code and change the `$productId` value yourself? Run the example directly in our PHP Tutorial and Code Simulator.