Create and deploy an HTTP Cloud Run function by using PHP (1st gen)

This guide takes you through the process of writing a Cloud Run function using the PHP runtime. There are two types of Cloud Run 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 Pub/Sub topic, or changes in a Cloud Storage bucket.

The sample shows how to create a simple HTTP function.

Before you begin

  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 Google Cloud 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 Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

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

    Get started with PHP

Create 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 Google\CloudFunctions\FunctionsFramework;
    use Psr\Http\Message\ServerRequestInterface;
    
    // Register the function with Functions Framework.
    // This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=http` environment
    // variable when deploying. The `FUNCTION_TARGET` environment variable should
    // match the first parameter.
    FunctionsFramework::http('helloHttp', 'helloHttp');
    
    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.

Specify 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": {
            "php": ">= 8.1",
            "google/cloud-functions-framework": "^1.1"
        },
        "scripts": {
            "start": [
               "Composer\\Config::disableProcessTimeout",
               "FUNCTION_TARGET=helloHttp php -S localhost:${PORT:-8080} vendor/google/cloud-functions-framework/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.

Build and test locally

Once you have completed the steps in Specify 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!

Deploy the function

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

gcloud functions deploy helloHttp --no-gen2 --runtime php82 --trigger-http --allow-unauthenticated

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

Test 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!"

View logs

Logs for Cloud Run functions are viewable using the Google Cloud CLI, and in the Cloud Logging UI.

Use the command-line tool

To view logs for your function with the gcloud CLI, 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

Use the Logging dashboard

You can also view logs for Cloud Run functions from the Google Cloud console.