edit-icon download-icon

PHP handler

Last Updated: Sep 14, 2018

To use PHP in Function Compute, you must first define a PHP function as a handler. This topic describes the PHP handlers that you may use and their definitions.

Overview

To make it easy to handle HTTP requests, Function Compute supports using HTTP triggers to call PHP functions. The HTTP triggered function is known as a handler with an HTTP trigger. Currently, the PHP runtime environment supports two types of handlers:

Common handlers

A basic handler is defined as follows:

  1. <? php
  2. function handler($event, $context) {
  3. return "hello world";
  4. }

Function name

handler must be consistent with the “handler” field you have specified when you create this function. For example, if you set “handler” to index.handler, Function Compute loads the handler function defined in file index.php.

Parameter $event

Parameter $event is an input parameter of the function. You must pass in this parameter when you call this function. The data type of this parameter is string. The PHP function directly uses the $event parameter that you have specified, without any preprocessing. You can parse the $event parameter in the function based on your needs. For example, if the input data is a JSON string, you can convert this parameter to an array. See the following example.

  • The input parameter $event is as follows:

    1. {
    2. "key": "value"
    3. }
  • Parse $event to return value using the following code:

    1. <? php
    2. function handler($event, $context) {
    3. $eventObj = json_decode($event, $assoc = true);
    4. return $eventObj['key'];
    5. }

Parameter $context

The $context parameter contains the runtime information of the function, such as the request ID (requestId) and the temporary security credentials (securityToken). The data type of $context is array, and $context is defined as follows:

  1. [
  2. 'requestId' => 'b1c5100f-819d-c421-3a5e-7782a27d8a33',
  3. 'credentials' => [
  4. 'accessKeyId' => 'STS.access_key_id',
  5. 'accessKeySecret' => 'access_key_secret',
  6. 'securityToken' => 'security_token',
  7. ],
  8. 'function' => [
  9. 'name' => 'my-func',
  10. 'handler' => 'index.handler',
  11. 'memory' => 128,
  12. 'timeout' => 10,
  13. ],
  14. 'service' =>[
  15. 'name' => 'my-service',
  16. 'logProject' => 'my-log-project',
  17. 'logStore' => 'my-log-store',
  18. ],
  19. 'region' => 'cn-shanghai',
  20. 'accountId' => '123456'
  21. ]

Parameter $context contains the following fields:

Field Data type Description
requestId String The ID of the current request. This field is usually used to trace problems and count requests.
function Array Contains the basic information about the function, such as the function name, handler, function memory, and timeout period.
credentials Array Contains the temporary security credentials (securityToken) that Function Compute obtains when assuming your service role. These credentials are updated every 15 minutes. You can also use temporary security credentials to access other Alibaba Cloud services, such as OSS. This prevents you from hard coding the AccessKey credentials in the code.
service Array Contains the details of the service where the function is used, such as the service name, the log project, and logStore in the related Log Service.
region String Represents the region to which the function applies, such as cn-shanghai. For more information, see Regions and zones.
accountId String Represents the ID of the Alibaba Cloud account that calls the function. For more information, see Obtain Alibaba Cloud account ID.

Example of a common handler

Temporary security credentials are used to verify the user identity and permissions. You must specify securityToken when you access other Alibaba Cloud services, for example, OSS. The following example uses temporary security credentials to upload a TXT file to an OSS bucket.

  1. <? php
  2. use OSS\OssClient;
  3. function handler($event, $context) {
  4. $accessKeyId = $context["credentials"]["accessKeyId"];
  5. $accessKeySecret = $context["credentials"]["accessKeySecret"];
  6. $securityToken = $context["credentials"]["securityToken"];
  7. $endpoint = "oss-cn-shenzhen.aliyuncs.com";
  8. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
  9. $bucket = "my-bucket";
  10. $object = "php.txt";
  11. $content = "Hello fc!" ;
  12. try {
  13. $ossClient->putObject($bucket, $object, $content);
  14. } catch (OssException $e) {
  15. print($e->getMessage());
  16. }
  17. return 'sucess';
  18. };

Handlers with an HTTP trigger

A basic handler with an HTTP trigger is defined as follows:

  1. <? php
  2. use RingCentral\Psr7\Response;
  3. function handler($request, $context): Response{
  4. /*
  5. $body = $request->getBody()->getContents();
  6. $queries = $request->getQueryParams();
  7. $method = $request->getMethod();
  8. $headers = $request->getHeaders();
  9. $path = $request->getAttribute("path");
  10. $requestURI = $request->getAttribute("requestURI");
  11. $clientIP = $request->getAttribute("clientIP");
  12. */
  13. return new Response(
  14. 200,
  15. array(
  16. "custom_header1" => "v1",
  17. "custom_header2" => ["v2", "v3"],
  18. ),
  19. "hello world"
  20. );
  21. }

Parameter $context

The $context parameter is the same as the $context parameter defined in common handlers.

Parameter $request

The $request parameter follows the RSR standards on HTTP message interfaces. For more information, see PSR-7-http-message. For more information about coding standards, see PSR Http Message.

The following example demonstrates the methods of $request:

  1. <? php
  2. $queries = $request->getQueryParams();
  3. $method = $request->getMethod();
  4. $headers = $request->getHeaders();
  5. $path = $request->getAttribute("path");
  6. $requestURI = $request->getAttribute("requestURI");
  7. $clientIP = $request->getAttribute("clientIP");
  8. $body = $request->getBody()->getContents();
Field Data type Description
$headers Array Contains the key-value pairs from the HTTP client. The key-value pairs are array field and follows the PSR-7 standard.
$path String Represents the path of the HTTP URL.
$queries Array Contains the key-value pairs in the query string of the HTTP URL. The value field can be a String or Array.
$method String Represents the HTTP method.
$clientIP String Represents the IP address of the HTTP client.
$requestURI String Represents the URL that excludes the hostname.
$body String Represents the body of the HTTP request.

Note:
Function Compute provides system fields by default, which cannot be used as custom fields. The default system fields are accept-encoding, connection, keep-alive, proxy-authorization, te, trailer, transfer-encoding, and fields starting with x-fc-.

Parameter $response

$response follows the RSR standards on HTTP message interfaces. The constructor of Response is as follows:

  1. <? php
  2. /**
  3. * @param int $status Status code for the response, if any.
  4. * @param array $headers Headers for the response, if any.
  5. * @param mixed $body Stream body.
  6. */
  7. public function __construct(
  8. $status = 200,
  9. array $headers = array(),
  10. $body = null,
  11. )
  12. {
  13. //...
  14. }

The body field can be a String or Stream. If the body field is a Stream, the body must implement the StreamInterface interface defined in PSR-7-http-message.

Example of a handler with an HTTP trigger

The following example demonstrates how to use $request and Response of a handler with an HTTP trigger.

  1. use RingCentral\Psr7\Response;
  2. function php_http_handler($request, $context): Response{
  3. $body = $request->getBody()->getContents();
  4. $queries = $request->getQueryParams();
  5. $method = $request->getMethod();
  6. $headers = $request->getHeaders();
  7. $path = $request->getAttribute("path");
  8. $requestURI = $request->getAttribute("requestURI");
  9. $clientIP = $request->getAttribute("clientIP");
  10. $params = array(
  11. 'method' => $method,
  12. 'clientIP' => $clientIP,
  13. 'requestURI' => $requestURI,
  14. 'path' => $path,
  15. 'queriesMap' => $queries,
  16. 'headersMap' => $headers,
  17. 'body' => $body,
  18. );
  19. $respHeaders = array('Content-Type' => 'application/json');
  20. $respBody = json_encode($params);
  21. return new Response(200, $respHeaders, $respBody);
  22. }

Limits on handlers with an HTTP trigger

Limits on Request

If the following limits are exceeded, the system throws HTTP status code 400 and error code InvalidArgument.

Component Limit HTTP status code Error code
headers The size of all key-value pairs in the headers cannot exceed 4 KB. 400 InvalidArgument
path The size of the path component and all query parameters cannot exceed 4 KB.
body The size of the request body cannot exceed 6 MB.

Response limits

If the following limits are exceeded, the system throws HTTP status code 502 and BadResponse error code.

Component Limit HTTP status code Error code
headers The size of all key-value pairs in the headers cannot exceed 4 KB. 502 BadResponse
body The size of the request body cannot exceed 6 MB.

Reference

For more information, see PHP runtime environment.

Thank you! We've received your feedback.