All Products
Search
Document Center

PHP runtime

Last Updated: Sep 28, 2018

Function Compute supports the PHP 7.2 runtime (runtime = php7.2). This topic describes the following features of PHP runtime environment:

Use logger

When the function uses $GLOBALS['fcLogger'] to output data, the data is collected and stored in the Logstore that you have specified when you create the service. Function Compute provides the logger module, which you can use through the $GLOBALS['fcLogger'] variable.

Log level

You can use the setLevel method to change log levels. The following log levels are listed in descending order of severity.

Log level Level Method Description
EMERGENCY 600 $logger->emergency Emergency logs
ALERT 550 $logger->alert Alert logs
CRITICAL 500 $logger->critical Serious warnings
ERROR 400 $logger->error Error messages
WARNING 300 $logger->warning Warnings
NOTICE 250 $logger->notice Notifications and general logs
INFO (Default) 200 $logger->info Detailed output information
DEBUG 100 $logger->debug Debug logs

For more information, see Function Compute logs.

logger example 1

  1. <? php
  2. function handler($event, $context) {
  3. $logger = $GLOBALS['fcLogger'];
  4. $logger->info("hello world");
  5. return 'hello world';
  6. }

The output logs are as follows:

  1. message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [INFO] hello world

logger example 2

  1. <?php
  2. use Monolog\Logger;
  3. function handler($evt, $ctx) {
  4. $logger = $GLOBALS['fcLogger'];
  5. $logger->setLevel(400);
  6. $logger->error("console error 1");
  7. $logger->info("console info 1");
  8. $logger->warning("console warn 1");
  9. $logger->debug("console debug 1");
  10. $logger->setLevel(Logger::WARNING);
  11. $logger->error("console error 2");
  12. $logger->info("console info 2");
  13. $logger->warn("console warn 2");
  14. $logger->debug("console debug 2");
  15. $logger->setLevel(200);
  16. }

The output logs are as follows:

  1. 2018-08-22T09:01:26Z c19b2706-9c4d-270b-52c8-5248ed5e2315 [ERROR]: console error 1
  2. 2018-08-22T09:01:26Z c19b2706-9c4d-270b-52c8-5248ed5e2315 [ERROR]: console error 2
  3. 2018-08-22T09:01:26Z c19b2706-9c4d-270b-52c8-5248ed5e2315 [WARNING]: console warn 2

Use built-in extensions

Function Compute provides the following built-in extensions:

  1. "Core", "date", "libxml", "openssl", "pcre", "zlib", "curl","filter", "hash", "readline", "Reflection",
  2. "SPL", "session","xml", "standard", "mysqlnd", "bcmath", "bz2", "calendar","ctype", "dom", "mbstring",
  3. "fileinfo", "ftp", "gettext", "gmp", "iconv","imagick", "json", "exif", "mysqli", "pcntl", "PDO",
  4. "pdo_mysql","Phar", "posix", "protobuf", "redis", "shmop", "SimpleXML", "soap","sockets", "sysvmsg",
  5. "sysvsem", "sysvshm", "tokenizer", "xmlreader","xmlrpc", "xmlwriter", "Zend OPcache", "xdebug",

Example of using a built-in extension

The following example uses imagick to process an image.

  1. <?php
  2. function imageProc($event, $context) {
  3. $image = new Imagick(__DIR__ . '/lena.jpg');
  4. $image->thumbnailImage(100, 0);
  5. $image->writeImages(__DIR__ . "/thumb.jpg", true);
  6. return strval($image->getImageWidth()) . "," . strval($image->getImageHeight());
  7. }

Use custom extensions

You can add custom extensions by creating a folder named extension in the same directory as the handler files, and adding the .ini and .so files of the extensions to this folder. For example, you can add and use the extension that contains a hello_world function as follows:

  1. .
  2. |____extension
  3. | |____hello.ini
  4. | |____hello.so
  5. |____main.php
  • hello.ini

    1. extension=/code/extension/hello.so
  • main.php

    1. <? php
    2. function handler($event, $context) {
    3. var_dump(extension_loaded('hello'));
    4. hello_world();
    5. return "ok";
    6. }

Use built-in packages

Function Compute currently provides the following built-in packages:

Package Version Description
oss v2.3.0 OSS SDK for PHP
tablestore V4.1.0 Table Store SDK for PHP
mns v1.3.5.5 MNS SDK for PHP

Example of using a built-in package

The following example uses a method from the built-in OSS library to upload a TXT file:

  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. }

Use custom packages

Function Compute also allows you to add custom packages. We recommend that you use Composer to install custom packages.

Method 1: Use Composer to install custom packages

If the package you want to use is from Packagist, the PHP Package Repository, you can use Composer to install this package. The following example uses the Function Compute command line tool fcli to install the Humble HTTP request library package requests:

  1. Create a folder to store the code and dependency modules.

    1. mkdir /tmp/code
  2. Create a function file, such as /tmp/code/index.php. Use requests in the code.

    1. <?php
    2. require_once __DIR__ . "/vendor/autoload.php";
    3. function handler($event, $context){
    4. $headers = array('Accept' => 'application/json');
    5. $options = array('auth' => array('user', 'pass'));
    6. $request = Requests::get('https://www.baidu.com', $headers, $options);
    7. var_dump($request->status_code);
    8. // int(200)
    9. var_dump($request->headers['content-type']);
    10. // string(31) "application/json; charset=utf-8"
    11. var_dump($request->body);
    12. // string(26891) "[...]"
    13. }
  3. Install the custom package under directory /tmp/code.

    1. Create the composer.json file as follows:

      1. {
      2. "require": {
      3. "rmccue/requests": ">=1.0"
      4. }
      5. }
    2. Run the composer install --no-dev command to install the dependencies.
      1. cd /tmp/code
      2. composer install --no-dev
    3. Check whether the installation has been successful. The /tmp/code directory is as follows if the installation is successful:

      1. ls -l /tmp/code
      2. -rw-r--r-- 1 rsong staff 72 8 22 09:54 composer.json
      3. -rw-r--r-- 1 rsong staff 2165 8 22 09:54 composer.lock
      4. -rw-r--r-- 1 rsong staff 523 8 22 09:54 index.php
      5. drwxr-xr-x 5 rsong staff 160 8 22 09:54 vendor
  4. Use fcli commands to create and call the function.

    1. ./fcli shell
    2. cd my-service
    3. mkf my-func -h index.handler --runtime php7.2 -d /tmp/code
    4. invk my-func

Method 2: Directly download custom packages

If the package you want to use is not from Packagist, the PHP Package Repository, for example, you want to use Aliyun-openapi-php-sdk and Log Service PHP SDK, you can directly download these packages and use them in the code. The following example uses the Function Compute command line tool fcli to install the Log Service PHP SDK:

  1. Create a folder to store the code and dependency modules.

    1. mkdir /tmp/code
  2. Create a function file, such as /tmp/code/index.php. Use Log Service PHP SDK methods in the code.

    1. <? php
    2. /* Use the autoloader class to automatically load all required PHP modules. Make sure you specify the correct path of the autoloader file */
    3. require_once realpath(dirname(__FILE__) . '/aliyun-log-php-sdk/Log_Autoload.php');
    4. function handler($event, $context){
    5. $endpoint = 'cn-hangzhou.sls.aliyuncs.com'; //Select the endpoint that corresponds to the region you have specified when you create the project.
    6. $accessKeyId = 'your_access_key_id'; //Your Alibaba Cloud AccessKeyId
    7. $accessKey = 'your_access_key'; //Your Alibaba Cloud AccessKeySecret
    8. $project = 'your_project'; //The log project name
    9. $logstore = 'your_logstore'; //The LogStore name
    10. $client = new Aliyun_Log_Client($endpoint, $accessKeyId, $accessKey);
    11. # List all LogStores in the specified log project
    12. $req1 = new Aliyun_Log_Models_ListLogstoresRequest($project);
    13. $res1 = $client->listLogstores($req1);
    14. var_dump($res1);
    15. }
  3. Download dependencies to directory /tmp/code.

    1. Run the following commands to download the dependencies.

      1. cd /tmp/code
      2. git clone https://github.com/aliyun/aliyun-log-php-sdk.git
    2. Check whether the download has been successful. The /tmp/code directory is as follows if the download is successful:

      1. ls -l /tmp/code
      2. drwxr-xr-x 11 rsong staff 352 8 22 10:35 aliyun-log-php-sdk
      3. -rw-r--r-- 1 rsong staff 957 8 22 10:42 index.php
  4. Use fcli commands to create and call the function.

    1. ./fcli shell
    2. cd my-service
    3. mkf my-func -h index.handler --runtime php7.2 -d /tmp/code
    4. invk my-func

Run external commands

If you want to run external tools, such as shell scripts, C++ code, or Go executables in your PHP functions, you can package and upload the tools and code together, and run external commands to use these tools. You can use the following PHP methods to run external programs: exec, system, and shell-exec.

Note: To run C, C++, and Go executables, make sure that the files are compatible with the Function Compute runtime environment. The PHP runtime environment in Function Compute is based on Linux 4.4.24-2.al7.x86_64 and Docker pull php:7.2.

The following example demonstrates how to use the exec method to run a shell script:

  1. <? php
  2. function handler($evt, $ctx){
  3. $script = $_ENV['FC_FUNC_CODE_PATH'] . '/script.sh';
  4. $a = exec("bash " . $script, $out, $status);
  5. print_r($a);
  6. var_dump($out);
  7. print_r($status);
  8. }

Handle exceptions

Function Compute captures exceptions that occur when executing PHP functions and returns information about the exceptions. The following example returns the oops exception:

  1. <? php
  2. function handler(event, context) {
  3. throw new Exception("oops");
  4. }

The system outputs the following response when the preceding function is called:

  1. {
  2. "errorMessage":"oops",
  3. "errorType":"Exception",
  4. "stackTrace":{
  5. "file":"/code/index.php",
  6. "line":3,
  7. "traceString":"#0 /var/fc/runtime/php7/src/invoke.php(67): handler('{\n "product"...', Array)
  8. #1 "
  9. }
  10. }

When an exception occurs, the HTTP header in the response message of the call containsX-Fc-Error-Type: UnhandledInvocationError. For more information about errors in Function Compute, see Error message.