Hello World from PHP on Google App Engine

table of contents
Hello,
I'm Mandai, the Wild Team member of the development team.
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, how to write app.yaml, what functions can be used, whether frameworks can be used in the first place, what the URL will be, etc.
Moreover, the development speed of SDKs and gcloud commands is fast, and sometimes you can't deploy with the commands you've looked up and you feel like giving 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 PHP5.5 as the execution environment.
Actually, it seems that there is no other option than PHP5.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.
The source code is as follows:
<?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 will be using Google Cloud SQL, we will need login information for Google Cloud SQL, so if you are using a user other than root, create that user in advance.
Of course, there will be no problem if you write it directly in the source code, but since there is a configuration file called app.yaml, we will write it there.
# 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 item allows you to register constants in the same way as defining them.
To receive these values on the PHP side, use the getenv() function (they are not actually defined).
We've also secretly added a handlers item, but without it the URL won't be recognized, so we'll create a URL called /test. The
secure item is related to the use of HTTPS, and has the following options:
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
If you run the python script dev_appserver.py included in the gcloud SDK, a local server will start up and you can check that it works, but it doesn't seem to be able to connect to Cloud SQL properly.
However, if you use cloud_sql_proxy (described later), you can connect to the database without any hassle.
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
You cannot connect to Cloud SQL from a local environment using the same app.yaml as the production environment, but by using a separate tool called cloud_sql_proxy, you can easily test applications using Cloud SQL locally. Here
is a simple summary of the steps.
- Using Google Cloud SQL to get cloud_sql_proxy and rename the file name.
- Go to a location that is in the path (for example, the Google Cloud SDK directory)
- Run gcloud auth application-default login
- The OAuth authentication page will be displayed in the browser, so select the logged-in user and allow them
-
Run cloud_sql_proxy. Reference URL: https://cloud.google.com/sql/docs/mysql/sql-proxy#flags[For Windows] cloud_sql_proxy.exe -instances=[instance connection name]=tcp:3306
If you use multiple users, the commands may be slightly different (mainly the gcloud auth command), but since this has not been tested, it is difficult to say for sure.
By using this tool, you do not need to register the IP address of the connection source in 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, after deployment, to check for any errors, you can check the logs using Stackdriver Error Reporting
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 process is a little different from my usual development methods, so I often get confused, but I feel like I can get it done by taking it one step at a time. I
especially found it very easy to use, as I can connect to Google Cloud SQL locally via a proxy.
It's a great service for hosting small, handy tools, and has many convenient features, such as automatically increasing instances as the scale grows, so it seems like it can be used for a variety of purposes. It
also uses memcache, and a directory for applications is created in Google Cloud Storage, making it easy to use, so you won't have to worry about where to store various data.
That's all
0
