Create and deploy an HTTP Cloud Function with 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 Pub/Sub topic, or changes in a Cloud Storage bucket.

For more detail, read writing HTTP functions and writing event-driven functions.

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, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging 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, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

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

    Go to Using PHP on Google Cloud

Create your 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. For more discussion of the structure and required elements in a PHP HTTP function, see Write HTTP functions.

Specify dependencies

  1. PHP uses Composer to manage dependencies. If you're using Cloud Shell, composer is pre-installed. Otherwise, you can install it with the following commands:

    1. Run the PHP Command-line installation script on the Composer download page to download Composer to your development machine.

    2. Move the composer.phar file to your /usr/local/bin directory:

      sudo mv composer.phar /usr/local/bin/composer
      
  2. Specify your function's dependencies:

    1. Add a composer.json file with the following contents to the helloworld_http directory:

      {
          "require": {
              "php": ">= 7.4",
              "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"
              ]
          }
      }
      

    The FUNCTION_TARGET line specifies your function's entry point.

    1. Run the following command in the helloworld_http directory:
    composer require google/cloud-functions-framework
    

    This adds the Functions Framework to your composer.json and creates a vendor directory inside helloworld_http that contains the dependencies.

Build and test your function locally

To build and test your function locally before deploying it, perform the following steps:

  1. Create a local web server running your helloHttp function:

    export FUNCTION_TARGET=helloHttp
    composer start
    
  2. Test your function by visiting http://localhost:8080 in a browser or by running curl localhost:8080 from another window.

    See Sending requests to local functions for more detail.

This sample function returns a cheery "Hello, World!" message.

Deploy your function

To deploy your function, run the following command in the helloworld_http directory:

  gcloud functions deploy php-http-function \
    --gen2 \
    --runtime=php82 \
    --region=REGION \
    --source=. \
    --entry-point=helloHttp \
    --trigger-http \
    --allow-unauthenticated

Replace REGION with the name of the Google Cloud region where you want to deploy your function (for example, us-west1).

The optional --allow-unauthenticated flag lets you reach your function without authentication.

Test your deployed function

  1. After the function deploys, note the uri property from the output of the gcloud functions deploy command, or retrieve it with the following command:

      gcloud functions describe php-http-function \
        --region=REGION
    

    Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

  2. Visit this URL in your browser. The function returns a "Hello World!" message.

    You can also find this URL in Google Cloud console. Go to the Cloud Functions Overview page, and click the name of your function to open its Function details page. Open the TRIGGER tab to see your function's URL.

View your function's logs

View the logs with the command-line tool

You can review your function's logs with the Cloud Logging UI or via the Google Cloud CLI.

To view logs for your function with the gcloud CLI, use the logs read command:

    gcloud functions logs read \
      --gen2 \
      --limit=10 \
      --region=REGION \
      php-http-function

Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

The output resembles the following:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:36.067
LOG:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:22.814
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "hello_http-1" on port 8080.

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:22.777
LOG: [pid1-nginx] Starting nginx (pid 17): /usr/sbin/nginx -c /tmp/nginxconf-953701689/nginx.conf [session:R8F8ZJ5]

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:22.766
LOG: [pid1-nginx] Successfully connected to /tmp/google-config/app.sock after 556.430499ms [session:R8F8ZJ5]

View logs with the logging dashboard

To view the logs for your function with the logging dashboard, open the Cloud Functions Overview page and click the name of your function from the list, then click the Logs tab.