Your First Function: PHP

This guide takes you through the process of writing a Cloud Function using the PHP runtime. There are two types of Cloud Functions:

  • An HTTP function, which you invoke from standard HTTP requests.
  • An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Cloud Pub/Sub topic, or changes in a Cloud Storage bucket.

The sample shows how to create a simple HTTP function.

Guide structure

  1. Creating a GCP project using Cloud SDK
  2. Creating a function
  3. Specifying dependencies
  4. Building and testing locally
  5. Deploying the function
  6. Testing the deployed function

Creating a GCP project using Cloud SDK

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  8. Install and initialize the Cloud SDK.
  9. Update and install gcloud components:
    gcloud components update
  10. Prepare your development environment.

    Go to Using PHP on Google Cloud

Creating a function

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X

    mkdir ~/helloworld_http
    cd ~/helloworld_http
    

    Windows

    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
  2. Create an index.php file in the helloworld_http directory with the following contents:

    <?php
    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloHttp(ServerRequestInterface $request): string
    {
        $name = 'World';
        $body = $request->getBody()->getContents();
        if (!empty($body)) {
            $json = json_decode($body, true);
            if (json_last_error() != JSON_ERROR_NONE) {
                throw new RuntimeException(sprintf(
                    'Could not parse body: %s',
                    json_last_error_msg()
                ));
            }
            $name = $json['name'] ?? $name;
        }
        $queryString = $request->getQueryParams();
        $name = $queryString['name'] ?? $name;
    
        return sprintf('Hello, %s!', htmlspecialchars($name));
    }
    

    This example function takes a name supplied in the HTTP request and returns a greeting, or "Hello World!" when no name is supplied.

Specifying dependencies

You use Composer to manage dependencies in PHP. If you don't already have Composer installed, you can do so as follows:

  1. Download Composer to any location you desire.

  2. Once it is downloaded, move the composer.phar file to a directory that is in your system path, for example:

    mv composer.phar /usr/local/bin/composer
    

Next, specify your function's dependencies:

  1. Add a composer.json file containing dependencies to your function code directory, where FUNCTION_TARGET=FUNCTION_NAME indicates the name of your function. In this example, FUNCTION_NAME is helloHttp:

    {
        "require": {
            "google/cloud-functions-framework": "^1.0"
        },
        "scripts": {
            "start": [
               "Composer\\Config::disableProcessTimeout",
               "FUNCTION_TARGET=helloHttp php -S localhost:${PORT:-8080} vendor/bin/router.php"
            ]
        }
    }
    
  2. In the directory containing your function code (which must also contain the composer.json file you just created), run the following command:

    composer require google/cloud-functions-framework
    

    This adds the Functions Framework to your composer.json. It also creates a vendor/ directory in your function code directory that contains the dependencies.

Building and testing locally

Once you have completed the steps in Specifying dependencies, you can build and test your function locally.

The following command creates a local web server running your helloHttp function:

export FUNCTION_TARGET=helloHttp
php -S localhost:8080 vendor/bin/router.php

If the function builds successfully, it displays a URL. You can visit this URL with your web browser: http://localhost:8080/. You should see a Hello World! message.

Alternatively, you can send requests to this function using curl from another terminal window:

curl localhost:8080
# Output: Hello World!

Deploying the function

To deploy the function with an HTTP trigger, run the following command in the helloworld_http directory:

gcloud functions deploy helloHttp --runtime php74 --trigger-http --allow-unauthenticated

The --allow-unauthenticated flag lets you reach the function without authentication. To require authentication, omit the flag.

Testing the deployed function

  1. When the function finishes deploying, take note of the httpsTrigger.url property or find it using the following command:

    gcloud functions describe helloHttp
    

    It should look like this:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
  2. Visit this URL in your browser. You should see a "Hello World!" message.

    Try passing a name in the HTTP request, as shown in this example URL:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME

    You should see the message "Hello NAME!"

Viewing logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Cloud Logging UI, and via the gcloud command-line tool.

To view logs for your function with the gcloud tool, use the gcloud logs read command, followed by the name of the function:

gcloud functions logs read helloHttp

The output should resemble the following:

LEVEL  NAME       EXECUTION_ID  TIME_UTC                 LOG
D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:25.983  Function execution started
D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:26.001  Function execution took 19 ms, finished with status code: 200

Using the Logging dashboard

You can also view logs for Cloud Functions from the Cloud Console.