PHP 7.4 is now generally available.

Building an App with PHP 7

Region ID

The REGION_ID is an abbreviated code that Google assigns based on the region you select when you create your app. The code does not correspond to a country or province, even though some region IDs may appear similar to commonly used country and province codes. Including REGION_ID.r in App Engine URLs is optional for existing apps and will soon be required for all new apps.

To ensure a smooth transition, we are slowly updating App Engine to use region IDs. If we haven't updated your Google Cloud project yet, you won't see a region ID for your app. Since the ID is optional for existing apps, you don't need to update URLs or make other changes once the region ID is available for your existing apps.

Learn more about region IDs.

This guide takes you through the process of building a PHP 7.2 app with App Engine. The sample app allows users to post the titles, authors, descriptions, publication date, and images of their favorite books to a webpage. The app stores the textual data in a Cloud SQL database and the images in a Cloud Storage bucket.

Guide structure

  1. Creating a Google Cloud project using Cloud SDK

  2. Downloading the sample app

  3. Specifying dependencies with composer.json

  4. Initializing the app and defining front controllers

  5. Integrating with Google Cloud services

  6. Configuring the app for App Engine

  7. Deploying the app

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 Cloud project. Learn how to confirm that billing is enabled for your project.

  4. Enable the Cloud Build API.

    Enable the API

  5. Install and initialize the Cloud SDK.
  6. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  8. Enable the Cloud Build API.

    Enable the API

  9. Install and initialize the Cloud SDK.
  10. Install Composer, the PHP dependency management tool. You must install Composer globally on Linux and Mac OS X systems.

Downloading the sample app

  1. Explore the code on GitHub

  2. Download or clone the app.

    git clone

    Or download the sample as a zip file and extract it.

  3. Navigate to the getting-started directory.

    cd appengine/standard/getting-started

Specifying dependencies with composer.json

The app uses a front controller to route requests. The sample code in this guide uses the Slim Framework, but you are free to use a web framework of your choice.

  1. Open the composer.json file to review all direct dependencies:

      "require": {
        "google/cloud-storage": "^1.6",
        "slim/slim": "^4.0",
        "slim/psr7": "^1.0",
        "slim/twig-view": "^3.0",
        "php-di/slim-bridge": "^3.1",
        "symfony/yaml": "^5.2"
      "autoload": {
         "psr-4": {
           "Google\\Cloud\\Samples\\AppEngine\\GettingStarted\\": "src"
  2. Run composer install to download dependencies and produce a composer.lock file. The composer.lock file is used to ensure your app will retrieve the same versions of the packages you use across multiple builds and environments.

Initializing the app and defining front controllers

The index.php file initializes the app and forwards all requests to controllers defined in the ./src/controllers.php file.

// Use the composer autoloader to load dependencies.
require_once __DIR__ . '/vendor/autoload.php';

//  Load the application code.
/** @var Slim\App $app */
$app = require __DIR__ . '/src/app.php';
require __DIR__ . '/src/controllers.php';

// Bootstrap the slim framework to handle the request.

For more on request handling, read about application startup and handling requests.

Integrating with Google Cloud services

App Engine requires apps to integrate with external systems for data storage. The sample app stores textual data on Cloud SQL and images on Cloud Storage.

See the Choosing a Storage Option page for all Google Cloud storage options.

Using Cloud SQL

In the sample app, users post books to a webpage. The app uses a Cloud SQL database to store the titles, authors, publication date, and descriptions of the books.

You will need to create a Cloud SQL instance before adding content to the app's database.

Creating a Cloud SQL instance

Use the Cloud SDK to create a Cloud SQL instance:

gcloud sql instances create INSTANCE_NAME --tier=MACHINE_TYPE --region=REGION

For example, if you want to name your instance bookshelf and use the machine type of db-n1-standard-2 in the United States central region:

gcloud sql instances create bookshelf --tier=db-n1-standard-2 --region=us-central1

Setting up the MySQL root user

You can use the gcloud command-line tool to set the root user's password of your Cloud SQL instance:

gcloud sql users set-password USER --host=HOST --instance=INSTANCE_NAME --password=PASSWORD

For example, if you want to set the root user's password for the Cloud SQL instance bookshelf to passw0rd!:

gcloud sql users set-password root --host=% --instance=bookshelf --password=passw0rd!

Setting up a database on the Cloud SQL instance

To store the authors, titles, publication date, and descriptions of the books, create a MySQL database:

gcloud sql databases create DATABASE_NAME --instance=INSTANCE_NAME

For example, if you want to create a database called book-data on the Cloud SQL instance bookshelf:

gcloud sql databases create book-data --instance=bookshelf

Connecting to Cloud SQL database

The sample app uses PHP's PDO to interact with the MySQL database.

// Fill the variables below to match your Cloud SQL configuration.
// $dbUser = 'YOUR_CLOUDSQL_USER';
$dsn = "mysql:unix_socket=/cloudsql/${dbConn};dbname=${dbName}";
$pdo = new PDO($dsn, $dbUser, $dbPass);

For this tutorial, these parameters are specified as environment variables below in Configuring the app.

Querying a single row

When the user clicks on a book, the app queries the database and returns a single row that includes the title, author, publication date, and description of the book.

$statement = $pdo->prepare('SELECT * FROM books WHERE id = :id');
$statement->bindValue('id', $id, PDO::PARAM_INT);
$result = $statement->fetch(PDO::FETCH_ASSOC);

Using Cloud Storage

The sample app uses Cloud Storage to store the images, which are binary files, uploaded by users.

Creating a Cloud Storage bucket

Cloud Storage uses buckets to organize and control access to your data.

Use Cloud SDK to create a Cloud Storage bucket:

gsutil mb -l BUCKET_REGION gs://BUCKET_NAME/

For example, if you want to create a bucket called picture-storage in the us-central1 region:

gsutil mb -l us-central1 gs://picture-storage/
  • If successful, you see the following output:

    Creating gs://BUCKET_NAME/
  • If not successful, you might see the following output:

    ServiceException: 409 Bucket BUCKET_NAME already exists

    Try again with a different bucket name.

Connecting a project to a Cloud Storage bucket

To use Cloud Storage, you need to specify the Cloud Storage library.

use Google\Cloud\Storage\StorageClient;

Storing images

Now that you have created a Cloud Storage bucket and set up a connection, you can store images. Images can be uploaded with predefined access controls lists (ACL) to control access to the images.

In this sample app, uploaded images will have the predefined ACL public-read. The public URL can be accessed via the mediaLink property of your Cloud Storage object. You can use this URL in an HTML image tag.

// Set your own image file path and content type below to upload an
// image to Cloud Storage.
// $imageStream = fopen('/path/to/your_image.jpg', 'r');
// $imageContentType = 'image/jpg';
$object = $bucket->upload($imageStream, [
    'metadata' => ['contentType' => $imageContentType],
    'predefinedAcl' => 'publicRead',
$imageUrl = $object->info()['mediaLink'];

For instructions on how to read a private Cloud Storage object, see Downloading Objects page.

Deleting images

When a user deletes a book from the app, this code removes the image from the Cloud Storage bucket.

$object = $bucket->object($objectName);

Configuring the app

You configure applications to run on App Engine using an app.yaml file, which specifies the application's runtime, environment variables, and other settings.

For an app with minimal configuration requirements, the app.yaml file can be a single line:

runtime: php72

You can add further configuration options and application-specific environment variables into the app.yaml configuration file.

Adding environment variables

The app.yaml file is where environment configuration is provided to the app. The bookshelf example used in this guide needs configuration provided as environment variables to know how to connect to the correct Cloud SQL instance and Cloud Storage bucket.

To deploy your app, you need to edit the app.yaml configuration file:

# See for a
# complete list of `app.yaml` directives.

runtime: php74

    # populate these to use the "mysql" or "postres" backends
    ## Uncomment to give your database a name other than "bookshelf"
  1. Set the GOOGLE_STORAGE_BUCKET variable to the name of your Cloud Storage bucket.

  2. Set the CLOUDSQL_CONNECTION_NAME variable to app-name:region:instance-name You can retrieve the necessary details by using the following gcloud command:

    gcloud sql instances describe INSTANCE

    For a Cloud SQL Second Generation instance, the CLOUDSQL_CONNECTION_NAME will be in the following format: your_project_name:your_region:your_instance

  3. Uncomment and set the CLOUD_SQL_DATABASE_NAME variable if the database you have created has a name other than bookshelf. In this example, te database was created with the name book-data.

  4. Review your app.yaml file, which should look something like:

    runtime: php72
      GOOGLE_STORAGE_BUCKET: picture-storage
      CLOUDSQL_CONNECTION_NAME: sample-application:us-central1:bookshelf
      CLOUDSQL_USER: root
      CLOUDSQL_PASSWORD: passw0rd!

Deploying the application

  1. To deploy the application, navigate to the getting-started directory and run the following command:

    gcloud app deploy
  2. When the location prompt appears, choose a location near your app users. App Engine is regional, which means the infrastructure that runs your app is located in a specific geographic area. For example, this tutorial has used the us-central1 region to deploy its storage resources. Deploy the app in the same region to decrease latency and improve performance.

    In general, choosing a location near your users is a good idea, but there are cases when deploying your application near where its resources are located is recommended. Read about the available App Engine locations and resource locations.

  3. View the application:

    gcloud app browse

Cleaning up

Delete your Google Cloud project to stop the billing for the resources used within the project.

To deleted your project using the following command:

gcloud projects delete PROJECT_ID

To verify the project was deleted, list your projects:

gcloud projects list

What's next