我正在使用require函数,如下所示:
<?php
require("../require/head.php");
require("../require/header.php");
require("content.php");
require("../require/footer.php");
?>
如果有任何需求找不到目标,是否有可能抛出503代码?
也有可能在我不想503错误的地方抛出普通异常,怎么办?
最佳答案
因为HTTP服务器响应代码是在 header 中发送的,所以您必须在将任何有效负载发送到客户端之前确定此代码。
因此,您可以使用输出缓冲,也可以首先循环遍历所需文件以检查其可读性,然后在缺少一个资源的情况下使用 http_response_code
发送503。
<?php
$files = [
"../require/head.php",
"../require/header.php",
"content.php",
"../require/footer.php",
];
foreach ($files as $file) {
if (!is_readable($file)) {
// return 503
http_response_code(503);
die();
// or you could throw an exception
throw new Exception("Missing file: $file");
}
}
foreach ($files as $file) {
require $file;
}
关于php - PHP要求抛出503状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43747986/