PHPackages                             arraypress/wp-request-utils - 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. arraypress/wp-request-utils

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

arraypress/wp-request-utils
===========================

A lean WordPress library for request detection and handling

115PHP

Since Jan 31Pushed 3mo agoCompare

[ Source](https://github.com/arraypress/wp-request-utils)[ Packagist](https://packagist.org/packages/arraypress/wp-request-utils)[ RSS](/packages/arraypress-wp-request-utils/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

WordPress Request Utilities
===========================

[](#wordpress-request-utilities)

A lightweight WordPress library for request type detection, header handling, and safe request variable management. Perfect for conditional logic, security, and API handling.

Features
--------

[](#features)

- 🎯 **Clean API**: WordPress-style snake\_case methods with consistent interfaces
- 🔍 **Request Detection**: Identify admin, AJAX, REST, cron, frontend, CLI, and more
- 🌐 **Header Management**: Safe header access with CloudFlare and proxy support
- 🛡️ **Safe Variables**: Sanitized access to $\_GET, $\_POST, $\_REQUEST, and JSON body
- 📍 **Real IP Detection**: Get client IP behind proxies and CloudFlare
- 🔄 **Cached Results**: Efficient variable sanitization with caching
- ⚡ **WordPress Native**: Uses core WordPress functions when available

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

[](#requirements)

- PHP 7.4 or later
- WordPress 5.0 or later

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

[](#installation)

```
composer require arraypress/wp-request-utils
```

Basic Usage
-----------

[](#basic-usage)

### Request Type Detection

[](#request-type-detection)

```
use ArrayPress\RequestUtils\Request;

// Check single request type
if ( Request::is( 'admin' ) ) {
    // Running in WordPress admin
}

if ( Request::is( 'ajax' ) ) {
    // Handle AJAX request
}

if ( Request::is( 'rest' ) ) {
    // REST API request
}

// Check multiple types at once (OR logic)
if ( Request::is( [ 'admin', 'ajax' ] ) ) {
    // Either admin OR ajax request
}

// Available types: admin, ajax, cron, frontend, json, rest, cli, editor, api
```

### Frontend Detection

[](#frontend-detection)

```
// Frontend = NOT admin, ajax, cron, rest, api, or cli
if ( Request::is_frontend() ) {
    // Public-facing request
}

// CLI detection
if ( Request::is_cli() ) {
    // Running from command line (WP-CLI)
}

// Block editor detection
if ( Request::is_editor() ) {
    // Block/Gutenberg editor context
}
```

### SSL &amp; CloudFlare Detection

[](#ssl--cloudflare-detection)

```
// SSL detection (includes CloudFlare support)
if ( Request::is_ssl() ) {
    // Secure HTTPS connection
}

// CloudFlare detection
if ( Request::is_cloudflare() ) {
    // Request is behind CloudFlare
}

// API request detection (REST or custom API headers)
if ( Request::is_api() ) {
    // REST request or has API headers (x-api-key, authorization, etc.)
}
```

### HTTP Method Handling

[](#http-method-handling)

```
// Get current method
$method = Request::get_method(); // "GET", "POST", "PUT", "DELETE", etc.

// Check method
if ( Request::is_method( 'POST' ) ) {
    // Handle POST request
}

// Check multiple methods
if ( Request::is_method( [ 'PUT', 'PATCH' ] ) ) {
    // Handle update request
}
```

### Header Management

[](#header-management)

```
// Get header value (case-insensitive)
$auth = Request::get_header( 'authorization' );
$content_type = Request::get_header( 'content-type', 'text/html' );

// Check if header exists
if ( Request::has_header( 'x-api-key' ) ) {
    $api_key = Request::get_header( 'x-api-key' );
}

// Get real client IP (handles proxies and CloudFlare)
$client_ip = Request::get_client_ip();
```

### Safe Request Variables

[](#safe-request-variables)

```
// Get sanitized request variables
$search  = Request::get_var( 'search', '' );
$page    = Request::get_var( 'page', 1 );
$filters = Request::get_var( 'filters', [] );

// Specify request method
$post_data = Request::get_var( 'data', null, 'post' );
$get_param = Request::get_var( 'param', 'default', 'get' );

// Check if variable exists
if ( Request::has_var( 'action' ) ) {
    $action = Request::get_var( 'action' );
}

// Get all sanitized variables
$all_get     = Request::get_get_vars();
$all_post    = Request::get_post_vars();
$all_request = Request::get_request_vars();
```

### JSON Body Handling

[](#json-body-handling)

```
// Get JSON request body (for REST/API endpoints)
$data = Request::get_json_body(); // Returns array or null

// Get as object instead of array
$data = Request::get_json_body( false ); // Returns object or null

// Example API endpoint
if ( Request::is_method( 'POST' ) && Request::has_header( 'content-type' ) ) {
    $json = Request::get_json_body();
    if ( $json && isset( $json['action'] ) ) {
        // Process JSON payload
    }
}
```

### REST API Helpers

[](#rest-api-helpers)

```
// Get current REST route
$route = Request::get_rest_route(); // e.g., "/wp/v2/posts" or null

// Check if specific REST endpoint
if ( Request::is( 'rest' ) ) {
    $route = Request::get_rest_route();
    if ( $route && str_contains( $route, '/my-plugin/' ) ) {
        // Handle custom REST endpoint
    }
}
```

### Pagination Helper

[](#pagination-helper)

```
// Get current page for pagination
$current_page = Request::get_current_page(); // Default parameter: 'paged'
$custom_page  = Request::get_current_page( 'page_num' );

// Use in WP_Query
$query = new WP_Query( [
    'paged'          => Request::get_current_page(),
    'posts_per_page' => 10
] );
```

Common Use Cases
----------------

[](#common-use-cases)

### Conditional Asset Loading

[](#conditional-asset-loading)

```
function enqueue_conditional_assets() {
    if ( Request::is( 'admin' ) ) {
        wp_enqueue_script( 'admin-script', 'admin.js' );
    }

    if ( Request::is_editor() ) {
        wp_enqueue_script( 'editor-blocks', 'blocks.js' );
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_conditional_assets' );
add_action( 'admin_enqueue_scripts', 'enqueue_conditional_assets' );
```

### AJAX Handler with Safety

[](#ajax-handler-with-safety)

```
function handle_search_ajax() {
    if ( ! Request::is( 'ajax' ) ) {
        wp_die( 'Invalid request' );
    }

    $search_term = Request::get_var( 'search', '', 'post' );
    $page        = Request::get_var( 'page', 1, 'post' );

    if ( empty( $search_term ) ) {
        wp_send_json_error( 'Search term required' );
    }

    // Process search...
    wp_send_json_success( $results );
}
add_action( 'wp_ajax_search', 'handle_search_ajax' );
add_action( 'wp_ajax_nopriv_search', 'handle_search_ajax' );
```

### REST API Endpoint with JSON Body

[](#rest-api-endpoint-with-json-body)

```
function handle_api_request( WP_REST_Request $request ) {
    // Get JSON payload
    $data = Request::get_json_body();

    if ( ! $data ) {
        return new WP_Error( 'invalid_json', 'Invalid JSON body', [ 'status' => 400 ] );
    }

    // Get client IP for logging
    $client_ip = Request::get_client_ip();

    // Check for API key
    $api_key = Request::get_header( 'x-api-key' );
    if ( ! $api_key || ! validate_api_key( $api_key ) ) {
        return new WP_Error( 'unauthorized', 'Invalid API key', [ 'status' => 401 ] );
    }

    // Process request...
    return new WP_REST_Response( $result, 200 );
}
```

### IP-Based Rate Limiting

[](#ip-based-rate-limiting)

```
function check_rate_limit() {
    $client_ip = Request::get_client_ip();
    $cache_key = 'rate_limit_' . md5( $client_ip );

    $requests = get_transient( $cache_key ) ?: 0;

    if ( $requests >= 100 ) {
        wp_die( 'Rate limit exceeded', 'Too Many Requests', [ 'response' => 429 ] );
    }

    set_transient( $cache_key, $requests + 1, HOUR_IN_SECONDS );
}
```

### Secure Form Processing

[](#secure-form-processing)

```
function process_contact_form() {
    // Only process POST requests
    if ( ! Request::is_method( 'POST' ) || ! Request::has_var( 'submit', 'post' ) ) {
        return;
    }

    // Require SSL in production
    if ( ! Request::is_ssl() && ! defined( 'WP_DEBUG' ) ) {
        wp_die( 'Secure connection required' );
    }

    // Get sanitized form data
    $name    = Request::get_var( 'name', '', 'post' );
    $email   = Request::get_var( 'email', '', 'post' );
    $message = Request::get_var( 'message', '', 'post' );

    // Validate and process...
}
```

### Context-Aware Caching

[](#context-aware-caching)

```
function get_cache_key( string $base_key ): string {
    $parts = [ $base_key ];

    if ( Request::is_ssl() ) {
        $parts[] = 'ssl';
    }

    if ( Request::is( 'admin' ) ) {
        $parts[] = 'admin';
    } elseif ( Request::is( 'rest' ) ) {
        $parts[] = 'rest';
    }

    return implode( '_', $parts );
}
```

API Reference
-------------

[](#api-reference)

### Request Type Detection

[](#request-type-detection-1)

MethodDescription`is($type)`Check request type(s): admin, ajax, cron, frontend, json, rest, cli, editor, api`is_frontend()`True if not admin/ajax/cron/rest/api/cli`is_cli()`Command line interface request`is_editor()`Block/Gutenberg editor context`is_api()`REST API or has API headers`is_ssl()`Secure HTTPS connection (CloudFlare-aware)`is_cloudflare()`Request is behind CloudFlare### HTTP Methods

[](#http-methods)

MethodDescription`get_method()`Get HTTP method (GET, POST, PUT, etc.)`is_method($method)`Check if method matches (string or array)### Headers

[](#headers)

MethodDescription`get_header($header, $default)`Get header value (case-insensitive)`has_header($header)`Check if header exists`get_client_ip()`Get real client IP (proxy/CloudFlare-aware)### Request Variables

[](#request-variables)

MethodDescription`get_var($key, $default, $method)`Get sanitized variable`has_var($key, $method)`Check if variable exists`get_json_body($associative)`Get JSON request body`get_request_vars($refresh)`All sanitized $\_REQUEST variables`get_post_vars($refresh)`All sanitized $\_POST variables`get_get_vars($refresh)`All sanitized $\_GET variables`get_current_page($param)`Get current page number for pagination### REST API

[](#rest-api)

MethodDescription`get_rest_route()`Get current REST route or nullSecurity
--------

[](#security)

All request variables are automatically sanitized using WordPress functions:

- Keys sanitized with `sanitize_key()`
- Values sanitized with `sanitize_text_field()`
- Arrays recursively sanitized
- JSON body decoded safely with error handling
- No raw `$_GET`/`$_POST`/`$_REQUEST` access needed

Performance
-----------

[](#performance)

- **Cached sanitization** - Request variables are sanitized once and cached
- **WordPress native** - Uses core WP functions when available (`wp_doing_ajax()`, `is_ssl()`, etc.)
- **Efficient detection** - Request type detection uses fast native checks

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

[](#requirements-1)

- PHP 7.4+
- WordPress 5.0+

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This project is licensed under the GPL-2.0-or-later License.

Support
-------

[](#support)

- [Documentation](https://github.com/arraypress/wp-request-utils)
- [Issue Tracker](https://github.com/arraypress/wp-request-utils/issues)

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance54

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/cd6eb8aff0903d87eb674d1ba3c5f3653899c0d7661504eb0deb7798ed86b643?d=identicon)[arraypress](/maintainers/arraypress)

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/arraypress-wp-request-utils/health.svg)

```
[![Health](https://phpackages.com/badges/arraypress-wp-request-utils/health.svg)](https://phpackages.com/packages/arraypress-wp-request-utils)
```

###  Alternatives

[friendsofsymfony/rest-bundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony

2.8k73.3M319](/packages/friendsofsymfony-rest-bundle)[php-http/discovery

Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations

1.3k309.5M1.2k](/packages/php-http-discovery)[pusher/pusher-php-server

Library for interacting with the Pusher REST API

1.5k94.8M293](/packages/pusher-pusher-php-server)[react/http

Event-driven, streaming HTTP client and server implementation for ReactPHP

78026.4M414](/packages/react-http)[php-http/curl-client

PSR-18 and HTTPlug Async client with cURL

48347.0M384](/packages/php-http-curl-client)[smi2/phpclickhouse

PHP ClickHouse Client

84310.1M71](/packages/smi2-phpclickhouse)

PHPackages © 2026

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