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

Print logs

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

  • Log levels

    You can call the setLevel method to specify the level of logs you want to print. The following table lists the log levels in descending order.

    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 setting) 200 $logger->info Detailed output information
    DEBUG 100 $logger->debug Debug logs

    For more information about function logs, see t1881203.html#multiTask1626.

  • Log printing example 1
    <? php
    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            
  • Log printing example 2
    <? php
    use Monolog\Logger;
    function handler($evt, $ctx) {
        $logger = $GLOBALS['fcLogger'];
        $logger->setLevel(400);
        $logger->error("console error 1");
        $logger->info("console info 1");
        $logger->warning("console warn 1");
        $logger->debug("console debug 1");
    
        $logger->setLevel(Logger::WARNING);
        $logger->error("console error 2");
        $logger->info("console info 2");
        $logger->warn("console warn 2");
        $logger->debug("console debug 2");
    
        $logger->setLevel(200);
    }            

    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            

Handle errors

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

<? php
function handler($event, $context) {
  throw new Exception("oops");
}           

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

{
    "errorMessage":"oops",
    "errorType":"Exception",
    "stackTrace":{
        "file":"/code/index.php",
        "line":3,
        "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 Handle errors.

Use built-in extensions

This section describes the built-in extensions for the PHP runtime environments, which meet most of your needs.

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

Sample built-in extension

The following sample code uses imagick to process an image:

<? php
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());
}           

Use custom extensions

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

.
|____extension
| |____hello.ini
| |____hello.so
|____main.php           
  • hello.ini
    extension=/code/extension/hello.so            
  • main.php
        <? php
        function handler($event, $context) {
            var_dump(extension_loaded('hello'));
            hello_world(); 
            return "ok";
        }                    

Use 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 Table Store SDK for PHP
mns v1.3.5.5 MNS SDK for PHP
fc v1.1.0 Function Compute SDK for PHP

Sample built-in package

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

<? php
use OSS\OssClient;
function handler($event, $context) {
     $accessKeyId = $context["credentials"]["accessKeyId"];
     $accessKeySecret = $context["credentials"]["accessKeySecret"];
     $securityToken = $context["credentials"]["securityToken"];
     $endpoint = "oss-cn-shenzhen.aliyuncs.com";
     $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) {
        print($e->getMessage());
     }
    return 'success';
}           

Use custom packages

Install custom packages

Function Compute also allows you to install custom packages. This section describes two ways 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 this package. The following example shows how to install Humble HTTP request library package requests:

    1. Create a folder to store the code and dependencies.
      mkdir /tmp/code       
    2. Create a code file, such as /tmp/code/index.php, and use requests in the code.
      <? php
      require_once __DIR__ . "/vendor/autoload.php";
      function handler($event, $context){
         $headers = array('Accept' => 'application/json');
         $options = array('auth' => array('user', 'pass'));
         $request = Requests::get('https://www.baidu.com', $headers, $options);
         var_dump($request->status_code);
         // int(200)
         var_dump($request->headers['content-type']);
         // string(31) "application/json; charset=utf-8"
         var_dump($request->body);
         // 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 the 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 and 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 the Log Service (SLS) SDK for PHP:
    1. Create a folder to store the code and dependencies.
      mkdir /tmp/code            
    2. Create a code file, such as /tmp/code/index.php, and use requests in the code.
      <? php
      /* Use the autoloader class to automatically load all required PHP modules. Make sure to use the suitable 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 = 'ch-hangzhou.sls.aliyuncs.com'; // Select an SLS endpoint that matches the region of the project created in the above process
         $accessKeyId = 'your_access_key_id';        // Use the AccessKey ID of your Alibaba Cloud account
         $accessKey = 'your_access_key';             // The AccessKey secret of your Alibaba Cloud account
         $project = 'your_project';                  //The log project name
         $logstore = 'your_logstore';                //The Logstore name
         $client = new Aliyun_Log_Client($endpoint, $accessKeyId, $accessKey);
         #List all Logstore names for the current project
         $req1 = new Aliyun_Log_Models_ListLogstoresRequest($project);
         $res1 = $client->listLogstores($req1);
         var_dump($res1);
      }            
    3. Download dependencies to the /tmp/code directory.
      cd /tmp/code
      git clone https://github.com/aliyun/aliyun-log-php-sdk.git           

Compress files and upload them to Function Compute

You must compress the desired files into a package instead of all code folders. After you compress the files, 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 the desired code directories of the function, right-click these files, and compress the files into a code package in ZIP format.
  • In Linux, when you call the zip command, specify all the files in the desired code directories as source files to generate a deployment code package. For example, you can use zip code.zip /home/code/*.

After the compression is complete, you can click the function name in the . 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 Docker pull php:7.2.

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

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