khaiphan9x / fastcgi
PHP的FastCGI客户端实现
This package is auto-updated.
Last update: 2024-09-29 05:48:47 UTC
README
使您能够从FastCGI服务器请求脚本执行。FastCGI是一种常用于Web服务器请求FastCGI守护进程(如php-fpm)执行脚本的协议。
使用场景
- 从命令行执行任何可以从APC中受益的脚本。
- 从长时间运行的守护进程中运行具有独立执行上下文的代码
- 更多
安装
$ composer require khaiphan9x/fastcgi
使用
客户端支持tcp
$client = new \EBernhardson\FastCGI\Client('localhost', '8989');
或Unix套接字
$client = new \EBernhardson\FastCGI\Client('/var/run/php7-fpm.sock');
使用环境参数数组和一个包含请求内容的字符串进行FastCGI请求。当连接到php-fpm时,$environment
将在$_SERVER
中可用。以下环境是php-fpm执行脚本所需的最小环境。
$environment = [
'REQUEST_METHOD' => 'GET',
'SCRIPT_FILENAME' => '/full/path/to/script.php',
];
$client->request($environment, '');
发出请求后,必须获取响应。在请求完成之前,response
方法将阻塞。
$response = $client->response();
response
方法返回一个包含四个键的数组:statusCode
、headers
、body
和stderr
。
目前,您必须在再次调用request
之前调用response
。不这样做会导致未定义的行为。FastCGI协议支持多路复用,因此这可能在将来改变。
异常
与FastCGI守护进程的任何通信失败都将导致异常。FastCGI的CommunicationException
扩展自SPL的RuntimeException
。
try {
$client->request($environment, $stdin);
$response = $client->response();
} catch (\EBernhardson\FastCGI\CommunicationException $failure) {
// handle failure
}
通过FastCGI传递的常见环境变量
GATEWAY_INTERFACE
描述要使用的fastcgi协议版本的变量。目前,此客户端支持版本1.0。
'GATEWAY_INTERFACE' => 'FastCGI/1.0'
REQUEST_METHOD
包含HTTP请求方法的必需环境变量。
可能值包括GET
、HEAD
、POST
、PUT
和DELETE
。
'REQUEST_METHOD' => 'GET'
SCRIPT_FILENAME
包含正在执行脚本的绝对路径的必需环境变量。此路径必须可由FastCGI服务器访问。
'SCRIPT_FILENAME' => '/home/zomg/deploy/current/web/app.php'
QUERY_STRING
可选地包含查询字符串。您可以使用http_build_query
函数以期望的格式格式化键/值对的数组。
'QUERY_STRING' => http_build_query(['key' => 'value'])
SERVER_SOFTWARE
用于发出FastCGI请求的软件。
'SERVER_SOFTWARE' => 'awesome-application/1.0'
SERVER_NAME
发出此请求的服务器名称
'SERVER_NAME' => php_uname('n')
CONTENT_TYPE
当随请求发送内容时,此指定内容的MIME类型。
'CONTENT_TYPE' => 'application/x-www-form-urlencoded'
CONTENT_LENGTH
当随请求发送内容时,此指定内容的长度。
'CONTENT_LENGTH' => strlen($content)
示例
传递HTTP头
Http头以HTTP_为前缀发送。
$client->request(
[
'REQUEST_METHOD' => 'GET',
'SCRIPT_FILENAME' => '/full/path/to/test.php',
'HTTP_ACCEPT' => 'application/json',
],
''
);
POST请求
$content = 'key=value';
$client->request(
[
'REQUEST_METHOD' => 'POST',
'SCRIPT_FILENAME' => '/full/path/to/test.php',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => strlen($content)
],
$content
);
php-fpm对无效的SCRIPT_FILENAME的响应
array(4) {
["statusCode"]=>
int(404)
["statusBody"]=>
string(2) "OK"
["headers"]=>
array(3) {
["status"]=>
string(14) "404 Not Found"
["x-powered-by"]=>
string(22) "PHP/5.4.9-4~precise+1"
["content-type"]=>
string(9) "text/html"
}
["body"]=>
string(15) "File not found."
["stderr"]=>
string(23) "Primary script unknown
"
}
php-fpm对成功执行的响应
array(4) {
["statusCode"]=>
int(200)
["statusBody"]=>
string(2) "OK"
["headers"]=>
array(3) {
["x-powered-by"]=>
string(22) "PHP/5.4.9-4~precise+1"
["content-type"]=>
string(9) "text/html"
["status"]=>
string(6) "200 OK"
}
["body"]=>
string(11) "Hello World"
["stderr"]=>
string(0) ""
}