tg111/php-request

A Python php-request HTTP client library for PHP

v1.0.0 2025-06-25 09:44 UTC

This package is auto-updated.

Last update: 2025-06-25 12:04:15 UTC


README

Latest Version Software License Total Downloads

A Python requests-like HTTP client library for PHP. This library provides an elegant and simple HTTP client with an interface similar to Python's popular requests library.

Documentation

Features

  • Simple and elegant API - Inspired by Python's requests library
  • Multiple HTTP methods - GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
  • Session support - Persistent cookies, headers, and configuration
  • Comprehensive data handling - JSON, form data, multipart uploads
  • Cookie management - Automatic cookie handling and custom cookie support
  • Custom headers - Set custom headers for requests
  • Authentication - Basic, Bearer token, and custom authentication
  • SSL support - Configure SSL verification and certificates
  • Proxy support - HTTP and HTTPS proxy configuration
  • Timeout control - Request and connection timeout settings
  • Error handling - Comprehensive exception handling
  • No dependencies - Only requires cURL extension

Installation

Install via Composer:

composer require tg111/php-request

Requirements

  • PHP 7.4 or higher
  • cURL extension
  • JSON extension

Quick Start

Basic Usage

use PhpRequest\PhpRequest;

// Simple GET request
$response = PhpRequest::get('https://httpbin.org/get');
echo $response->text();

// GET with parameters
$response = PhpRequest::get('https://httpbin.org/get', [
    'key1' => 'value1',
    'key2' => 'value2'
]);

// POST with data
$response = PhpRequest::post('https://httpbin.org/post', [
    'username' => 'user',
    'password' => 'pass'
]);

// JSON POST
$response = PhpRequest::post('https://httpbin.org/post', [
    'name' => 'John Doe',
    'email' => 'john@example.com'
], [
    'headers' => ['Content-Type' => 'application/json']
]);

Using Global Functions

// Alternative syntax using global functions
$response = requests_get('https://httpbin.org/get');
$response = requests_post('https://httpbin.org/post', ['key' => 'value']);

Advanced Usage

Custom Headers and Authentication

$response = PhpRequest::get('https://api.example.com/data', [], [
    'headers' => [
        'Authorization' => 'Bearer your-token-here',
        'Accept' => 'application/json',
        'User-Agent' => 'MyApp/1.0'
    ],
    'timeout' => 30
]);

Cookies

$response = PhpRequest::get('https://httpbin.org/cookies', [], [
    'cookies' => [
        'session_id' => 'abc123456789',
        'user_preference' => 'dark_mode'
    ]
]);

Session Management

Sessions allow you to persist cookies, headers, and other configuration across multiple requests:

use PhpRequest\PhpRequest;

// Create a session
$session = PhpRequest::session()
    ->setHeaders([
        'Authorization' => 'Bearer token123',
        'Accept' => 'application/json'
    ])
    ->setCookies([
        'session_id' => 'session123'
    ])
    ->setTimeout(60);

// Use the session for multiple requests
$profile = $session->get('/user/profile');
$settings = $session->get('/user/settings');
$updated = $session->post('/user/update', ['name' => 'New Name']);

Authentication

// Basic authentication
$session = PhpRequest::session()->auth('username', 'password');

// Bearer token
$session = PhpRequest::session()->bearerAuth('your-token');

// Custom header authentication
$session = PhpRequest::session()->setHeader('API-Key', 'your-api-key');

Error Handling

use PhpRequest\PhpRequest;
use RequestsLike\RequestException;

try {
    $response = PhpRequest::get('https://api.example.com/data');
    
    if ($response->ok()) {
        $data = $response->json();
        // Process successful response
    } else {
        // Handle HTTP error status codes
        echo "HTTP Error: " . $response->getStatusCode();
    }
    
} catch (RequestException $e) {
    // Handle network errors, timeouts, etc.
    echo "Request failed: " . $e->getMessage();
}

Response Object

The response object provides various methods to access response data:

$response = PhpRequest::get('https://httpbin.org/json');

// Get response content
$text = $response->text();           // Raw text content
$data = $response->json();           // Parse JSON response
$code = $response->getStatusCode();  // HTTP status code

// Check response status
$success = $response->ok();          // True for 2xx status codes
$isClientError = $response->isClientError(); // True for 4xx codes
$isServerError = $response->isServerError(); // True for 5xx codes

// Get headers and metadata
$headers = $response->getHeaders();
$contentType = $response->getContentType();
$totalTime = $response->getTotalTime();
$url = $response->getUrl();

// Save response to file
$response->save('/path/to/file.json');

Configuration Options

All request methods accept an options array with the following parameters:

Option Type Description
headers array Custom headers to send
cookies array Cookies to include
timeout int Request timeout in seconds
connect_timeout int Connection timeout in seconds
proxy string Proxy URL (http://proxy:port)
proxy_auth string Proxy authentication (user:pass)
verify bool Verify SSL certificates
cert string Path to SSL certificate file
http_version string HTTP version ('1.0', '1.1', '2.0')

Examples

File Upload

$response = PhpRequest::post('https://httpbin.org/post', [
    'file' => new CURLFile('/path/to/file.txt'),
    'description' => 'File upload test'
], [
    'headers' => ['Content-Type' => 'multipart/form-data']
]);

API Client Example

class ApiClient
{
    private $session;
    
    public function __construct($apiKey, $baseUrl = 'https://api.example.com')
    {
        $this->session = RequestsLike::session()
            ->setBaseUrl($baseUrl)
            ->setHeaders([
                'Authorization' => "Bearer $apiKey",
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ])
            ->setTimeout(30);
    }
    
    public function getUser($id)
    {
        $response = $this->session->get("/users/$id");
        return $response->ok() ? $response->json() : null;
    }
    
    public function createUser($userData)
    {
        $response = $this->session->post('/users', $userData);
        return $response->ok() ? $response->json() : null;
    }
}

// Usage
$client = new ApiClient('your-api-key');
$user = $client->getUser(123);
$newUser = $client->createUser(['name' => 'John', 'email' => 'john@example.com']);

Testing

Run the test suite:

composer test

Run tests with coverage:

composer test-coverage

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Comparison with Python requests

Python requests PHP PhpRequest
requests.get(url, params=data) PhpRequest::get($url, $params)
requests.post(url, data=data) PhpRequest::post($url, $data)
requests.Session() PhpRequest::session()
response.text $response->text()
response.json() $response->json()
response.status_code $response->getStatusCode()
response.ok $response->ok()
response.headers $response->getHeaders()

Changelog

See CHANGELOG.md for version history.

Support