Hello World from PHP on Google App Engine

Hello.
I'm Mandai, the Wild team member in charge of development.

Google App Engine (hereinafter referred to as GAE) is a powerful PaaS, but there are quite a few things you need to know before you get started in order to get going

For example, things like how to write app.yaml, what functions are available, whether a framework can be used at all, and what the URL will be.
Moreover, the development speed of the SDK and gcloud command is so fast that you might feel like giving up when you can't deploy using the command you looked up.

So, taking into account the latest GAE environment as of now (2017/03/22), I will try to deploy a Hello World-type program and get a grasp of the process

Due to space constraints, we will proceed under the assumption that the latest gcloud command is installed

 

Creating app.yaml

Create a suitable directory and create app.yaml

app.yaml is a configuration file that sets the program environment

In app.yaml, we will first enter the execution environment

# app.yaml # Required field runtime: php55

I chose PHP 5.5 as the execution environment.
Actually, it seems there are no other options besides PHP 5.5 on GAE.

 

Write the source

This time, we'll be doing Hello World, but simply saying "echo "hello world";" isn't very interesting, so we'll create a simple program that uses Google SQL

Let's create a file named form.php.
I've prepared the following source code.

<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = getenv('MYSQL_USER'); $password = getenv('MYSQL_PASSWORD'); $dsn = getenv('MYSQL_DSN'); $subject = isset($_POST['subject']) ? $_POST['subject'] : null; $content = isset($_POST['content']) ? $_POST['content'] : null; if (!empty($dsn) && !empty($username) && !empty($password) && !is_null($subject) && !is_null($content)) { $db = new PDO($dsn, $username, $password); $stmt = $db-> prepare('INSERT INTO `forms` (`subject`, `content`, `created_at`) VALUES (?, ?, ?)'); $data = array( $subject, $content, date('Ymd H:i:s'), ); if (!$stmt->execute($data)) { $info = array( 'title' => $stmt->errorCode(), 'body' => $stmt->errorInfo(), ); } else { $info = array( 'title' => 'info', 'body' => 'Successfully Signed Up!', ); } } }?><!doctype html><html><head><title> test form </title><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></head><body><div class="container"><?php if (isset($info)){?><div class="panel panel-default alert alert-info"><div class="panel-heading"><?php echo $info['title'] ?></div><div class="panel-body"><?php echo $info['body'] ?></div></div><?php } ?><form method="POST"><div class="form-group"> <label for="subject">title</label><input id="subject" type="text" class="form-control" name="subject"></div><div class="form-group"> <label for="content">Main text</label><textarea id="content" class="form-control" name="content" rows="10"></textarea></div> <button class="btn btn-default">send</button></form></div></body></html>

This is a simple registration form page using Twitter Bootstrap

The DB tables used in this program are as follows:

CREATE TABLE `forms` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `subject` varchar(255) DEFAULT NULL, `content` text, `created_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Since we'll be using Google Cloud SQL, you'll need login information for Google Cloud SQL. If you're using a user other than root, create it beforehand.
While it's perfectly fine to write this directly in the source code, we'll use the app.yaml configuration file instead.

# app.yaml # Add to the app.yaml you created earlier env_variables: MYSQL_DSN: mysql:unix_socket=/cloudsql/[instance connection name];dbname=[DB schema name to use] MYSQL_USER: [MySQL login user] MYSQL_PASSWORD: [MySQL login password] # Also add URL routing handlers: - url: /test script: form.php secure: always

The `env_variables` field allows you to register constants in a similar way to defining them.
To receive these values ​​on the PHP side, you use the `getenv()` function (they are not actually defined).

Also, I've secretly added a field called "handlers," but without it, the URL won't be recognized, so I've created a URL called "/test."
The "secure" field is related to the use of HTTPS, and the following options are available.

always

Use HTTPS only (redirects when accessed via HTTP)

optional

Accessible via both HTTP and HTTPS

never

Only HTTP accessible

 

Check the operation in a local environment

Writing source code and testing it on GAE is a hassle, and once operations begin it can be quite difficult, so a method for testing in a local environment is also provided

Running the Python script `dev_appserver.py` included in the gcloud SDK will start a local server and allow you to test its functionality, but it seems that it won't connect to Cloud SQL properly in this state.
However, by using `cloud_sql_proxy`, as described later, you can connect to the database without any further configuration.

dev_appserver.py is included in the Google Cloud SDK and is executed by specifying the path to the directory where app.yaml is located (a relative path is acceptable) as an argument

In the case of Windows, it is installed in a fairly deep directory, so one solution would be to set the path to the directory where the Google Cloud SDK executable file is located

 

Connecting to Google Cloud SQL from a local development environment using cloud_sql_proxy

While you can't connect to Cloud SQL from your local environment using the same app.yaml file as your production environment, you can easily test your Cloud SQL application from your local machine using a separate tool called cloud_sql_proxy. Here
's a brief summary of the steps.

  1. for using Google Cloud SQL, I obtained the cloud_sql_proxy file and renamed it.
  2. Go to a location that is in the path (for example, the Google Cloud SDK directory)
  3. Run gcloud auth application-default login
  4. The OAuth authentication page will be displayed in the browser, so select the logged-in user and allow them
  5. [For Windows] cloud_sql_proxy.exe -instances=[instance connection name]=tcp:3306

It's possible that the commands might change slightly if you're using multiple users (mainly the gcloud auth command), but I can't say for sure as I haven't tested it.
This tool eliminates the need to register the IP address of the connection source with Cloud SQL, so once the setup is complete, development becomes much easier.

 

Deploy

There is a gcloud command available for deploying to GAE, so run the following command in the directory where app.yaml is located

gcloud app deploy

If it has already been deployed, you will be asked to confirm, but in most cases it should be able to be deployed without any problems

Also, if there are any handlers registered in app.yaml that are not routed at this time, the following warning will be displayed

WARNING: The URL path "/hogehoge" is reserved and will not be matched.

In this case, even if you deploy it as is, the URL for running the program will not be set, so you will need to adjust it

 

View the access log

Although there is a slight time lag, the access log can be viewed from the local environment via the gcloud command

gcloud app logs tail -s default

As shown above, the accessed path and response code are displayed, allowing for simple error checking

 

View the error log

Since GAE is a PaaS, you cannot log in to the server and check the error log

Therefore, to check for errors after deployment,Stackdriver Error Reportingyou should use

The data is neatly parsed and displayed, making it easy to read, but the information is scattered all over the place, so it takes some getting used to

 

summary

The development process is a little different from usual, so I'm often confused, but I feel like I can manage if I take it one step at a time.
In particular, I found the ability to connect to Google Cloud SQL from my local machine via a proxy to be very convenient.

It's an ideal service for hosting small, handy tools, and even as your project grows, it automatically increases instances, offering many convenient features that make it suitable for a variety of uses.
Additionally, it supports memcache, creates application directories in Google Cloud Storage for easy management, and is designed to provide convenient storage for various types of data.

That's all

If you found this article helpful,please give it a "Like"!
0
Loading...
0 votes, average: 0.00 / 10
1,306
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author

Yoichi Bandai

My main job is developing web APIs for social games, but thankfully I'm also given the opportunity to work on various other tasks, including marketing.
My image rights within Beyond are treated as CC0.