Google App Engine

PHP Runtime Environment

Python |Java |PHP |Go

App Engine runs your PHP web application using the PHP 5.4 interpreter in a safe "sandboxed" environment.

  1. Selecting the PHP runtime
  2. Requests and domains
  3. Requests
  4. Request headers
  5. Responses
  6. The request timer
  7. The sandbox
  8. Automatic class loading
  9. Enabled extensions
  10. Sessions
  11. Special $_SERVER keys
  12. Directives with new initialization defaults
  13. Disabled functions
  14. Stream support
  15. Pure PHP
  16. App caching
  17. Logging
  18. Quotas and limits
  19. SPDY
  20. PHP interpreter source code

See the PHP Getting Started Guide for an introduction to developing web applications with PHP and Google App Engine.

Selecting the PHP runtime

App Engine knows to use the PHP runtime environment for your application code when you use the tool named appcfg.py from the PHP SDK with a configuration file named app.yaml.

You specify the runtime element in app.yaml:

runtime: php
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 the App Engine team ever needs to release changes to the environment that may not be compatible with existing code, they will do so with 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 app.yaml and appcfg.py, see PHP Application Configuration, and Uploading an App.

Requests and domains

App Engine determines that an incoming request is intended for your application using the domain name of the request. A request whose domain name is http://your_app_id.appspot.com is routed to the application whose ID is your_app_id. Every application gets an appspot.com domain name for free.

appspot.com domains also support subdomains of the form subdomain-dot-your_app_id.appspot.com, where subdomain can be any string allowed in one part of a domain name (not .). Requests sent to any subdomain in this way are routed to your application.

You can set up a custom top-level domain using Google Apps. With Google Apps, you assign subdomains of your business's domain to various applications, such as Google Mail or Sites. You can also associate an App Engine application with a subdomain. For convenience, you can set up a Google Apps domain when you register your application ID, or later from the Administrator Console. See Deploying your Application on your Google Apps URL for more information.

Requests for these URLs all go to the version of your application that you have selected as the default version in the Administration Console. Each version of your application also has its own URL, so you can deploy and test a new version before making it the default version. The version-specific URL uses the version identifier from your app's configuration file in addition to the appspot.com domain name, in this pattern: http://version_id-dot-latest-dot-your_app_id.appspot.com You can also use subdomains with the version-specific URL: http://subdomain-dot-version_id-dot-latest-dot-your_app_id.appspot.com

The domain name used for the request is included in the request data passed to the application. If you want your app to respond differently depending on the domain name used to access it (such as to restrict access to certain domains, or redirect to an official domain), you can check the request data (such as the Host request header) for the domain from within the application code and respond accordingly.

Please note that in April of 2013, Google stopped issuing SSL certificates for double-wildcard domains hosted at appspot.com (i.e. *.*.appspot.com). If you rely on such URLs for HTTPS access to your application, please change any application logic to use "-dot-" instead of ".". For example, to access version "1" of application "myapp" use "https://1-dot-myapp.appspot.com" instead of "https://1.myapp.appspot.com." If you continue to use "https://1.myapp.appspot.com" the certificate will not match, which will result in an error for any User-Agent that expects the URL and certificate to match exactly.

Requests

When App Engine receives a web request for your application, it calls the handler script that corresponds to the URL, as described in the application's app.yaml configuration file.

App Engine uses multiple web servers to run your application, and automatically adjusts the number of servers it is using to handle requests reliably. A given request may be routed to any server, and it may not be the same server that handled a previous request from the same user.

The server determines which PHP handler script to run by comparing the URL of the request to the URL patterns in the app's configuration file. It then runs the script populated with the request data. The server puts the request data in environment variables and the standard input stream. The script performs actions appropriate to the request, then prepares a response and puts it on the standard output stream.

Request headers

An incoming HTTP request includes the HTTP headers sent by the client. For security purposes, some headers are sanitized or amended by intermediate proxies before they reach the application.

The following headers are removed from the request:

  • Accept-Encoding
  • Connection
  • Keep-Alive
  • Proxy-Authorization
  • TE
  • Trailer
  • Transfer-Encoding

In addition, the header Strict-Transport-Security is removed from requests served to any domains other than appspot.com or *.appspot.com.

These headers relate to the transfer of the HTTP data between the client and server, and are transparent to the application. For example, the server may automatically send a gzipped response, depending on the value of the Accept-Encoding request header. The application itself does not need to know which content encodings the client can accept.

As a service to the app, App Engine adds some headers:

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

Responses

App Engine calls the script with the $_REQUEST array populated, buffers any output from the script, and when the script completes execution, sends the buffered output to the end user.

App Engine does not support sending data to the client, performing more calculations in the application, then sending more data. In other words, App Engine does not support "streaming" data in response to a single request.

Dynamic responses are limited to 32MB. If a script handler generates a response larger than this limit, the server sends back an empty response with a 500 Internal Server Error status code. This limitation does not apply to responses that serve data from Google Cloud Storage.

If the client sends HTTP headers with the request indicating that the client can accept compressed (gzipped) content, App Engine compresses the response data automatically and attaches the appropriate response headers. It uses both the Accept-Encoding and User-Agent request headers to determine if the client can reliably receive compressed responses. Custom clients can indicate that they are able to receive compressed responses by specifying both Accept-Encoding and User-Agent headers with a value of gzip. The Content-Type of the response is also used to determine whether compression is appropriate; in general, text-based content types are compressed, whereas binary content types are not.

The following headers are ignored and removed from the response:

  • Connection
  • Content-Encoding
  • Content-Length
  • Date
  • Keep-Alive
  • Proxy-Authenticate
  • Server
  • Trailer
  • Transfer-Encoding
  • Upgrade

In addition, the header Strict-Transport-Security is removed from responses served from any domains other than *.appspot.com.

Headers with non-ASCII characters in either the name or value are also removed. In addition, the following headers are added or replaced in the response:

Cache-Control, Expires and Vary

These headers specify caching policy to intermediate web proxies (such as Internet Service Providers) and browsers. If your script sets these headers, they will usually be unmodified, unless the response has a Set-Cookie header, or is generated for a user who is signed in using an administrator account. Static handlers will set these headers as directed by the configuration file. If you do not specify a Cache-Control, the server may set it to private, and add a Vary: Accept-Encoding header.

If you have a Set-Cookie response header, the Cache-Control header will be set to private (if it is not already more restrictive) and the Expires header will be set to the current date (if it is not already in the past). Generally, this will allow browsers to cache the response, but not intermediate proxy servers. This is for security reasons, since if the response was cached publicly, another user could subsequently request the same resource, and retrieve the first user's cookie.

Content-Encoding
Depending upon the request headers and response Content-Type, the server may automatically compress the response body, as described above. In this case, it adds a Content-Encoding: gzip header to indicate that the body is compressed.
Content-Length or Transfer-Encoding
The server always ignores the Content-Length header returned by the application. It will either set Content-Length to the length of the body (after compression, if compression is applied), or delete Content-Length, and use chunked transfer encoding (adding a Transfer-Encoding: chunked header).
Content-Type

If not specified by the application, the server will set a default Content-Type: text/html header.

Date
Set to the current date and time.
Server
Set to Google Frontend. The development server sets this to Development/x, where x is the version number.

If you access your site while signed in using an administrator account, App Engine includes per-request statistics in the response headers:

X-AppEngine-Estimated-CPM-US-Dollars
An estimate of what 1,000 requests similar to this request would cost in US dollars.
X-AppEngine-Resource-Usage
The resources used by the request, including server-side time as a number of milliseconds.

Responses with resource usage statistics will be made uncacheable.

The request timer

A PHP script has a limited amount of time to generate and return a response to a request, typically around 60 seconds. Once the deadline has been reached, the TIMEOUT bit on the connection status bitfield is set. Your script will then have a short second deadline to clean up any long running tasks and return a response to the user.

function check_conn_timeout() {
  $status = connection_status();
  if (($status & CONNECTION_TIMEOUT) == CONNECTION_TIMEOUT) {
    echo 'Got timeout';
  }
}

while(1) { 
  check_conn_timeout();
  sleep(1);
}

If your script hasn't returned a response by the second deadline, the handler is terminated and a default error response is returned.

While a request can take as long as 60 seconds to respond, App Engine is optimized for applications with short-lived requests, typically those that take a few hundred milliseconds. An efficient app responds quickly for the majority of requests. An app that doesn't will not scale well with App Engine's infrastructure.

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) [http://php.net/spl] classes and any classes that are part of the PHP 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 App Engine PHP SDK 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
  • filter
  • FTP
  • gd
  • hash
  • iconv
  • json
  • libxml
  • mbstring
  • mcrypt
  • memcache
  • memcached
  • mysql
  • mysqli
  • mysqlnd
  • OAuth
  • openssl
  • pcre
  • PDO
  • pdo_mysql
  • Reflection
  • session
  • shmop
  • SimpleXML
  • soap
  • SPL
  • standard
  • tokenizer
  • xml
  • xmlreader
  • xmlwriter
  • Zip
  • zlib

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 may be flushed periodically, meaning any session information will be lost. For longer-lived sessions, it may 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 Apps 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.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. If you use OpenID, you should not rely on this email address to be correct. 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 Adminstrator 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. For OpenID users, the nickname is the OpenID identifier.
  • 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 Apps domain.

Directives with new initialization defaults

This table specifies directives whose initialization defaults differ from the defaults supplied with the standard PHP 5.4 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 Google 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 Google 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 Google 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()
  • tempnam()

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

Partially restricted functions

The Google App Engine for PHP runtime does not support the /e pattern modifier of the preg_replace() and mg_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 may 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.

Stream support

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 Google App Engine and have have been unregistered.

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

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 5.4 standard library. Some modules have been disabled because their core functions are not supported by App Engine, such as networking or writing to the filesystem.

You can include other pure PHP libraries with your application by putting the code in your application directory. If you make a symbolic link to a module's directory in your application directory, appcfg.py will follow the link and include the module in your app.

The PHP module include path includes your application's root directory (the directory containing the app.yaml file). Modules you create in your application's root directory are available using a path from the root.

App caching

The PHP runtime environment includes the Alternative PHP Cache (APC) which can cache PHP intermediate code and significantly improve your application's response time. You can disable APC opcode caching by setting apc.enabled = "0" in the application's php.ini file.

Logging

The App Engine web server captures everything the handler script writes to the standard output stream for the response to the web request. It also captures everything the handler script writes to the standard error stream, and stores it as log data. Log data for your application can be viewed and analyzed using the Administration Console, or downloaded using appcfg.py request_logs.

The App Engine PHP runtime environment includes support for logging arbitrary messages from your application using PHP's built-in syslog() function, which invokes the Logs PHP Api.

if (authorized_user()) {
  // Some code
} else {
  syslog(LOG_WARNING, 'Unauthorized access');
}

Quotas and limits

Google App Engine automatically allocates resources to your application as traffic increases. However, this is bound by the following restrictions:

  • App Engine reserves automatic scaling capacity for applications with low latency, where the application responds to requests in less than one second. Applications with very high latency (over one second per request for many requests) and high throughput require Silver, Gold, or Platinum support. Customers with this level of support can request higher throughput limits by contacting their support representative.
  • Applications that are heavily CPU-bound may also incur some additional latency in order to efficiently share resources with other applications on the same servers. Requests for static files are exempt from these latency limits.

Each incoming request to the application counts toward the Requests limit. Data sent in response to a request counts toward the Outgoing Bandwidth (billable) limit.

Both HTTP and HTTPS (secure) requests count toward the Requests, Incoming Bandwidth (billable), and Outgoing Bandwidth (billable) limits. The Quota Details page of the Admin Console also reports Secure Requests, Secure Incoming Bandwidth, and Secure Outgoing Bandwidth as separate values for informational purposes. Only HTTPS requests count toward these values. See the Quotas page, and the "Quota Details" section of the Admin Console for more information.

In addition to system-wide safety limits, the following limits apply specifically to the use of request handlers:

Limit Amount
request size 32 megabytes
response size 32 megabytes
request duration 60 seconds
maximum total number of files (app files and static files) 10,000 total
1,000 per directory
maximum size of an application file 32 megabytes
maximum size of a static file 32 megabytes
maximum total size of all application and static files first 1 gigabyte is free
$ 0.026 per gigabyte per month after first 1 gigabyte

SPDY

App Engine applications will automatically use the SPDY protocol when accessed over SSL by a browser that supports SPDY. This is a replacement for HTTP designed by Google and intended to reduce the latency of web page downloads. The use of SPDY should be entirely transparent to both applications and users (applications can be written as if normal HTTP was being used). For more information, see the SPDY project page.

PHP interpreter source code

You can download the source code for App Engine's PHP interpreter here at this GitHub repository: https://github.com/GoogleCloudPlatform/appengine-php

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.