Created
July 18, 2020 04:37
-
-
Save TennousuAthena/9ff7a8670003daf33e3987b36662f25e to your computer and use it in GitHub Desktop.
PHP SCF Quick Start
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// main function, called by SCF | |
// 主函数,调用的入口 | |
function main_handler($event, $context) { | |
// print parameters | |
// 进门打印传入参数是好习惯 | |
echo 'event:'.json_encode($event, JSON_PRETTY_PRINT).' | |
context:'.json_encode($context, JSON_PRETTY_PRINT); | |
// echo $event->{'headers'}->{'host'} ; // parameter is object. 传入的参数是object | |
// convert parameters to array | |
// 转换为数组 | |
$event = json_decode(json_encode($event), true); | |
$context = json_decode(json_encode($context), true); | |
// good choice to clean variables | |
// SCF中使用全局的变量前最好清空 | |
unset($_GET); | |
unset($_POST); | |
// get the path in url | |
// 取得链接中非域名部分的path值 | |
$function_name = $context['function_name']; | |
$host_name = $event['headers']['host']; | |
$serviceId = $event['requestContext']['serviceId']; | |
if ( $serviceId === substr($host_name,0,strlen($serviceId)) ) { | |
// using long url of API gateway | |
// 使用API网关长链接时 | |
$path = substr($event['path'], strlen('/' . $function_name . '/')); | |
} else { | |
// using custom domain | |
// 使用自定义域名时 | |
$path = substr($event['path'], strlen($event['requestContext']['path']=='/'?'/':$event['requestContext']['path'].'/')); | |
} | |
// get the queryString | |
// 取得链接后?queryString提交的值 | |
$_GET = $event['queryString']; | |
// get the POST values | |
// 取得表格POST提交的值 | |
$_POSTbody = explode("&",$event['body']); | |
foreach ($_POSTbody as $postvalues){ | |
$pos = strpos($postvalues,"="); | |
$_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); | |
} | |
// start the web html | |
// 网页开始 | |
@ob_start(); | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>HTML</title> | |
<meta charset=utf-8> | |
<meta name="viewport" content="width=device-width,initial-scale=1"/> | |
</head> | |
<body> | |
<h1>Hello, SCF!</h1> | |
</body> | |
</html> | |
<?php | |
// end the web html | |
// 网页结束 | |
$html=ob_get_clean(); | |
// return the web html | |
// 返回html网页 | |
return [ | |
'isBase64Encoded' => false, | |
'statusCode' => 200, | |
'headers' => [ 'Content-Type' => 'text/html' ], | |
'body' => $html | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment