Function PHP

Note: This content applies only to Cloud Functions (1st gen). See Cloud Functions version comparison for more information.

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.

Learn more: For more details, read about and CloudEvent functions.

Guide structure

Creating a GCP project using gcloud CLI

  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.

    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a 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.

    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  6. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  8. Install and initialize the gcloud CLI.
  9. Update and install
    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    5 components:
    gcloud components update
  10. Note: Need a command prompt? You can use the Google Cloud Shell. The Google Cloud Shell is a command line environment that already includes the Google Cloud CLI, so you don't need to install it. The Google Cloud CLI also comes preinstalled on Google Compute Engine Virtual Machines.
  11. 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

    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    6 file in the
    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    7 directory with the following contents:

    functions/helloworld_http/index.php

    View on GitHub

    <?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.

    Note: Cloud Functions looks for deployable functions in
    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    6 by default. Use the flag when to specify a different directory containing an
    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    6 file.

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

    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    2 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

    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    3 file containing dependencies to your function code directory, where
    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    4 indicates the name of your function. In this example,
    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    5 is
    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    6:

    functions/helloworld_http/composer.json

    View on GitHub

    {
        "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"
            ]
        }
    }
    

  2. In the directory containing your function code (which must also contain the

    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    3 file you just created), run the following command:

    composer require google/cloud-functions-framework
    

    This adds the Functions Framework to your

    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    3. It also creates a
    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
    9 directory in your function code directory that contains the dependencies.

Learn more: For more details, read about specifying dependencies.

Building and testing locally

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

The following command creates a local web server running your

mkdir %HOMEPATH%\helloworld_http
cd %HOMEPATH%\helloworld_http
6 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:

<?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));
}
1. You should see a
<?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));
}
2 message.

Alternatively, you can send requests to this function using

<?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));
}
3 from another terminal window:

curl localhost:8080
# Output: Hello World!
Note: See the Cloud Functions testing documentation for information on writing unit tests for HTTP functions and CloudEvent functions.

Deploying the function

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

mkdir ~/helloworld_http
cd ~/helloworld_http
7 directory:

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

The

<?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));
}
5 flag lets you reach the function . To require , omit the flag.

Learn more: For more details, read about deploying Cloud Functions.

Testing the deployed function

  1. When the function finishes deploying, take note of the

    <?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));
    }
    
    6 property or find it using the following command:

    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    0

    It should look like this:

    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    1
  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:

    mkdir ~/helloworld_http
    cd ~/helloworld_http
    
    2

    You should see the message "Hello

    <?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));
    }
    
    7!"

Viewing logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Cloud Logging UI, and via the Google Cloud CLI.

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

<?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));
}
8 command, followed by the name of the function:

mkdir ~/helloworld_http
cd ~/helloworld_http
3

The output should resemble the following:

mkdir ~/helloworld_http
cd ~/helloworld_http
4Note: There is typically a slight delay between when log entries are created and when they show up in Cloud Logging.

What is a function in PHP?

PHP User Defined Functions A function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.

What is PHP function example?

A function is a piece of code that takes another input in the form of a parameter, processes it, and then returns a value. A PHP Function feature is a piece of code that can be used over and over again and accepts argument lists as input, and returns a value. PHP comes with thousands of built-in features.

How to declare a function in PHP?

Creating a Function To call a function we just need to write its name followed by the parenthesis. A function name cannot start with a number. It can start with an alphabet or underscore. A function name is not case-sensitive.

What are the types of functions in PHP?

Types of Functions in PHP. There are two types of functions as: Internal (built-in) Functions. User Defined Functions.