You can use PHP handlers to respond to events and execute your business logic. This topic describes the concepts, structure, and examples of PHP handlers.
What is a handler
A handler for an FC function is the method in your function code that processes requests. When your FC function is invoked, Function Compute runs the handler you specified. You can configure the handler in the Function Compute console by setting the Handler parameter.
For a PHP function in FC, the handler must be in the filename.methodname format. For example, if your file is named main.php and the method is named handler, the handler is main.handler.
For more information about defining FC functions, see Create an event-triggered function.
Configurations of handlers must conform to the configuration specifications of Function Compute. The configuration specifications vary based on the handler type.
Handler signature
The following code defines a simple handler signature.
<?php
function handler($event, $context) {
return 'hello world';
}The following describes the parameters:
handler: The method name. This corresponds to the Handler configured in the Function Compute console. For example, if the Handler for an FC function is set toindex.handler, Function Compute loads thehandlerfunction defined inindex.phpand starts execution from thehandlerfunction.$event: The parameter that you pass when you call the function. Its data type is string. A PHP function directly uses the specifiedeventparameter without any preprocessing. You can parse theeventin your function as needed. For example, if the input data is a JSON string, you can convert it to an Array.$context: Contains runtime information about the function, such as the request ID and temporary credentials. You can use this information in your code.
If you want to use HTTP triggers or custom domain names to access functions, obtain request struct before you define HTTP responses. For more information, see Use an HTTP trigger to invoke a function.
Example 1: Parse JSON-formatted parameters
Sample Code
Function Compute passes JSON-formatted parameters as a raw string, which you must parse in your code. The following sample code shows how to parse a JSON-formatted event.
<?php
function handler($event, $context) {
$v = json_decode($event, true);
var_dump($v['key1']);
var_dump($v['key2']);
var_dump($v['key3']);
return $v;
}Prerequisites
You have created a function that uses the PHP runtime. For more information, see Create an event-triggered function.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Code tab, enter the sample code in the code editor, and then click Deploy.
NoteIn the sample code, the handler is the
handlermethod inindex.php. If the handler of your function is configured differently, update the file and method names to match your configuration.On the Code tab, click the
icon to the right of Test Function, select Configure Test Parameters from the drop-down list, enter the following sample test parameters, and click OK.{ "key1": "value1", "key2": "value2", "key3": { "v1": true, "v2": "bye", "v3": 1234 } }Click Test Function.
After the function executes, it returns the JSON-formatted content, and the values of
key1,key2, andkey3are printed to the logs.
Example 2: Securely access OSS resources
Sample Code
You can use temporary credentials from Function Compute to access Object Storage Service (OSS). The following code shows an example.
<?php
use OSS\OssClient;
use OSS\Core\OssException;
function handler($event, $context) {
/*
An AccessKey pair of an Alibaba Cloud account grants full permissions for all API operations. We recommend that you use a RAM user for API calls and routine maintenance.
To mitigate the risk of AccessKey leaks, we recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code.
This example shows how to obtain credentials from the context.
*/
$creds = $context["credentials"];
$accessKeyId = $creds["accessKeyId"];
$accessKeySecret = $creds["accessKeySecret"];
$securityToken = $creds["securityToken"];
$endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";
$bucket= "randombucket";
$object = "exampledir/index.php";
$filePath = "/code/index.php";
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
$ossClient->uploadFile($bucket, $object, $filePath);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return $e->getMessage();
}
return 'hello world';
}The sample code is explained as follows:
$creds = $context["credentials"]: Obtains temporary credentials from the$contextparameter. This practice avoids hard-coding sensitive information, such as credentials, in your code.The preceding code uploads the
/code/index.phpfile to the exampledir directory in therandombucketbucket in OSS.NoteReplace
endpoint,bucket,object, andfilePathwith your actual resource values.
Prerequisites
You have configured a role for the function that has permissions to access Object Storage Service (OSS). For more information, see Use a role to grant Function Compute permissions to access other cloud services.
You have created a function that uses the PHP runtime. For more information, see Create an event-triggered function.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Code tab, enter the sample code in the code editor, and then click Deploy.
NoteIn the sample code, the handler is the
handlermethod inindex.php. If the handler of your function is configured differently, update the file and method names to match your configuration.Click Test Function.
After the function executes, it returns
hello world.
Example 3: Call external commands
Your PHP program can also fork a process to call external commands.
If your PHP function needs to use tools written in other languages, such as shell scripts or executables compiled in C++ or Go, you can package the tools with your function code and upload them together. You can then call these tools by running external commands from your function. Common methods for calling external commands include exec, system, and shell_exec.
The following sample code runs the Linux command ls -halt to list the detailed contents of the /code directory.
<?php
function handler($event, $context) {
return shell_exec("ls -halt /code");
} Example 4: Invoke a function using an HTTP trigger
Sample code
<?php
function handler($event, $context) {
$logger = $GLOBALS['fcLogger'];
$logger->info('hello world');
$logger->info('receive event: ' . $event);
try {
$evt = json_decode($event, true);
if (is_null($evt['body'])) {
return "The request did not come from an HTTP Trigger, event: " . $event;
}
$body = $evt['body'];
if ($evt['isBase64Encoded']) {
$body = base64_decode($evt['body']);
}
return array(
"statusCode" => 200,
'headers' => array("Content-Type" => "text/plain"),
'isBase64Encoded' => false,
"body" => $body
);
} catch (Exception $e) {
$logger->error("Caught exception: " . $e->getMessage());
return "The request did not come from an HTTP Trigger, event: " . $event;
}
}Prerequisites
You have created a function that uses the PHP runtime and an HTTP trigger. For more information, see Create an event-triggered function and Configure an HTTP trigger.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Trigger tab to find the public endpoint of the HTTP trigger.
Run the following cURL command to invoke the function.
curl -i "https://http-trigger-demo.cn-shanghai.fcapp.run" -d 'Hello FC!'ImportantIf the Authentication Method for the HTTP trigger is set to No Authentication, you can directly use Postman or cURL to call the function. For more information, see Steps.
If the Authentication Method of the HTTP trigger is Signature Authentication, JWT Authentication, or Bearer Authentication, you must use the corresponding authentication method to invoke the function. For more information, see Authentication and authorization.
Error analysis
This sample code supports invocations using an HTTP trigger or a custom domain name. If you test the function from the console with an event that does not match the HTTP trigger request format, an error occurs.
For example, if you invoke the function in the console, set the request parameter to "Hello, FC!", and click Test Function, the function returns the following response:
The request did not come from an HTTP Trigger, event: Hello FC!