是否可以使用 PHP 在 die() 上重定向?

Is it possible to redirect on die() using PHP?

我正在尝试将 die() 上的用户重定向到另一个地方。例如,如果用户点击取消,他将被重定向到 tryagain.php 或者如果他输入不正确的凭据,他将被重定向到 resetpassword.php

请指导我,以便我能实现。

我该如何实现。下面是我的代码:

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');


if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}


// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']]))
    die('Wrong Credentials!');


// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
echo 'You are logged in as: ' . $data['username'];


// function to parse the http auth header
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^]+?)|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>

PHP 有一个预定义的方法 header('Location: tryagain.php'); 只需将 die 语句替换为上述语句即可。 你不需要使用 die 因为你是有条件的所以你可以很容易地重定向你的用户尝试 again.php 如果他插入错误的细节 您可以在 Google

上对其进行更多研究

只需使用

header('Location: tryagain.php');

在您的 if 语句中,然后调用 die

引自this answer

If you don't put a die() or exit() after your header('Location: http://something') your script may continue resulting in unexpected behaviour. This may for example result in content being disclosed that you actually wanted to prevent with the redirect (HTTP 301). The aforementioned may not directly be visible for an end user as the browser may not render it (due to the 301). Conclusion, the exit() and die() functions stop the script from continuing.

你可以这样做

die("<script>window.location = 'https://www.example.com/tryagain.php';</script>");

header("Location: http://example.com/tryagain.php");
die();