【问题标题】:How I can redirect to page in php?如何重定向到 php 中的页面?
【发布时间】:2013-08-20 23:48:31
【问题描述】:

我尝试为我的活动页面制作登录表单。注册也完成了。我的问题是,当我成功登录时,我无法使用'header(location:)'重定向到起始页。请帮助我,或修复php的错误。谢谢!

注意:php的链接是示例,不是真实的。

<?php

$hostname="host"; // Host of MySQL
$user="user"; // Username at MySQL
$password="pass"; // Password at MySQL
$dbname="db"; // Database on MySQL

$connection=mysql_connect($hostname, $user, $password);
    if(! $connection)
        {
            die(''.mysqlerror());
        }
mysql_select_db($dbname, $connection) or die('');

$given_email=mysql_real_escape_string($_POST['email']);
$given_pass=mysql_real_escape_string($_POST['pass']);

$sql="SELECT * FROM users WHERE email='$given_email' and password='$given_pass'";
$result=mysql_query($sql) or die(mysql_error());
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);

if($count==1)
{    
    //echo "OK";
    header( 'Location: http://www.yoursite.com/new_page.html' ) ;
    //setUrl ("http://testseite.aufderlicht.bplaced.de/loggedin/start.html");
}
    else 
    {
        setUrl ("http://testseite.aufderlicht.bplaced.de/login/err/err.html");
    }

//mysql_close($connection)

?>

【问题讨论】:

  • 你得到什么错误而不是重定向?
  • 确保在标头调用之前没有输出,否则会报错
  • 也许您的空间在欺骗您。在header( 等之后尝试header('Location: http://www.yoursite.com/new_page.html');,不带空格。
  • 使路径相对而不是包含完整路径。即 /loggedin/start.html 和 /login/err/err.html
  • 另外,如果脚本中的 php 标记之前有空格,那么 header() 将不起作用。另外,在header() 之后添加exit()die() 以避免任何问题并停止执行脚本。

标签: php mysql sql header login-script


【解决方案1】:

有时我只是将'/'相对路径放在标题中:

header ('Location: /');

但是,这是推荐的:

header ('Location: http://example.com/');

只这样做是行不通的:header ('Location: ');,从规范中可以看出:

注意: HTTP/1.1 需要一个绝对 URI 作为 » Location 的参数:包括方案、主机名和绝对路径,但一些客户端接受相对 URI。您通常可以使用 $_SERVER['HTTP_HOST']、$_SERVER['PHP_SELF'] 和 dirname() 自己从相对的 URI 中创建绝对 URI:

另外,还有几点注意事项:

  • Do NOT store passwords in plain text。即使认为此注释不会修复您的代码,它也非常重要。

  • 在每个 die('') 中包含一些错误。按照他们的立场,他们只会杀死脚本而不提供任何有用的信息。很可能是其中一个被触发了。例如:

mysql_select_db($dbname, $connection) or die('Could not select database');

  • 不要将 mysql_* 函数用于新代码,因为它们已被弃用,PDO 或 mysqli_* 更好。

【讨论】:

    【解决方案2】:

    您可以使用 Javascript 而不是 PHP 页面进行重定向,特别是因为某些 webhosts 不允许在文件中间使用 header()。

    这是一个例子:

           echo "
             <script type='text/javascript'>
                  window.location.replace('http://www.yoursite.com/new_page.html');
    
             </script>";
    

    【讨论】:

      猜你喜欢
      • 2016-10-23
      • 2011-06-26
      • 2011-03-20
      • 2013-11-18
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      相关资源
      最近更新 更多