PHP需要停止主脚本

时间:2018-04-01 10:55:16

标签: php rest api

我的main.php文件需要auth.php来验证用户身份:

require 'auth.php';

但是如果身份验证失败,我想停止/退出main.php文件的执行。

目前脚本将在要求之后继续。

auth.php将退出:

http_response_code(403);
return;

在返回时停止两个脚本的任何想法?

感谢。

2 个答案:

答案 0 :(得分:0)

没有进一步的细节我会回答你的问题。

不返回任何内容,而是返回状态。

所以:

if (bad) {
    http_response_code(403);
    return false;
} else {
    return true;
}

然后在你的来电者

$auth = require 'auth.php';

if (!$auth) {
    // do something to exit out or show/build error
}

或者设置状态并且不要返回。

if (bad) {
    http_response_code(403);
    $auth = false;
} else {
    $auth = true;
}

然后在你的来电者

require 'auth.php';

if (!$auth) {
    // do something to exit out or show/build error
}

答案 1 :(得分:0)

  

在返回时停止两个脚本的任何想法?

只有原始exit,即使有消息,通常也不是最佳方法。调用视图文件以获取浏览器的任何输出通常会更好 例如,您的auth.php约为"授权",因此它负责设置标头并退出并不理想。真的应该是一个新类,或者至少是一个可以返回有用状态的函数。

当您使用类和视图模板(例如twig)时,这是理想且简单的,但可以使用过程代码和文件轻松完成,或者只是使函数更容易。

所以你可以得到一个" error.php"调用通常的输出,页眉/页脚和其他内容的文件。然后,如果在某些时候出现错误,您可以调用此文件,将错误消息传递给它,并让它显示您的网站布局/ CSS等错误消息。

main.php:

require 'auth.php';

$authError = auth_function();

if ($authError) {
    require 'error.php';
    output_error($authError);
    exit; // You could exit in the error function, but maybe one day you do not want to
}

auth.php:

function auth_function()
{
    // Do whatever

    if (403) {
        return '403';
    }
    // Can have other "elseifs" here to return other things

    return null;
}

error.php:

function output_error($error)
{
    // Include all your header/css/body/set header to 403/whatever
    echo "Sorry we found the error {$error}";
    // Include footer etc
}