n5s/http-cli
Composer 安装命令:
composer require --dev n5s/http-cli
包简介
Serverless HTTP client - make requests to PHP scripts on the command line
README 文档
README
Serverless HTTP client - make requests to PHP scripts on the CLI.
This library lets you make HTTP requests to PHP applications without running a web server. Instead of Apache or nginx, it executes your PHP scripts directly via the command line while emulating the full HTTP environment ($_GET, $_POST, $_SERVER, $_SESSION, headers, cookies, etc.).
Perfect for testing, CI pipelines, unreleased deployment or any scenario where spinning up a web server is overkill or not possible.
Installation
composer require n5s/http-cli
Usage
use n5s\HttpCli\Client; use n5s\HttpCli\RequestOptions; $client = new Client('/path/to/your/app'); // Simple GET request $response = $client->request('GET', 'https://example.com/api/users'); echo $response->getContent(); // POST with JSON $response = $client->request('POST', '/api/users', RequestOptions::create() ->json(['name' => 'John', 'email' => 'john@example.com']) ->build() ); // POST with form data $response = $client->request('POST', '/login', RequestOptions::create() ->formParams(['username' => 'admin', 'password' => 'secret']) ->build() );
How It Works
When you make a request, the library:
- Spawns a PHP CLI process targeting your script
- Injects a bootstrap that populates
$_GET,$_POST,$_SERVER,$_COOKIE, and$_SESSION - Provides polyfills for specific HTTP context functions:
header(),headers_sent(),http_response_code(), etc. - Captures the output and headers, returning a
Responseobject
Your PHP scripts run exactly as they would under a web server, but without one.
Framework Adapters
Use your favorite HTTP client library - just swap in our handler.
Guzzle
composer require guzzlehttp/guzzle
use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use n5s\HttpCli\Guzzle\CliHandler; use n5s\HttpCli\Client; $cliClient = new Client('/path/to/your/app'); $handler = new CliHandler($cliClient); $client = new Client([ 'handler' => HandlerStack::create($handler), ]); // Use Guzzle as normal $response = $client->get('/api/users'); $response = $client->post('/api/users', [ 'json' => ['name' => 'John'], ]);
Symfony HttpClient
composer require symfony/http-client
use n5s\HttpCli\Symfony\CliClient; use n5s\HttpCli\Client; $cliClient = new Client('/path/to/your/app'); $client = new CliClient($cliClient); // Use Symfony HttpClient as normal $response = $client->request('GET', '/api/users'); $data = $response->toArray();
WordPress Requests
composer require rmccue/requests
use WpOrg\Requests\Requests; use n5s\HttpCli\WordPress\Cli; use n5s\HttpCli\Client; $cliClient = new Client('/path/to/your/app'); Requests::set_transport([Cli::class]); Cli::setClient($cliClient); // Use WordPress Requests as normal $response = Requests::get('/api/users');
Request Options
Build requests with a fluent API:
use n5s\HttpCli\RequestOptions; $options = RequestOptions::create() // Body ->json(['key' => 'value']) // JSON payload ->formParams(['field' => 'value']) // Form data (application/x-www-form-urlencoded) ->body('raw content') // Raw body ->multipart([ // Multipart form data ['name' => 'file', 'contents' => 'data', 'filename' => 'test.txt'], ]) // Headers & Auth ->headers(['X-Custom' => 'value']) ->basicAuth('user', 'pass') ->bearerToken('token') ->cookies(['session' => 'abc123']) // Other ->query(['page' => 1, 'limit' => 10]) ->timeout(30.0) ->build(); $response = $client->request('POST', '/api/endpoint', $options);
Response
$response = $client->request('GET', '/api/users'); $response->getStatusCode(); // 200 $response->getHeaders(); // ['Content-Type: application/json', ...] $response->getContent(); // Response body as string $response->getSession(); // Session data array $response->getProcess(); // Symfony Process instance (for debugging)
Configuration
$client = new Client( documentRoot: '/path/to/your/app', // Required: your app's root directory file: 'index.php', // Entry point (default: index.php) globalsHandler: null, // GlobalsHandler to customize superglobals phpExecutable: null, // PHP binary path (auto-detected) );
Globals Handler
By default, the child PHP process receives a clean set of superglobals built from the HTTP request only. If your application depends on environment variables from the parent process (e.g. APP_ENV, DATABASE_URL), you can use the built-in InheritEnvGlobalsHandler:
use n5s\HttpCli\Client; use n5s\HttpCli\InheritEnvGlobalsHandler; $client = new Client( documentRoot: '/path/to/your/app', globalsHandler: new InheritEnvGlobalsHandler(), );
This merges the parent's $_SERVER and $_ENV into the child process. Request-specific variables take precedence over inherited ones.
You can also implement the GlobalsHandler interface to customize superglobals however you need:
use n5s\HttpCli\GlobalsHandler; final class MyGlobalsHandler implements GlobalsHandler { public function handle(array &$globals): void { $globals['_SERVER']['APP_ENV'] = 'testing'; $globals['_ENV']['CUSTOM_VAR'] = 'value'; } }
Adapter Options Support
Guzzle
| Option | Supported |
|---|---|
timeout |
✅ |
headers |
✅ |
query |
✅ |
body |
✅ |
json |
✅ |
form_params |
✅ |
multipart |
✅ |
auth |
✅ |
cookies |
✅ |
allow_redirects |
✅ |
http_errors |
✅ |
decode_content |
✅ |
version |
✅ |
sink |
✅ |
on_headers |
✅ (callback) |
on_stats |
✅ (callback) |
connect_timeout |
❌ ignored |
verify |
❌ ignored |
cert |
❌ ignored |
proxy |
❌ ignored |
ssl_key |
❌ |
progress |
❌ |
debug |
❌ |
Symfony HttpClient
| Option | Supported |
|---|---|
timeout |
✅ |
headers |
✅ |
query |
✅ |
body |
✅ |
json |
✅ |
auth_basic |
✅ |
auth_bearer |
✅ |
max_redirects |
✅ |
verify_peer |
❌ ignored |
verify_host |
❌ ignored |
cafile |
❌ ignored |
proxy |
❌ ignored |
http_version |
❌ |
on_progress |
❌ |
resolve |
❌ |
local_cert |
❌ |
local_pk |
❌ |
ciphers |
❌ |
WordPress Requests
| Option | Supported |
|---|---|
timeout |
✅ |
useragent |
✅ |
redirects |
✅ |
follow_redirects |
✅ |
auth |
✅ |
cookies |
✅ |
connect_timeout |
❌ ignored |
proxy |
❌ ignored |
verify |
❌ ignored |
verifyname |
❌ ignored |
filename |
❌ |
hooks |
❌ |
max_bytes |
❌ |
Limitations
Running PHP scripts via CLI instead of a web server comes with inherent limitations:
Not Supported
| Feature | Reason |
|---|---|
| Persistent connections | Each request spawns a new PHP process |
| Keep-alive | No connection reuse between requests |
| HTTP/2, HTTP/3 | CLI execution doesn't use HTTP protocol |
| WebSockets | Requires persistent connection |
| Server-Sent Events | Requires streaming connection |
| Real SSL/TLS | No actual HTTPS handshake (URLs are parsed, not connected) |
| Output streaming | Response is captured after script completes |
fastcgi_finish_request() |
FPM-specific function |
| APCu user cache | Not shared between CLI processes |
| OPcache benefits | Each process starts fresh |
| Static files | Only executes PHP - images, fonts, CSS, JS won't be served |
Behavioral Differences
- Performance: Process spawning overhead, but no DNS resolution, TCP/SSL handshake, or network latency
$_SERVERvalues: Some values likeSERVER_SOFTWAREwill differ from Apache/nginx- File uploads: Multipart parts are written to temp files and populated in
$_FILES - Session handling: Works but uses an in-memory handler, not file-based persistence
php://input: Custom stream wrapper provides the request body
License
MIT
n5s/http-cli 适用场景与选型建议
n5s/http-cli 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.74k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2026 年 01 月 02 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「symfony」 「http」 「cli」 「testing」 「Guzzle」 「command-line」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 n5s/http-cli 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 n5s/http-cli 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 n5s/http-cli 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
The bundle for easy using json-rpc api on your project
Bundle Symfony DaplosBundle
http客户端
Easily add Excepct-CT header to your project
Slim starter / Slim skeleton package to boost your development with Slim framework
统计信息
- 总下载量: 5.74k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-02