Function Compute supports the PHP 7.2.7 runtime environment, where Runtime=php7.2. This topic describes log printing, error handling, PHP extensions, custom packages, and external commands in PHP runtime environments.

Log printing

Function Compute provides a built-in logger module, which can be used by using$GLOBALS['fcLogger']. The logs that are printed are collected to the Logstore that you specify when you create the service.

  • Log level

    You can call the setLevel method to specify the level of logs that you want to print. The following table lists the log levels by severity from high to low.

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

    For more information about function logs, see Grant an event source permissions to access Function Compute.

  • Example 1
    function handler($event, $context) {
        $logger = $GLOBALS['fcLogger'];
        $logger->info("hello world");
        return 'hello world';

    After the preceding code is executed, the following log is printed:

    message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [INFO] hello world            
  • Example 2
    use Monolog\Logger;
    function handler($evt, $ctx) {
        $logger = $GLOBALS['fcLogger'];
        $logger->error("console error 1");
        $logger->info("console info 1");
        $logger->warning("console warn 1");
        $logger->debug("console debug 1");
        $logger->error("console error 2");
        $logger->info("console info 2");
        $logger->warn("console warn 2");
        $logger->debug("console debug 2");

    After the preceding code is executed, the following log is printed:

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


Function Compute captures exceptions that occur during the execution of PHP functions and returns information about the exceptions. In the following sample code, information about the oops exception is returned.

function handler($event, $context) {
  throw new Exception("oops");

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

        "traceString":"#0 /var/fc/runtime/php7/src/invoke.php(67): handler('{\n "product"...', Array)
#1 "

When an error occurs, the HTTP header in the response contains X-Fc-Error-Type: UnhandledInvocationError. For more information about error types in Function Compute, see Troubleshooting.

PHP built-in extensions

This section describes a list of built-in extensions for the PHP runtime environment and provides examples.

Built-in extension list

Note If you want to view and print the installed PHP extensions, include print_r(get_loaded_extensions()); in the code of the target function.
bcmath bz2 calendar Core
ctype curl date dom
exif fileinfo filter ftp
gd gettext gmp hash
iconv imagick json libxml
mbstring memcached mysqli mysqlnd
openssl pcntl pcre PDO
pdo_mysql Phar posix protobuf
readline redis Reflection session
shmop SimpleXML soap sockets
SPL standard sysvmsg sysvsem
sysvshm tokenizer xdebug xml
xmlreader xmlrpc xmlwriter Zend OPcache
zip zlib Xdebug Zend OPcache

Example of built-in extensions

The following sample code uses imagick to process an image:

function imageProc($event, $context) {
    $image = new Imagick(__DIR__ . '/lena.jpg');
    $image->thumbnailImage(100, 0);
    $image->writeImages(__DIR__ . "/thumb.jpg", true);
    return strval($image->getImageWidth()) . "," . strval($image->getImageHeight());

PHP custom extensions

You can create a directory named extension in the same directory as the function handler files, and put the .ini and .so files of the extension in the extension directory to add the PHP custom extension. The following example shows the custom extension hello. Assume that the extension has a hello_world function.

Notice When you use the PHP runtime, Function Compute automatically sets the PHP_INI_SCAN_DIR environment variable for you to point to /usr/local/etc/php/conf.d:/code/extension so that you can load custom extensions. For more information, see Load and unload built-in extensions.
| |____hello.ini
| |
  • hello.ini
  • main.php
        function handler($event, $context) {
            return "ok";

PHP built-in packages

Function Compute provides the following built-in packages.

Package Version Description
oss v2.3.0 OSS SDK for PHP
tablestore v4.1.0 Tablestore SDK for PHP
mns v1.3.5.5 MNS SDK for PHP
fc v1.1.0 Function Compute SDK for PHP

Example of built-in packages

The following sample code shows how to use methods in the OSS built-in package to upload a .txt file:

use OSS\OssClient;
function handler($event, $context) {
     $accessKeyId = $context["credentials"]["accessKeyId"];
     $accessKeySecret = $context["credentials"]["accessKeySecret"];
     $securityToken = $context["credentials"]["securityToken"];
     $endpoint = "";
     $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
     $bucket = "my-bucket";
     $object = "php.txt";
     $content = "Hello fc!";
     try {
        $ossClient->putObject($bucket, $object, $content);
     } catch (OssException $e) {
    return 'success';

PHP custom packages

Install custom packages

Function Compute allows you to install custom packages. This section describes two methods to install custom packages.

  • Method 1: Use Composer to install custom packages (recommended)

    If the package you want to use is from Packagist, the PHP Package Repository, you can use Composer to install the package. The following example shows how to install the Humble HTTP request library package requests.

    1. Create a folder to store the code and dependent modules.
      mkdir /tmp/code       
    2. Create a code file, such as /tmp/code/index.php, and use requests in the code.
      require_once __DIR__ . "/vendor/autoload.php";
      function handler($event, $context){
         $headers = array('Accept' => 'application/json');
         $options = array('auth' => array('user', 'pass'));
         $request = Requests::get('', $headers, $options);
         // int(200)
         // string(31) "application/json; charset=utf-8"
         // string(26891) "[...]"
    3. Install the custom package in the /tmp/code directory.
      1. Create a file named composer.json.
            "require": {
                "rmccue/requests": ">=1.0"
      2. Run the composer install --no-dev command to install dependencies.
        cd /tmp/code
        composer install --no-dev            
  • Method 2: Directly download the custom package
    If the package you want to use, such as Aliyun-openapi-php-sdk or Log Service SDK for PHP, is unavailable at Packagist The PHP Package Repository, you can directly download the package and reference the package in the code. The following example shows how to add a custom package of Log Service SDK for PHP:
    1. Create a folder to store the code and dependent modules.
      mkdir /tmp/code            
    2. Create a code file, such as /tmp/code/index.php, and use requests in the code.
      /* Use the autoloader class to automatically load all required PHP modules. Make sure to use the valid path to specify the file containing the autoloader class. */
      require_once realpath(dirname(__FILE__) . '/aliyun-log-php-sdk/Log_Autoload.php');
      function handler($event, $context){
         $endpoint = ''; // Select an endpoint that matches the region of the project created in the preceding process.
         $accessKeyId = 'your_access_key_id';        // Use the AccessKey ID of your Alibaba Cloud account.
         $accessKey = 'your_access_key';             // Use the AccessKey secret of your Alibaba Cloud account.
         $project = 'your_project';                  // Specifies the name of the log project.
         $logstore = 'your_logstore';                // Specifies the name of your Logstore.
         $client = new Aliyun_Log_Client($endpoint, $accessKeyId, $accessKey);
         # List names of all Logstores for the current log project.
         $req1 = new Aliyun_Log_Models_ListLogstoresRequest($project);
         $res1 = $client->listLogstores($req1);
    3. Download dependencies to the /tmp/code directory.
      cd /tmp/code
      git clone           

Package files and upload them to Function Compute.

You must package the files that you want instead of all code folders. After the files are packaged, ensure that the files of the handler function are placed in the root directory of the package.

  • In Windows, you can select all the files in specific code directories of the function, right-click these files, and compress the files into a code package in the ZIP format.
  • In Linux, when you call the zip command, specify all the files in the code directories as source files to generate a deployment code package. For example, you can use zip /home/code/*.

After the compression is complete, you can click the function name in the Function Compute console. On the page that appears, click the Code tab, and select Import from OSS or Upload Zip File to upload the code package.

Call external commands

If you want to run external tools, such as shell scripts and executable files compiled in C++ or Go 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 execute external programs: exec, system, and shell-exec.

Note The executable files compiled in C, C++, and Go must be compatible with the runtime environment of Function Compute. The PHP runtime environment in Function Compute is based on Linux 4.4.24-2.al7.x86_64 and the Docker pull php:7.2 basic image.

The following sample code shows how to use the exec method to call a shell script.

function handler($evt, $ctx){
    $script = $_ENV['FC_FUNC_CODE_PATH'] . '/';
    $a = exec("bash " . $script, $out, $status);