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

时间:2018-08-14 17:14:22

标签: php redirect die

我正在尝试将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 . ')=(?:([\'"])([^\2]+?)\2|([^\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;
}
?>

3 个答案:

答案 0 :(得分:3)

您可以这样做

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

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

答案 1 :(得分:2)

只需使用

header('Location: tryagain.php');

在您的if语句中,然后致电die

引用this answer

  

如果您没有在标题('位置:http://something')之后放置die()或exit(),则脚本可能会继续导致意外行为。例如,这可能会导致泄露您实际上想要通过重定向(HTTP 301)阻止的内容。最终用户可能无法直接看到上述内容,因为浏览器可能无法呈现(由于301)。结论,exit()和die()函数阻止脚本继续运行。

答案 2 :(得分:1)

PHP提供了一种预定义的方法 header('Location: tryagain.php'); 只需用上面的语句替换die语句即可。 您无需使用die,因为您是有条件的,因此如果用户插入了错误的详细信息,则可以轻松地将用户重定向到try.php 您可以在Google上对其进行更多研究