PHPackages                             alexcane/php-json-response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. alexcane/php-json-response

ActiveLibrary[HTTP &amp; Networking](/categories/http)

alexcane/php-json-response
==========================

PHP library for standardized JSON response formatting and password validation with preset security levels

v1.0.1(5mo ago)07MITPHPPHP ^7.4 || ^8.0CI passing

Since Oct 16Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/alexcane/php-json-response)[ Packagist](https://packagist.org/packages/alexcane/php-json-response)[ Docs](https://github.com/alexcane/php-json-response)[ RSS](/packages/alexcane-php-json-response/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

[![Tests](https://github.com/alexcane/php-json-response/actions/workflows/ci.yml/badge.svg)](https://github.com/alexcane/php-json-response/actions/workflows/ci.yml/badge.svg)[![License](https://camo.githubusercontent.com/aa486122ec0d6955629fec847a43c0e10158046de55c143ae424894467f57d55/68747470733a2f2f706f7365722e707567782e6f72672f616c657863616e652f7068702d6a736f6e2d726573706f6e73652f6c6963656e7365)](https://packagist.org/packages/alexcane/php-json-response)

PHPJsonResponse
===============

[](#phpjsonresponse)

Personal PHP Class Library for standardized JSON response formatting and password validation.

Features
--------

[](#features)

- ✅ Standardized JSON response structure
- ✅ Automatic data sanitization (trim strings, convert 'true'/'false' to booleans)
- ✅ Built-in password validation with preset security levels
- ✅ Multi-language support (French/English)
- ✅ Fully tested with PHPUnit

Installation
------------

[](#installation)

```
composer require alexcane/php-json-response
```

Usage
-----

[](#usage)

### JsonResp Class

[](#jsonresp-class)

The main class for handling JSON responses with consistent structure.

#### Basic Example

[](#basic-example)

```
use PhpJsonResp\JsonResp;

// Create instance with data
$resp = new JsonResp(['email' => '  user@example.com  ', 'active' => 'true']);

// Data is automatically sanitized
$data = $resp->getData();
// ['email' => 'user@example.com', 'active' => true]

// Add validation errors
if (empty($data['email'])) {
    $resp->addErrMsg('Email is required');
}

// Check for errors
if ($resp->isError()) {
    echo $resp->returnResponse(true); // Return as JSON string
    exit;
}

// Return successful response
echo $resp->returnResponse(true);
```

#### Response Structure

[](#response-structure)

All responses follow this format:

```
{
    "status": "success",
    "error_msg": [],
    "data": {
        "email": "user@example.com",
        "active": true
    }
}
```

On error:

```
{
    "status": "error",
    "error_msg": ["Email is required", "Password is too short"],
    "data": {...}
}
```

#### Available Methods

[](#available-methods)

```
// Data management
$resp->setData(['key' => 'value']);
$resp->getData();
$resp->clearData();

// Error management
$resp->addErrMsg('Error message');
$resp->setErrMsg(['Error 1', 'Error 2']);
$resp->getErrMsg();
$resp->errorCount();

// Validation
$resp->isSuccess(); // true if no errors
$resp->isError();   // true if has errors

// Custom response field
$resp->setResponse('Custom data or HTML');
$resp->getResponse();

// Return response
$resp->returnResponse();      // Returns array
$resp->returnResponse(true);  // Returns JSON string
```

### PasswordValidator Class

[](#passwordvalidator-class)

Extension of JsonResp for password validation with configurable security levels.

#### Basic Example

[](#basic-example-1)

```
use PhpJsonResp\PasswordValidator;

// Create instance (default: light config, French messages)
$validator = new PasswordValidator(['password' => $_POST['password']]);

// Validate password
if (!$validator->isValidPassword($_POST['password'])) {
    echo $validator->returnResponse(true);
    exit;
}

// Password is valid
echo $validator->returnResponse(true);
```

#### Security Levels

[](#security-levels)

**Light Config** (default)

```
$validator->setLightConfig();
// - Min 6 characters
// - Requires digits
// - Uppercase optional
// - Symbols optional
```

**Medium Config**

```
$validator->setMediumConfig();
// - Min 10 characters
// - Requires digits
// - Requires uppercase
// - Requires symbols
```

**Hard Config**

```
$validator->setHardConfig();
// - Min 20 characters
// - Requires digits
// - Requires uppercase
// - Requires symbols
```

**Custom Config**

```
$validator->setCustomConfig(
    min: 8,
    max: 50,
    uppercase: true,
    digits: true,
    symbols: false
);
```

#### Multi-language Support

[](#multi-language-support)

```
// French (default)
$validator = new PasswordValidator([], 'fr_FR');
// Error messages: "Mot de passe invalide", "6 caractères minimum", etc.

// English
$validator = new PasswordValidator([], 'en_US');
// Error messages: "Invalid Password", "at least 6 characters long", etc.
```

#### Get Generated Regex

[](#get-generated-regex)

```
$validator->setMediumConfig();
$regex = $validator->getRegex();
// Returns: /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?:{}|-_])[A-Za-z\d!@#$%^&*(),.?:{}|-_]{10,100}$/
```

#### Complete Validation Example

[](#complete-validation-example)

```
use PhpJsonResp\PasswordValidator;

$validator = new PasswordValidator($_POST, 'en_US');
$validator->setMediumConfig();

// Validate password
if (!$validator->isValidPassword($_POST['password'])) {
    header('Content-Type: application/json');
    http_response_code(400);
    echo $validator->returnResponse(true);
    exit;
}

// Password is valid, continue with registration
$user = createUser($validator->getData());

$validator->setResponse(['user_id' => $user->id]);
header('Content-Type: application/json');
echo $validator->returnResponse(true);
```

Response Structure
------------------

[](#response-structure-1)

- `status`: string - 'error' or 'success'
- `error_msg`: array - List of error messages
- `data`: array - Validated/processed data (omitted if empty)
- `response`: mixed - Custom response data (omitted if empty)

Requirements
------------

[](#requirements)

- PHP ^7.4 || ^8.0
- ext-json

Testing
-------

[](#testing)

```
# Run all tests
composer test

# Run with coverage
composer test:coverage
```

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) file for details.

Author
------

[](#author)

Alexandre Cane -

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance69

Regular maintenance activity

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~401 days

Total

2

Last Release

179d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4d44e61b6e38602d7d6e0da5c52832d5017898060d5c3561838a1e47411a0067?d=identicon)[alexcane](/maintainers/alexcane)

---

Top Contributors

[![alexcane](https://avatars.githubusercontent.com/u/12563984?v=4)](https://github.com/alexcane "alexcane (24 commits)")

---

Tags

httpresponsejsonapivalidationrestsecuritypassword

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/alexcane-php-json-response/health.svg)

```
[![Health](https://phpackages.com/badges/alexcane-php-json-response/health.svg)](https://phpackages.com/packages/alexcane-php-json-response)
```

###  Alternatives

[jsor/hal-client

A lightweight client for consuming and manipulating Hypertext Application Language (HAL) resources.

2425.9k1](/packages/jsor-hal-client)[guanguans/laravel-api-response

Normalize and standardize Laravel API response data structure. - 规范化和标准化 Laravel API 响应数据结构。

485.6k](/packages/guanguans-laravel-api-response)[elementaryframework/water-pipe

URL routing framework and requests/responses handler for PHP

254.6k4](/packages/elementaryframework-water-pipe)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
