简体   繁体   中英

How I can redirect to page in php?

I try to make a login form for my active page. The registration also completed. My problem is, that when I was get that I logged in successfully, I cannot to redirect to startpage with 'header(location:)'. Please help me, or fix the php's errors. Thanks!

Note: the links of the php are samples, aren't real.

<?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)

?>

Sometimes I just put the '/' relative path in the header:

header ('Location: /');

However, this is the recommended:

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

Doing only this won't work: header ('Location: '); , as can be seen in the specifications:

Note: HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

Also, few notes:

  • Do NOT store passwords in plain text . Even thought this note won't fix your code, it's very important.

  • Include some error inside every die('') . As they stand, they only kill the script without providing any useful information. It could perfectly be that one of them is being triggered. For example:

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

  • Don't use mysql_* functions for new code since they are deprecated, PDO or mysqli_* are much better.

You can do a redirection using Javascript instead of PHP page,especially because some webhosts don't allow using header() in the middle of files.

here is an example :

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

         </script>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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