在函数计算服务使用PHP编程,需要定义一个函数作为入口函数。本文介绍了PHP HTTP函数的结构和特点。
HTTP函数定义
以下代码示例定义了一个基本的PHP HTTP入口函数。
<?php
use RingCentral\Psr7\Response;
function handler($request, $context): Response{
/*
$body = $request->getBody()->getContents();
$queries = $request->getQueryParams();
$method = $request->getMethod();
$headers = $request->getHeaders();
$path = $request->getAttribute("path");
$requestURI = $request->getAttribute("requestURI");
$clientIP = $request->getAttribute("clientIP");
*/
return new Response(
200,
array(
"custom_header1" => "v1",
"custom_header2" => ["v2", "v3"],
"Set-Cookie" => urlencode("test php") . '=' . urlencode('test;more')
),
"hello world"
);
}
header
的方法,例如header
、setcookie
等。
HTTP函数$context参数
$context参数与事件函数中的$context参数相同,详情请参见事件函数$context参数。
HTTP函数$request参数
$request参数遵循PSR(HTTP message interfaces)标准。更多详情请参见PSR-7-http-message。具体的代码定义遵循PSR Http Message。
$request参数携带的可用信息代码示例如下:
<?php
$queries = $request->getQueryParams();
$method = $request->getMethod();
$headers = $request->getHeaders();
$path = $request->getAttribute("path");
$requestURI = $request->getAttribute("requestURI");
$clientIP = $request->getAttribute("clientIP");
$body = $request->getBody()->getContents();
参数 | 类型 | 描述 |
---|---|---|
$headers | Array | 存放来自HTTP客户端的键值对,键值对中的值为数组类型,遵循PSR-7标准。 |
$path | String | HTTP URL中的路径。 |
$queries | Array | 存放来自HTTP URL中的查询部分的键值对,键值对中的值可以是字符串或数组。 |
$method | String | HTTP方法。 |
$clientIP | String | HTTP客户端的IP地址。 |
$requestURI | String | 请求中除host以外的URL。 |
$body | String | HTTP请求中的请求体数据。 |
HTTP函数$response参数
$response遵循PSR(HTTP message interfaces)标准。以下代码为Response构造示例。
<?php
/**
* @param int $status Status code for the response, if any.
* @param array $headers Headers for the response, if any.
* @param mixed $body Stream body.
*/
public function __construct(
$status = 200,
array $headers = array(),
$body = null,
)
{
//...
}
PHP HTTP函数示例
下文代码示例演示了如何使用HTTP函数中的$request
和$Response
。
use RingCentral\Psr7\Response;
function php_http_handler($request, $context): Response{
$body = $request->getBody()->getContents();
$queries = $request->getQueryParams();
$method = $request->getMethod();
$headers = $request->getHeaders();
$path = $request->getAttribute("path");
$requestURI = $request->getAttribute("requestURI");
$clientIP = $request->getAttribute("clientIP");
$params = array(
'method' => $method,
'clientIP' => $clientIP,
'requestURI' => $requestURI,
'path' => $path,
'queriesMap' => $queries,
'headersMap' => $headers,
'body' => $body,
);
$respHeaders = array('Content-Type' => 'application/json');
$respBody = json_encode($params);
return new Response(200, $respHeaders, $respBody);
}
限制说明
- 请求限制
如果超过以下限制,会返回
400
状态码和InvalidArgument
错误码。字段 限制说明 HTTP状态码 错误码 headers 请求头中的所有键和值的总大小不能超过4 KB。 400 InvalidArgument path 请求路径以及所有查询参数的总大小不能超过4 KB。 body HTTP body的总大小不能超过6 MB。 - 响应限制
如果超过以下限制,会返回
502
状态码和BadResponse
错误码。字段 限制说明 HTTP状态码 错误码 headers 响应头中的所有键和值对的大小不能超过4 KB。 502 BadResponse body HTTP body的大小不能超过6 MB。
更多信息
PHP运行环境的详细信息,请参见PHP运行环境。