简体   繁体   English

为什么我的php重定向不起作用?

[英]why doesn't my php redirect work?

Im writing a login script. 我正在写一个登录脚本。 My db.php doesnt echo/print anything so why doesnt header("Location: index.php"); 我的db.php没有回显/打印任何内容,所以为什么没有header(“ Location:index.php”); redirect upon successful login? 成功登录后重定向? the login info is correct. 登录信息正确。 I know i need to sanitize the input but that is not a problem at the moment. 我知道我需要清理输入内容,但目前这不是问题。

 <?php
        require('db.php');
        $username = $_POST['un'];
        $password = $_POST['pw'];
        $qry="SELECT uid FROM users WHERE name='$username' AND pass='".md5($password)."'";
        $result=mysql_query($qry);
        if(mysql_num_rows($result) == 1){
            session_regenerate_id();
            $user = mysql_fetch_assoc($result);
            $_SESSION['S_UID'] = $user['uid'];
            session_write_close();
            header("Location: index.php");
            exit();
        }else{
            echo "<center><form action='index.php' name='login'>Login failed! Please try again with correct username and password.<br><input type='submit' name='failed' value='Return to Login'></form></center>";
            exit();
        }
    ?>

the function header will only work if no output has been sent by the script before the function is called. 仅在调用函数之前脚本未发送任何输出的情况下,函数头才起作用。 Check if any codes above has echoed something. 检查上面的代码是否回显了某些内容。

If not, check that the include files above do not have an extra space or newline after the closing "?>" tag. 如果不是,请检查上面的包含文件,在结束的“?>”标记后没有多余的空格或换行符。 Otherwise this space or newline will be sent to the browser before your header. 否则,该空格或换行符将在标题之前发送到浏览器。

Are you sure no output is being produced anywhere in the script (or db.php)? 您确定脚本(或db.php)中的任何地方都没有产生输出吗? Not even a few extraneous spaces ? 甚至没有几个多余的空间?

Try using the full URL for example: 尝试使用完整的URL,例如:

header("Location: http://www.mysite.com/index.php");

Some browsers (thanks IE) doesn't understand the 301 redirect code with uncompleted URI. 某些浏览器(感谢IE)无法理解URI未完成的301重定向代码。

This header location behavior in PHP is a good tool, but easy to be implemented in the incorrect scenario...for this purpose i would consider using require() instead of header(location) PHP中的标头定位行为是一个很好的工具,但是很容易在不正确的情况下实现...为此,我将考虑使用require()代替header(location)

like: 喜欢:

if (!imLoggedIn()){
  require('loginForm.php');
  exit;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM