Input Validation in a Plain PHP API: How to Validate JSON Before Saving It

Illustration of validating JSON input in a plain PHP API before saving it to the database

Quick answer: Before saving anything, read the body with json_decode(file_get_contents('php://input'), true) and check that it is valid JSON. Validate required fields, types, email format and lengths, collect every error in one list, and answer 422 with that list when something fails. Normalize the data (trim, lowercase emails) and only then save it with PDO and prepared statements.

Validating incoming data is one of the most important steps before an API writes anything to the database. In a plain PHP API that receives JSON, it is not enough to take the body and run an INSERT. You need to check that required fields were sent, that formats and types make sense, and that the error response is clear for whoever consumes the API.

In this article you will build simple, organized and reusable validation in plain PHP for JSON APIs, with no framework. You can use the same base for sign-ups, logins, admin systems, mobile apps, third-party integrations and any endpoint that receives data.

In short: before saving data that comes into the API, validate required fields, formats, types, lengths, numeric limits and business rules. If something is wrong, return consistent JSON with the right HTTP status.

Why validate data before saving it?

An API should never fully trust what a user, an app or a third-party system sends. Even if the frontend validates with JavaScript, backend validation is still required: anyone can call your API directly with Postman, Insomnia, cURL, a mobile app or a script.

Common problems when the backend doesn't validate:

  • Required fields saved empty;
  • Invalid emails stored in the database;
  • Phone numbers, postal codes or dates in the wrong format;
  • Numbers arriving as text, and booleans arriving as strings;
  • Database errors shown directly to the user;
  • Crashes or security issues caused by malformed input;
  • Inconsistencies between the web frontend, the app and the API.

Backend validation is the barrier between the request and the database. Data is saved only when it is correct.

The validation flow in a plain PHP API

  1. Receive the JSON request;
  2. Decode the request body;
  3. Check that the JSON is valid;
  4. Validate required fields;
  5. Validate formats, types and business rules;
  6. Return a consistent error if anything fails;
  7. Save to the database only if everything is valid;
  8. Return a JSON success response.

Example JSON sent to the API

Imagine an endpoint that creates users. The frontend sends:

{
  "name": "Jane Smith",
  "email": "jane@example.com",
  "password": "correct-horse-battery",
  "age": 28,
  "active": true
}

Before saving, we need to check that:

  • name was sent and is not empty;
  • email was sent and has a valid format;
  • password has a minimum length;
  • age, if sent, is a positive integer;
  • active, if sent, is a boolean.

Reading JSON in plain PHP

The request body is read from php://input, and json_decode turns it into an associative array:

<?php

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

$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid JSON.',
        'errors' => [
            'json' => 'The request body is not valid JSON.'
        ]
    ]);
    exit;
}

When the body itself is broken, the right status is 400 Bad Request.

A helper for JSON responses

<?php

function jsonResponse(int $statusCode, array $data): void
{
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

Every success and error goes through the same function, so all responses share one shape.

A function that validates the input

validateUser receives the request data and returns an array of errors. An empty array means the data passed.

<?php

function validateUser(array $data): array
{
    $errors = [];

    // Name: required, text, at least 3 characters
    $name = $data['name'] ?? null;
    if (!is_string($name) || trim($name) === '') {
        $errors['name'] = 'Name is required.';
    } elseif (mb_strlen(trim($name)) < 3) {
        $errors['name'] = 'Name must be at least 3 characters long.';
    }

    // Email: required and valid
    $email = $data['email'] ?? null;
    if (!is_string($email) || trim($email) === '') {
        $errors['email'] = 'Email is required.';
    } elseif (!filter_var(trim($email), FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Enter a valid email address.';
    }

    // Password: required, at least 8 characters
    $password = $data['password'] ?? null;
    if (!is_string($password) || $password === '') {
        $errors['password'] = 'Password is required.';
    } elseif (mb_strlen($password) < 8) {
        $errors['password'] = 'Password must be at least 8 characters long.';
    }

    // Age: optional, but if sent it must be a positive integer
    if (array_key_exists('age', $data) && $data['age'] !== null) {
        if (!is_int($data['age'])) {
            $errors['age'] = 'Age must be a whole number.';
        } elseif ($data['age'] <= 0) {
            $errors['age'] = 'Age must be greater than zero.';
        }
    }

    // Active: optional, but if sent it must be true or false
    if (array_key_exists('active', $data) && !is_bool($data['active'])) {
        $errors['active'] = 'Active must be true or false.';
    }

    return $errors;
}

Checking is_string before trim matters: if a client sends "name": ["x"], calling trim() on an array throws a TypeError in PHP 8 and your API answers with a 500 instead of a clean 422.

Keeping validation in its own function separates input rules from database logic, which makes both easier to maintain.

Using the validation before saving

<?php

// jsonResponse() and validateUser() from the examples above

$data = json_decode(file_get_contents('php://input'), true);

if (json_last_error() !== JSON_ERROR_NONE) {
    jsonResponse(400, [
        'success' => false,
        'message' => 'Invalid JSON.',
        'errors' => ['json' => 'The request body is not valid JSON.']
    ]);
}

// "123" or "true" are valid JSON too, but not an object
if (!is_array($data)) {
    jsonResponse(400, [
        'success' => false,
        'message' => 'Invalid request.',
        'errors' => ['body' => 'Send a JSON object.']
    ]);
}

$errors = validateUser($data);

if (!empty($errors)) {
    jsonResponse(422, [
        'success' => false,
        'message' => 'Some fields are invalid.',
        'errors' => $errors
    ]);
}

// From here on, the data is valid and can be normalized and saved

Why 422 for validation errors?

When the JSON is malformed, the request itself is broken: 400 Bad Request fits. When the JSON is fine but the values break your rules, use 422 Unprocessable Content (formerly "Unprocessable Entity").

This body is valid JSON with invalid values:

{
  "name": "",
  "email": "not-an-email",
  "password": "123"
}

So the response can be:

{
  "success": false,
  "message": "Some fields are invalid.",
  "errors": {
    "name": "Name is required.",
    "email": "Enter a valid email address.",
    "password": "Password must be at least 8 characters long."
  }
}

Returning every error at once lets the frontend show a message next to each field, and the user fixes everything in one go.

Normalizing data before saving

After validating, normalize the values to a standard format:

  • Remove extra spaces with trim;
  • Lowercase emails with strtolower;
  • Strip formatting from phone numbers and postal codes;
  • Cast numbers to the right type;
  • Set defaults for optional fields.
<?php

$user = [
    'name' => trim($data['name']),
    'email' => strtolower(trim($data['email'])),
    'password_hash' => password_hash($data['password'], PASSWORD_DEFAULT),
    'age' => $data['age'] ?? null,
    'active' => $data['active'] ?? true
];

This keeps the database clean and avoids duplicates caused by small differences, such as upper case letters in an email.

Saving with PDO after validation

<?php

try {
    $pdo = new PDO(
        'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
        'user',
        'password',
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );

    $sql = "INSERT INTO users (name, email, password_hash, age, active)
            VALUES (:name, :email, :password_hash, :age, :active)";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':name' => $user['name'],
        ':email' => $user['email'],
        ':password_hash' => $user['password_hash'],
        ':age' => $user['age'],
        ':active' => $user['active'] ? 1 : 0
    ]);

    jsonResponse(201, [
        'success' => true,
        'message' => 'User created.',
        'data' => ['id' => (int) $pdo->lastInsertId()]
    ]);

} catch (PDOException $e) {
    error_log('Error saving user: ' . $e->getMessage());

    jsonResponse(500, [
        'success' => false,
        'message' => 'Internal error while saving the data.'
    ]);
}

Validation does not replace prepared statements; see how to prevent SQL injection with PDO.

Checking whether the email already exists

Some rules depend on the database, such as rejecting an email that is already registered:

<?php

function emailExists(PDO $pdo, string $email): bool
{
    $stmt = $pdo->prepare("SELECT 1 FROM users WHERE email = :email LIMIT 1");
    $stmt->execute([':email' => $email]);
    return (bool) $stmt->fetchColumn();
}

if (emailExists($pdo, $user['email'])) {
    jsonResponse(422, [
        'success' => false,
        'message' => 'Some fields are invalid.',
        'errors' => ['email' => 'This email is already registered.']
    ]);
}

This check alone has a gap: two sign-ups arriving at the same moment can both pass it. Add a UNIQUE index on users.email and, in the catch, treat SQLSTATE 23000 (duplicate key) as the same 422 error. The index is the real guarantee; the query just gives a friendlier message first.

Moving validation into its own file

As the API grows, keep validation out of the endpoint file:

/api
  /helpers
    response.php
  /validators
    UserValidator.php
  /controllers
    UserController.php
  index.php
<?php

class UserValidator
{
    public static function validateSignup(array $data): array
    {
        $errors = [];

        if (!is_string($data['name'] ?? null) || trim($data['name']) === '') {
            $errors['name'] = 'Name is required.';
        }

        if (!is_string($data['email'] ?? null) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Enter a valid email address.';
        }

        if (!is_string($data['password'] ?? null) || mb_strlen($data['password']) < 8) {
            $errors['password'] = 'Password must be at least 8 characters long.';
        }

        return $errors;
    }
}

And in the endpoint:

<?php

require_once __DIR__ . '/../validators/UserValidator.php';

$errors = UserValidator::validateSignup($data);

if (!empty($errors)) {
    jsonResponse(422, [
        'success' => false,
        'message' => 'Some fields are invalid.',
        'errors' => $errors
    ]);
}

For where this fits in a full API (router, controllers, authentication), see how to create a REST API in plain PHP.

Does frontend validation replace backend validation?

No. Frontend validation improves the user experience: it can say right away that an email is invalid or a password is too short. But anyone can skip the frontend and call the API directly.

  • Frontend: validates for a better user experience;
  • Backend: validates to protect the application and the database.

Validation checklist for a PHP API

  • Is the request body valid JSON, and is it an object?
  • Were the required fields sent, and are they not empty?
  • Is each field the expected type (string, integer, boolean)?
  • Is the email format valid?
  • Does the password meet the minimum length?
  • Are dates in a valid format?
  • Are phone numbers and postal codes normalized?
  • Is there a duplicate check, backed by a unique index, where needed?
  • Is the error response JSON, with the right HTTP status?
  • Are internal errors logged instead of shown?

Common mistakes when validating data in PHP

1. Relying only on JavaScript

JavaScript helps the interface but doesn't protect the backend. Always validate again in PHP.

2. Saving before validating everything

Validation must happen before any database write.

3. Returning errors as HTML

If the API returns HTML instead of JSON, the frontend breaks when it tries to parse the response. See how to find the cause of a PHP 500 error when that happens.

4. Showing the real database error to the user

Database messages can reveal table names, columns and internal details. Log them and return a generic message.

5. Calling string functions on values that may not be strings

JSON can carry arrays, numbers and null where you expect text. Check the type first.

Example of a final success response

{
  "success": true,
  "message": "User created.",
  "data": {
    "id": 15
  }
}

Conclusion

Validating input in a plain PHP API prevents bad data, protects the database and improves the quality of the whole application. Whenever the API receives JSON, check that the body is valid, validate required fields, types and formats, normalize the data and only then save it.

With a well-organized validation function, consistent JSON responses and the right HTTP status codes, you get a professional API in plain PHP, no framework required.

Frequently asked questions about input validation in PHP APIs

Do I need to validate in PHP if the frontend already validates?

Yes. Frontend validation improves the experience; PHP validation protects the API and the database. Never rely only on the browser.

Which HTTP status should I use for validation errors?

Use 400 Bad Request for invalid JSON and 422 Unprocessable Content for valid JSON with invalid fields.

Can I save first and validate later?

No. Validation must happen before any write to the database.

How do I validate an email in PHP?

Use filter_var with FILTER_VALIDATE_EMAIL:

<?php

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo 'Invalid email';
}

Does validation prevent SQL injection?

It reduces bad input, but it doesn't replace prepared statements. To prevent SQL injection, use PDO with bound parameters.

Should I return all errors at once or only the first one?

For forms and APIs used by a frontend, return all of them at once, so the user can fix everything in one try.

More in PHP