PHPackages                             tg111/php-request - 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. tg111/php-request

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

tg111/php-request
=================

A Python php-request HTTP client library for PHP

v1.0.2(6mo ago)191MITPHPPHP &gt;=7.1

Since Jun 25Pushed 6mo agoCompare

[ Source](https://github.com/tg111/php-request)[ Packagist](https://packagist.org/packages/tg111/php-request)[ Docs](https://github.com/tg111/php-request)[ RSS](/packages/tg111-php-request/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (4)Versions (4)Used By (0)

PHP Request
===========

[](#php-request)

[![Latest Version](https://camo.githubusercontent.com/7fb6da88e44891f9a7644b7f45eab852df25c6cd5e850918db0e2830b123e813/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74673131312f7068702d726571756573742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tg111/php-request)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Total Downloads](https://camo.githubusercontent.com/f06f53276079eb0b85e8fe965702ccf7cb49d8cd4c06c86df2836e5600b7cf06/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f74673131312f7068702d726571756573742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tg111/php-request)

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
-------------

[](#documentation)

- [English Documentation](README.md) (Current)
- [中文文档](docs/README-zh.md)

Features
--------

[](#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
------------

[](#installation)

Install via Composer:

```
composer require tg111/php-request
```

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

[](#requirements)

- PHP 7.1 or higher
- cURL extension
- JSON extension

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#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

[](#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
--------------

[](#advanced-usage)

### Custom Headers and Authentication

[](#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

[](#cookies)

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

### Session Management

[](#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

[](#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

[](#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
---------------

[](#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
---------------------

[](#configuration-options)

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

OptionTypeDescription`headers`arrayCustom headers to send`cookies`arrayCookies to include`timeout`intRequest timeout in seconds`connect_timeout`intConnection timeout in seconds`proxy`stringProxy URL ()`proxy_auth`stringProxy authentication (user:pass)`verify`boolVerify SSL certificates`cert`stringPath to SSL certificate file`http_version`stringHTTP version ('1.0', '1.1', '2.0')Examples
--------

[](#examples)

### File Upload

[](#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

[](#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
-------

[](#testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test-coverage
```

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

[](#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
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Comparison with Python requests
-------------------------------

[](#comparison-with-python-requests)

Python requestsPHP 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
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for version history.

Support
-------

[](#support)

- 📚 [Documentation](docs/)
- 🐛 [Issue Tracker](https://github.com/tg111/php-request/issues)

---

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance67

Regular maintenance activity

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity34

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.

###  Release Activity

Cadence

Every ~91 days

Total

3

Last Release

191d ago

PHP version history (2 changes)v1.0.0PHP &gt;=7.4

v1.0.1PHP &gt;=7.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/58ac236ee454684cbf6a5dc8a1a80f7ab721110af4315614d3c040b9181d4b62?d=identicon)[tg111](/maintainers/tg111)

---

Top Contributors

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

---

Tags

httpapiclientrestcurlrequestspython-like

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tg111-php-request/health.svg)

```
[![Health](https://phpackages.com/badges/tg111-php-request/health.svg)](https://phpackages.com/packages/tg111-php-request)
```

###  Alternatives

[nategood/httpful

A Readable, Chainable, REST friendly, PHP HTTP Client

1.8k17.7M275](/packages/nategood-httpful)[ismaeltoe/osms

PHP library wrapper of the Orange SMS API.

4640.8k](/packages/ismaeltoe-osms)[voku/httpful

A Readable, Chainable, REST friendly, PHP HTTP Client

16185.7k1](/packages/voku-httpful)[e-moe/guzzle6-bundle

Integrates Guzzle 6 into your Symfony application

12262.2k1](/packages/e-moe-guzzle6-bundle)[openapi/openapi-sdk

Minimal and agnostic PHP SDK for Openapi® (https://openapi.com)

171.5k1](/packages/openapi-openapi-sdk)

PHPackages © 2026

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