PHP 5 Runtime Environment

With App Engine, you can build web applications using the PHP Programming Language. Your PHP application runs on Google's scalable infrastructure and uses large- scale persistent storage and services.

Selecting the PHP runtime

App Engine runs your PHP web application using a PHP version 5.5.34 interpreter. Note: On Linux you must also install PHP locally to run your PHP apps.

To set your app to use the PHP runtime, add the following to your app.yaml file:

runtime: php55
api_version: 1
...

The first element, runtime, selects the PHP runtime environment.

The second element, api_version, selects which version of the PHP runtime environment to use. As of this writing, App Engine only has one version of the PHP environment, 1. If there are future changes that might not be backwards compatible, the App Engine team will use a a new version identifier. Your app will continue to use the selected version until you change the api_version setting and upload your app.

For more information about the app.yaml file and how to deploy your app to App Engine, see the app.yaml Reference, and Deploying a PHP App topics.

The sandbox

To allow App Engine to distribute requests for applications across multiple web servers, and to prevent one application from interfering with another, the application runs in a restricted "sandbox" environment. In this environment, the application can execute code, use the App Engine mail, URL fetch and users services, and examine the user's web request and prepare the response.

An App Engine application cannot:

  • write to the filesystem. PHP applications can use Google Cloud Storage for storing persistent files. Reading from the filesystem is allowed, and all application files uploaded with the application are available.

  • respond slowly. A web request to an application must be handled within a few seconds. Processes that take a very long time to respond are terminated to avoid overloading the web server.

  • make other kinds of system calls.

Automatic class loading

Both Standard PHP Library (SPL) classes and any classes that are part of the SDK for App Engine are automatically loaded when needed. This means that you do not have to use include or require statements at the top of your PHP scripts.

By default, automatic class loading will occur only for classes defined in files that reside in the root directory of SDK for App Engine root (and, if it has been specified by --php_executable_path, your local PHP installation).

To add more paths to be searched for automatic class loading, use set_include_path in your PHP script.

set_include_path('my_additional_path' . PATH_SEPARATOR . get_include_path());

Enabled extensions

The following extensions have been enabled in the PHP runtime for App Engine:

  • apc
  • bcmath
  • calendar
  • Core
  • ctype
  • date
  • dom
  • ereg
  • exif
  • filter
  • ftp
  • gd
  • hash
  • iconv
  • json
  • libxml
  • mailparse
  • mbstring
  • mcrypt
  • memcache
  • memcached
  • mysql
  • mysqli
  • mysqlnd
  • OAuth
  • openssl
  • pcre
  • PDO
  • pdo_mysql
  • Reflection
  • session
  • shmop
  • SimpleXML
  • soap
  • sockets (for billing-enabled apps)
  • SPL
  • standard
  • tokenizer
  • xml
  • xmlreader
  • xmlwriter
  • xsl
  • zip
  • zlib

Dynamically loadable extensions

The following extensions are dynamically loadable by configuring php.ini.

To enable these extensions, add directives for them in your php.ini file under extension like so:

extension = "curl.so"
extension = "mongo.so"
extension = "imagick.so"
extension = "intl.so"
extension = "fileinfo.so"

Sessions

Most web applications need a way to preserve user state information between requests. PHP provides a convenient session management layer. Sessions in App Engine work much like sessions in any other PHP application.

Setting a variable in a user's session:

session_start();
$_SESSION['Foo'] = 'Bar';

On a subsequent request by the same user:

session_start();
print $_SESSION['Foo']; // prints Bar

By default the App Engine runtime will use memcache to store session information using the MemcacheSessionHandler class. You can adjust this behavior by specifying your own session handler using PHP's session_set_save_handler() method. Memcache allows session data to be saved and retrieved quickly, meaning the overhead on your request is minimal. However data in App Engine memcache might be flushed periodically, meaning any session information will be lost. For longer-lived sessions, it can be preferable to use an alternative storage service such as Cloud SQL.

Special $_SERVER keys

PHP makes the special $_SERVER[] array available to in the request scope. In addition to the standard CGI paramaters, App Engine adds some additional useful keys.

  • APPLICATION_ID - The app_id of the application set when the app was created. eg. my-wordpress
  • AUTH_DOMAIN - The domain used for authenticating users with the Users API. Apps hosted on appspot.com have an AUTH_DOMAIN of gmail.com, and accept any Google account. Apps hosted on a custom domain using Google Workspace have an AUTH_DOMAIN equal to the custom domain
  • CURRENT_VERSION_ID - The major and minor version of the currently running application, as "X.Y". The major version number ("X") is specified in the app's app.yaml file. The minor version number ("Y") is set automatically when each version of the app is uploaded to App Engine. On the development web server, the minor version is always "1".
  • DEFAULT_VERSION_HOSTNAME - The hostname of the default version of this application, eg. my-php-app.uc.r.appspot.com.
  • HTTP_X_APPENGINE_CITY - Name of the city from which the request originated. For example, a request from the city of Mountain View might have the header value mountain view.
  • HTTP_X_APPENGINE_CITYLATLONG - Latitude and longitude of the city from which the request originated. This string might look like "37.386051,-122.083851" for a request from Mountain View.
  • HTTP_X_APPENGINE_COUNTRY - Country from which the request originated, as an ISO 3166-1 alpha-2 country code. App Engine determines this code from the client's IP address.
  • HTTP_X_APPENGINE_REGION - Name of region from which the request originated. This value only makes sense in the context of the country in X-Appengine-Country. For example, if the country is "US" and the region is "ca", that "ca" means "California", not Canada.
  • USER_EMAIL - Returns the email address of the user, if they have been authenticated using the Users API. Applications should use nickname for displayable names.
  • USER_ID - If the email address is associated with a Google account, user_id returns the unique permanent ID of the user, a str. If they have been authenticated using the Users API. This ID is always the same for the user regardless of whether the user changes her email address.
  • USER_IS_ADMIN - 1 if the logged in user is also an Administrator of the application, if they have been authenticated using the Users API. 0 otherwise.
  • USER_NICKNAME - For Google Accounts users, the nickname is either the "name" portion of the user's email address if the address is in the same domain as the application, or the user's full email address otherwise.
  • USER_ORGANIZATION - An application using the Google Accounts setting can determine if the currently signed-in user is using a personal Google Account or an account which is managed by a Google Workspace domain.

Updated PHP_SELF and SCRIPT_NAME behavior in 1.9.0

The implementation of $_SERVER['SCRIPT_NAME'] and $_SERVER['PHP_SELF'] prior to 1.9.0 differs significantly from 1.9.0 and onward. The changes were made to be consistent with the Apache implementation generally expected by PHP applications.

The following examples demonstrate the difference.

Before 1.9.0After 1.9.0

app.yaml:

- url: /.*
  script: index.php
REQUEST_URI: /
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /
      PHP_SELF: /
REQUEST_URI: /
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /index.php
PHP_SELF: /index.php
REQUEST_URI: /bar
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /bar
PHP_SELF: /bar
REQUEST_URI: /bar
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /index.php
PHP_SELF: /index.php
REQUEST_URI: /index.php/foo/bar
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /index.php/foo/bar
PHP_SELF: /index.php/foo/bar
REQUEST_URI: /index.php/foo/bar
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /index.php
PHP_SELF: /index.php/foo/bar
REQUEST_URI: /test.php/foo/bar
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /test.php/foo/bar
PHP_SELF: /test.php/foo/bar
REQUEST_URI: /test.php/foo/bar
SCRIPT_FILENAME: /path/to/index.php
SCRIPT_NAME: /index.php
PHP_SELF: /index.php

app.yaml:

- url: /.*
  script: foo/index.php
REQUEST_URI: /bar
SCRIPT_FILENAME: /path/to/foo/index.php
SCRIPT_NAME: /bar
PHP_SELF: /bar
REQUEST_URI: /bar
SCRIPT_FILENAME: /path/to/foo/index.php
SCRIPT_NAME: /foo/index.php
PHP_SELF: /foo/index.php

Directives with new initialization defaults

This table specifies directives whose initialization defaults differ from the defaults supplied with the standard PHP interpreter available from php.net. You can override these default directives by including them in a php.ini file for your application.

Directive Default Value in App Engine
detect_unicode false
session.gc_maxlifetime 600
session.cookie_secure 600
session.cookie_httponly 1
session.use_only_cookies 1
display_errors 0
display_startup_errors 0
html_errors 0
log_errors 1
file_uploads 0
upload_max_filesize 262144
max_file_uploads 0
date.timezone UTC
sendmail_path null
allow_url_fopen 1
allow_url_include 0
enable_dl 0
expose_php Off
register_globals Off
magic_quotes_gpc 0
mysqlnd.collect_statistics 0
mysql.allow_local_infile 0
mysqli.allow_local_infile 0

Disabled functions

Either for security reasons, or for compatibility with App Engine execution environment, some PHP functions have been disabled. Some of these functions can be explicitly re-enabled in the php.ini file for your application.

Permanently disabled functions

The following functions have been permanently disabled in App Engine:

  • disk_free_space()
  • disk_total_space()
  • diskfreespace()
  • escapeshellarg() and escapeshellcmd()
  • exec()
  • highlight_file()
  • lchgrp(), lchown(), link(), and symlink()
  • passthru()
  • pclose() and popen()
  • proc_close(), prog_get_status(), proc_nice(), proc_open(), and proc_terminate()
  • set_time_limit()
  • shell_exec()
  • show_source()
  • system()

App Engine does not include the pcntl extension, and thus the functions provided by pcntl are not available to PHP apps running in App Engine.

tempnam() and sys_get_temp_dir() support

App Engine apps run in a security sandbox that doesn't allow for writing to local filesystem. For this reason, App Engine's version of tempnam() returns an in-memory temp file that can be written to permanent storage solution such as Google Cloud Storage buckets later.

Here is an example on how to write to the in-memory temp file using file_put_contents() and fwrite().

<?php
$dir = sys_get_temp_dir();
$tmp = tempnam($dir, “foo”);
file_put_contents($tmp, “hello”)
$f = fopen($tmp, “a”);
fwrite($f, “ world”);
fclose($f)
echo file_get_contents($tmp);

The expected output from the example would then be:

hello world

Partially restricted functions

App Engine for PHP runtime does not support the /e pattern modifier of the preg_replace() and mb_ereg_replace() functions. See the PREG_REPLACE_EVAL documentation for the deprecation notice and an example of how to update your code to use preg_replace_callback() instead.

Functions that can be manually enabled

This list specifies the PHP function that must be manually enabled by using the google_app_engine.enable_functions directive in the php.ini file for your application.

  • gc_collect_cycles(), gc_enable(), gc_disable(), and gc_enabled()
  • getmypid()
  • getmyuid() and getmygid()
  • getrusage()
  • getmyinode()
  • get_current_user()
  • libxml_disable_entity_loader()*
  • parse_str()
  • phpinfo()
  • phpversion()
  • php_uname()
  • php_sapi_name()

You can also manually disable functions by using the disable_functions directive in the php.ini file for your application.

Functions that require billing enabled

The following functions make use of Sockets and thus are only available to billing enabled apps.

Stream support

Supported PHP I/O stream wrappers

The following PHP I/O stream wrappers are supported:

  • php://input
  • php://output
  • php://memory
  • php://temp

Stream wrappers

Many functions in PHP such as fopen() or file_get_contents() take advantage of PHP's streams interface to support different protocols.

The following is a list of built-in stream wrappers that are automatically registered and available in the App Engine runtime.

The following is a list of built-in stream handlers that are not supported in App Engine and have been unregistered.

  • data://
  • expect://
  • ogg://
  • phar://
  • rar://
  • ssh2://

Disabled stream transports

The following stream transports have been disabled.

  • ssl
  • sslv2
  • sslv3
  • tcp
  • tls
  • udg
  • udp
  • unix

Pure PHP

All code for the PHP runtime environment must be pure PHP. App Engine does not allow you to upload your own C extensions.

The environment includes the PHP standard library. Some extensions have been disabled because their core functions are not supported by App Engine, such as networking and writing to the filesystem.

You can include other pure PHP libraries with your application by putting the code in your application's directory, which is the same directory that contains your app.yaml file.

For example, you can create a symbolic link in your application's directory that points to a library's directory. That link is then followed and that library gets included in your application when you deploy to App Engine.

You can also include PHP libraries by specifying php.ini directives and including PHP include statements in your code. However, the preferred alternative is to use a PHP dependency management tool such as Composer.

Examples:

  • If you include your application's root directory in the include_path directive of your php.ini file:

    include_path=".:/[ROOT_DIR]/myapp"
    

    You can then use the include or include_once statements to include PHP files relative to your include_path:

    include_once 'myfile.php';
    
  • If you choose to use Composer to include your pure PHP libraries, you can simply include a single file after your dependencies are installed:

    require_once 'vendor/autoload.php';
    

    When you use Composer to install your application's dependencies, all of the packages are added within your application's directory under vendor, which is also where the autoload.php file gets generated.

Tools

The SDK for App Engine includes tools for testing your application and uploading application files.

The development server runs your application on your local computer for testing your application.

The gcloud tool handles all command-line interaction with your application running on App Engine. You use gcloud app deploy to upload your application to App Engine, or to update individual configuration files. You can also view your app's log data, so you can analyze your app's performance using your own tools.

PHP interpreter source code

You can download the source code for App Engine's PHP interpreter the appengine-php repository in GitHub.

Concurrency and latency

Your application's latency has the biggest impact on the number of instances needed to serve your traffic. If you process requests quickly, a single instance can handle a lot of requests.

Environment variables

The following environment variables are set by the runtime:

Environment variable Description
GAE_APPLICATION The ID of your App Engine application. This ID is prefixed with 'region code~' such as 'e~' for applications deployed in Europe.
GAE_DEPLOYMENT_ID The ID of the current deployment.
GAE_ENV The App Engine environment. Set to standard.
GAE_INSTANCE The ID of the instance on which your service is currently running.
GAE_RUNTIME The runtime specified in your app.yaml file.
GAE_SERVICE The service name specified in your app.yaml file. If no service name is specified, it is set to default.
GAE_VERSION The current version label of your service.
GOOGLE_CLOUD_PROJECT The Google Cloud project ID associated with your application.
PORT The port that receives HTTP requests.

You can define additional environment variables in your app.yaml file, but the above values cannot be overridden.