Google App Engine and PHP: Getting Started

Share this article

It’s been a while since Google announced PHP support on Google App Engine. This article series will take you through all the necessary steps in getting your app up and running on GAE.

For this tutorial, we’ll be using PhpStorm which supports GAE projects out of the box, but you can use any IDE of your choice.

Start by respecting the prerequisites for your platform. This is necessary because the Google App Engine SDK requires certain software to be runnable locally, namely Python which runs the “server”.

If your PhpStorm instance doesn’t have the GAE plugin for some reason, go into Preferences and find it in the plugin browser – it’s available for download and installation via the plugin repositories.

Registering an app on GAE

To develop an app for GAE, you first need to register it and retrieve an application ID. Go to https://appengine.google.com/ and log in with your Google account. Once done, click the “Create Application” button in the dashboard and enter the required information into the form.

Starting a project

To start a new GAE PHP project, simply select it from the drop down menu and fill in the required data.

Once you accept, the IDE will automatically create two files: app.yaml and main.php. If you’re not using PhpStorm, you can create these yourself.

app.yaml:

application: sitepoint-test
version: 1
runtime: php
api_version: 1
threadsafe: true

handlers:
- url: .*
  script: main.php

main.php:

<?php

echo 'Hello, world!';

Let’s explain the non self-explanatory YAML attributes.

threadsafe refers to PHP’s thread safety, a highly disputed issue with most people being skeptical of it and still doubting that PHP actually properly supports threads. For more information, read these two StackOverflow questions.

This value seems to be optional but I generally tend to trust Google and Jetbrains to know what they’re doing and seeing as there is no proper documentation on said property, let’s leave it in.

handlers is a set of values that defines which script handles which URL pattern. URL patterns are regular expressions, and this part of the YAML file can be used to define routes.

At this point, you can optionally enter the Project Settings in PhpStorm, and under Google App Engine for PHP you can enter your Google Account username and password, so that you don’t get prompted for them when deploying.

Testing the application

We have two ways of testing our “application”.

Please note that you HAVE to run the first way at least once before you try the second one, because the first one asks you a question about updating Python which PHPStorm doesn’t currently forward. So if you find your PHPStorm version not working, try to run it via terminal first, say “yes”, then shut it down, and try with PHPStorm again. Thanks to Dave Wyers for this tip.

  1. Running from the terminal
  2. Running from PhpStorm

Running the app from the terminal

To run the server from the terminal, enter the following:

{google_appengine folder}/dev_appserver.py {project folder}

or, in my case specifically when I replace the braced values with real ones:

google_appengine/dev_appserver.py gae01/

This runs the application server and points it at the folder provided as the first parameter. Two things happen when you do this: an administration console is run at http://localhost:8000 and the app itself is run at http://localhost:8080. If you visit the admin console, you’ll see a plethora of useful information from memcache contents to cronjobs and more:

Pointing it at http://localhost:8080 will show “Hello World” in the browser.

Note that if you get a The path specified with the --php_executable_path flag () does not exist. error when running the app, this means the app server doesn’t know where php-cgi is, and thus cannot run it. Simply add it to the execution line:

google_appengine/dev_appserver.py --php_executable_path=/usr/bin/php-cgi gae01/

Finding out where your php-cgi is is easy – type whereis php-cgi and if it’s in your $PATH variable, its location will be shown in the terminal.

Running the app from PhpStorm

To run it from PhpStorm, click the “Edit Configurations” option in the “Select Run/Debug Configuration” menu:

Most of the information in the dialog that pops up will already be populated. The only missing value will be the “Path to php-cgi executable” which you can find out by typing whereis php-cgi into your terminal. On Linux, mine was at /usr/bin/php-cgi.

After hitting Apply and OK, click the green arrow next to the “Select Run/Debug Configuration” menu, or just press Shift + F10 as a shortcut to the “Run default” command. The PhpStorm console should output the information about the server it just ran and http://localhost:8000 and http://localhost:8080 should now both be accessible, with the latter producing a “Hello World” output when visited in the browser.

Running through PhpStorm has the additional advantage of being able to set breakpoints and do step by step debugging. Just click near a line number in your code (in the gutter of the editor window) and a red ball should appear. That’s a breakpoint. When running your app, the server will pause as soon as it reaches this point, allowing you to inspect currently defined variables, memory consumption, and more.

Deployment

There are three ways to deploy our application to GAE:

1) Through the terminal/command line 2) Through PhpStorm 3) Through Git

Deployment through terminal

Uploading the app through terminal is as simple as calling {google_appengine}/appcfg.py update {project folder} or in my particular case google_appengine/appcfg.py gae01/.

Deployment through PhpStorm

To deploy from PhpStorm, go to Tools -> Google App Engine for PHP -> Upload App Engine PHP app…

If you’ve entered your credentials in the Project Settings, the process will proceed automatically without any questions. Otherwise, you’ll be prompted to enter your username and password, and the plugin will then call the same command you call manually when deploying through terminal.

Deployment through Git (Push-to-Deploy)

Push-to-deploy is still in an experimental state right now, but it’s well worth your time and effort to master it.

To set up PTD, you need to enter the cloud console and find your app there.

Click on your app’s name, scroll to “Cloud Development” in the left menu, and click on “Create a New Repo”.

Save the repo URL and click “Get Password”. This should produce a string not unlike machine code.google.com login {user} password {pass} with {user} and {pass} replaced with your own data. Copy this string into a file called .netrc which you should create in your home folder. If you’re on Windows, it should be called _netrc. Windows also needs to have the HOME variable defined, which you can do by calling setx HOME %USERPROFILE%.

All you need to do now is link the remote url to the repo you have on your local machine (either add remote or clone directly from the repo URL the cloud console gave you before) and push it live. Since the app we created in this article already exists, let’s make a Git repo on top of it and add a remote url to it. To prevent IDE junk from being uploaded alongside our source files, add this .gitignore file to the folder.

cd gae01
git init
git add .
git commit -am 'Initial commit'
git remote add appengine REPO_URL

Replace REPO_URL with the repo url the cloud console gave you. What the last command does is it adds a remote link to the local repo that binds it to the remote repo. This link is called “appengine” – appengine is just a label, you can choose your own, but there’s not much point in using something other than the self explanatory default demonstrated here.

Whenever you make changes, use the repo as you usually would. You can even set up a Github repo on the side, and add another remote link to this local repository. This would allow you to have version control on Github if you’re used to it more than Google Code, while still deploying to GAE via PTD when you pull changes from Github and push to the appengine link.

To push the app online now, just call

git push appengine master

Note that you can have as many branches as you want, just like in any Git repo, but only pushing the master branch will actually deploy to the live environment. Also, your source code is protected from prying eyes, the repo is not public and is visible only to admins and contributors. However, should a user disable PTD and turn it on again, the repo is trashed and a new one is created – there is no way to restore the old one. Be careful about whom you give permission to.

Visiting the appropriate URL now ( your-app-id.appspot.com ) should give you the Hello World message, and clicking on the repo name in the cloud console will give you a version history list and an overview of the source code.

Conclusion

Google App Engine is an excellent way to deploy high-traffic highly scalable applications. Their free quotas allow for some 5 million views a month, easily enough for any app, and scaling past the quota once needed is only a mouse click away.

In this article we’ve covered basic deployment with and without an IDE, and explained the Push-To-Deploy mechanics. Stay tuned for more advanced topics coming soon and let us know your thoughts in the comments below!

Frequently Asked Questions (FAQs) about Google App Engine in PHP

What is Google App Engine and how does it work with PHP?

Google App Engine is a cloud computing platform for developing and hosting web applications in Google-managed data centers. It provides automatic scaling for web applications, meaning that the App Engine allocates more resources for web applications that have increased traffic and less for applications that have less traffic. When it comes to PHP, Google App Engine supports PHP 7.2, 7.3, and 7.4, allowing developers to run their PHP applications in a fully managed environment.

How can I get started with Google App Engine in PHP?

To get started with Google App Engine in PHP, you need to have a Google Cloud account. Once you have an account, you can create a new project in the Google Cloud Console. After creating a project, you can download and install the Google Cloud SDK, which includes the gcloud command-line tool that you’ll use to deploy your PHP applications to the App Engine.

What are the benefits of using Google App Engine for PHP applications?

Google App Engine provides several benefits for PHP applications. It offers a fully managed environment, meaning you don’t have to worry about server management and infrastructure. It also provides automatic scaling, which adjusts resources based on your application’s traffic. Additionally, App Engine supports popular PHP frameworks like Laravel and Symfony, and it provides seamless integration with other Google Cloud services.

How can I deploy my PHP application to Google App Engine?

To deploy your PHP application to Google App Engine, you need to create an app.yaml configuration file that specifies the runtime and the entrypoint for your application. Once you have the configuration file, you can use the gcloud command-line tool to deploy your application. The command to deploy your application is “gcloud app deploy”.

Can I use MySQL with Google App Engine in PHP?

Yes, you can use MySQL with Google App Engine in PHP. Google Cloud provides Cloud SQL, a fully-managed database service that makes it easy to set up, maintain, manage, and administer your relational databases. You can connect your PHP application to a Cloud SQL instance using the PDO_MySQL or mysqli extension.

How can I handle sessions in Google App Engine with PHP?

To handle sessions in Google App Engine with PHP, you can use PHP’s native session handling functions. However, since App Engine does not support sticky sessions, you need to configure your PHP application to store session data in a shared storage system like Datastore or Memcache.

How can I debug my PHP application in Google App Engine?

Google Cloud provides Cloud Debugger, a feature that lets you inspect the state of your PHP application at any code location without stopping or slowing down your applications. You can use Cloud Debugger to capture the application state and variables, and view them in the Google Cloud Console.

How can I monitor my PHP application in Google App Engine?

Google Cloud provides Cloud Monitoring, a feature that lets you understand your application’s performance, troubleshoot issues, and optimize costs. You can use Cloud Monitoring to create dashboards, set up alerts, and view metrics about your PHP application.

How can I secure my PHP application in Google App Engine?

Google App Engine provides several features to help you secure your PHP application. It provides Identity-Aware Proxy (IAP), which controls access to your application based on identity and context. It also provides App Engine firewall, which lets you control access to your application based on IP address and IP range.

How much does it cost to use Google App Engine for PHP applications?

The cost of using Google App Engine for PHP applications depends on the resources you use. App Engine offers a free tier, but if you exceed the resources in the free tier, you’ll be charged for the additional resources. You can use the Google Cloud Pricing Calculator to estimate your costs.

Bruno SkvorcBruno Skvorc
View Author

Bruno is a blockchain developer and technical educator at the Web3 Foundation, the foundation that's building the next generation of the free people's internet. He runs two newsletters you should subscribe to if you're interested in Web3.0: Dot Leap covers ecosystem and tech development of Web3, and NFT Review covers the evolution of the non-fungible token (digital collectibles) ecosystem inside this emerging new web. His current passion project is RMRK.app, the most advanced NFT system in the world, which allows NFTs to own other NFTs, NFTs to react to emotion, NFTs to be governed democratically, and NFTs to be multiple things at once.

Cloudcloud developmentGAEgitGoogle App EnginePHP
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week