首页 > 解决方案 > 如何通过 PHP 执行 Google Cloud Function?

问题描述

是否可以执行谷歌云函数并通过 PHP 等待它的结果?

我在以下位置搜索了文档:

但是没有一个集成了 Cloud Functions。

标签: phpfirebasegoogle-cloud-platformgoogle-cloud-functions

解决方案


您可以创建一个 HTTP 触发的云函数。有关更多信息,请转到HTTP 触发器文档。然后使用函数的触发 URL 向您的 PHP 代码发出 http 请求。要查看它,请转到Cloud FunctionsGoogle Cloud Console 中的页面。单击您的云函数的名称,Function details页面将打开。转到Trigger选项卡,URL您可以在下面看到执行云功能的链接。

执行此操作的 PHP 示例如下(它是众多示例之一,这对我有用): 运行sudo apt-get install php-curl以安装 php curl

使用以下 PHP 代码:

<?php
global $url;

//The Cloud Function's trigger URL
$url = "www.[FUNCTION_ZONE]-[PROJECT_ID].cloudfunctions.net/[FUNCTION_NAME]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Get the response and close the channel.
$response = curl_exec($ch);
echo "Printing response: \n\n";
echo $response;
curl_close($ch);

推荐阅读