Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

How to Build a Simple JSON Web Service in PHP

Create a small PHP endpoint that accepts a request, validates input and returns JSON. Run it locally, test success and error responses, and understand production and database considerations.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can create a small PHP web service with one PHP file: accept an HTTP request, validate its input, set a JSON content type and return a JSON response with an appropriate status code. This example assumes PHP is installed locally and you have an HTTP server for testing. It does not need a database; persistence is optional.

What this endpoint does

A web service endpoint is a URL that accepts an HTTP request and returns data or performs an action. PHP runs on the server and can produce JSON or XML as well as HTML. For this tutorial, the endpoint accepts a name in a query parameter and returns a JSON greeting. A missing or invalid name produces a client-error response.

As an Amazon Associate I earn from qualifying purchases.

The example uses plain PHP rather than a framework, and keeps data in the request instead of storing it. That makes the request, validation, status code and response easy to see in one place.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you need

  • A local PHP parser/runtime.
  • A web server. For local learning and testing, PHP includes a built-in development server.
  • A browser or HTTP client, such as curl, to send a request and inspect the response.

The PHP documentation describes the runtime and web server as core components for server-side PHP use. See What is PHP and what can it do?.

Create the PHP endpoint

Create a file named index.php in a new project directory, then add this code:

<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$name = $_GET['name'] ?? '';

if (!is_string($name)) {
    http_response_code(400);
    echo json_encode(['error' => 'Name must be a single text value.']);
    exit;
}

$name = trim($name);

if ($name === '') {
    http_response_code(400);
    echo json_encode(['error' => 'The name parameter is required.']);
    exit;
}

http_response_code(200);
echo json_encode(['message' => 'Hello, ' . $name . '!']);

How the response is formed

  • header() tells the client that the response body is JSON encoded as UTF-8.
  • http_response_code() sets the HTTP status: 200 for success and 400 when the request is invalid.
  • json_encode() converts PHP arrays into valid JSON.
  • exit stops execution after an error response so the success response is not also sent.

For a request with ?name=Ada, the response body is {"message":"Hello, Ada!"}. A request with no name returns {"error":"The name parameter is required."} and status 400. In a larger service, handle encoding failures explicitly and keep response shapes consistent.

Run it locally and send a request

  1. Open a terminal in the directory containing index.php.
  2. Start PHP’s built-in server with php -S 127.0.0.1:8000.
  3. In a browser, visit http://127.0.0.1:8000/?name=Ada, or run curl -i "http://127.0.0.1:8000/?name=Ada" in another terminal.
  4. Check that the response includes a successful HTTP status, a JSON content type and the greeting object. Try curl -i "http://127.0.0.1:8000/" to check the missing-input error and its 400 status.
  5. Stop the server with Ctrl+C when you finish.

The built-in server is intended for development, testing or controlled demonstrations—not public networks or production. PHP documents that it is not a full-featured web server; by default it is single-threaded, so a blocked request can stall the application. Use a production web server and deployment setup for a public service. See PHP: Built-in web server.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate input and protect errors

Treat every value from a client as untrusted. This example checks that name is a single string, trims whitespace and rejects an empty value. Real endpoints should also decide which characters and maximum length are acceptable for their specific data, and reject malformed or out-of-range values before using them.

Return useful client-facing errors without disclosing filesystem paths, credentials, stack traces or raw exception messages. Configure PHP appropriately for the deployment environment and log diagnostic details privately. The PHP manuals cover security fundamentals and security.

When to add a database

This greeting endpoint has no state to preserve, so it does not need a database. Add persistence only when the service must store or retrieve data across requests. PHP’s PDO extension offers a consistent interface for database access, but you still need the PDO driver matching the database you choose. PDO does not rewrite SQL or emulate missing database features; it is not a complete database abstraction layer. See PHP Data Objects.

For a database-backed endpoint, use prepared statements with bound values for client-supplied data instead of building SQL by concatenating input. Keep database credentials outside the public document root, install the required PDO driver, and avoid returning database exceptions to callers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Be cautious with older examples that use a PDO DSN beginning with uri:: the PHP manual marks this DSN form deprecated as of PHP 8.5.0 because remote URI-based DSNs raise security concerns. Check the applicable guidance for your PHP version in PDO::__construct.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Prepare the service for production

Local success only confirms that the endpoint works in a development setup. Before making a service public, choose and configure a production web server, confirm the PHP version and required extensions, and deploy the code with an appropriate document root. Review error display and logging, validate all request data, and add authentication or authorization if the endpoint exposes private data or actions. A database is not a default requirement; if you add one, secure credentials and use safe query patterns.

A framework can help when an application needs routing, structured validation, middleware or shared conventions. Plain PHP is enough for a small endpoint, but you must implement those concerns yourself as the service grows. There is no single framework, API design, authentication method or hosting vendor required by the term “web service.”

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.