Sitemap

Google cloud function with PHP (first time)

Duckdev84
3 min readSep 12, 2021

Google cloud function with PHP (first time)

First time to see elephant code.

I would provide a simple function on the cloud, but I don’t want to initiate a full PHP web service, and then looking for something to solve this. mostly cloud service they are not friendly for PHP might it necessary rely on server software or engine, to execution. Until I found google cloud function to solve my requirement.

I skip Google Cloud Platform registration and then on your Google Cloud console can type “cloud function” in the search field, and then on the Cloud Function page must be enabled Api to open this feature service and then install the Cloud SDK on your laptop for “gcloud” cli ready to used if your already have just make sure with cmd.

gcloud components update

After then would login to allow access with command line. Don’t forget create a project to get project id and then set current project.

gcloud auth login
......
# after that
gcloud config set project PROJECT_ID

Create an index.php file and write a simple PHP code for response a parameter.

<?php

use Psr\Http\Message\ServerRequestInterface;

function helloHttp1(ServerRequestInterface $request): string
{
$name = 'World';
$body = $request->getBody()->getContents();
if (!empty($body)) {
$json = json_decode($body, true);
if (json_last_error() != JSON_ERROR_NONE) {
throw new RuntimeException(sprintf(
'Could not parse body: %s',
json_last_error_msg()
));
}
$name = $json['name'] ?? $name;
}
$queryString = $request->getQueryParams();
$name = $queryString['name'] ?? $name;

return json_encode([
'data' => sprintf('Hello, %s!', htmlspecialchars($name))
]);
}

Created composer.json file.

{
"require": {
"google/cloud-functions-framework": "^0.8"
},
"scripts": {
"start": [
"Composer\\Config::disableProcessTimeout",
"FUNCTION_TARGET=helloHttp1 php -S localhost:${PORT:-8080} vendor/bin/router.php"
]
}
}

After that run composer install.

composer install

This’s finished coding step try run your code.

php -S localhost:8080 vendor/bin/router.php

If everything finds let’s go deploying.

gcloud functions deploy helloHttp1 --runtime php74 --trigger-http --allow-unauthenticate

If you have an error like me, we will solve this in next article.

deploy error

Error log on GCP.

logs error

The error above is because I don’t create and allow a service account (xxxx@cloudbuild.gserviceaccount.com), you can go to IAM & Admin and create an account and add role, might owner role for the first time, and running deploy command again, then completed the function is active on Cloud Function service, see below.

click detail to see link url.

--

--

No responses yet