php - PHP要求抛出503状态码

标签 php html error-handling require

我正在使用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/

相关文章:

PHP CMS 教程,写出 html 文件

html - 如何在@media 和跨浏览器中水平居中 div 类?

html - 单击带有 <href> 和 <a> 标签的按钮

php - 插入 PHP 代码时整个页面都向左移动?

php - 点击时如何查询MYSQL?

.net - 需要异常号而不是消息字符串

ruby-on-rails - Ruby 通用捕获所有错误

jquery - jQuery ajax错误处理程序函数存在,但仍引发异常

php - 如何重定向来自 Google 搜索的用户,而不是同一页面的 Google 抓取工具?

html - Bootstrap 表格单元格中的垂直居中复选框