簡體   English   中英

成功登錄后頁面無法用PHP代碼重定向到新頁面

[英]After successful login page is not redirecting to new page in php code

我在php中創建登錄系統。當我填寫用戶名和密碼時,會話開始,但頁面未重定向到profile.php,登錄后我想要的是登錄頁面,而登錄頁面正在刷新自身。但是當我手動刷新login.php時,它將重定向到配置文件.ph。 我的登錄代碼是:

if ($result->num_rows != 1) {
    //echo "Invalid credentials...!";
    $message = "wrong credentials";
    echo "<script type='text/javascript'>alert('$message');</script>";
} else {
    // Authenticated, set session variables
    $user = $result->fetch_array();
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];


    $message = "You have successfully logged in..";
    echo "<script type='text/javascript'>alert('$message');</script>";

    redirect_to("profile.php?id={$_SESSION['user_id']}");

}

采用

redirect("profile.php?id={$_SESSION['user_id']}");

要么

http_redirect("profile.php", array("id" => "$_SESSION['user_id']"), true, HTTP_REDIRECT_PERM);

要么

header("profile.php?id={$_SESSION['user_id']}");

一些有用的鏈接

  1. 標頭
  2. http_redirect
  3. 如何在PHP中進行重定向?

發送后輸出PHP頭重定向不起作用 你在這里寄

$message = "You have successfully logged in..";
echo "<script type='text/javascript'>alert('$message');</script>";

根據您的評論,您的函數確實使用標頭重定向。

function redirect_to ($url) { header("Location: {$url}"); }

由於上述原因,該方法將無法正常工作。

在此處使用JavaScript重定向。

  echo "<script>location.href='profile.php?id={$_SESSION['user_id']}';</script>";

如您對問題的評論中所述,標頭重定向必須是瀏覽器要做的第一件事。 因此,您需要刪除echo語句。

if ($result->num_rows != 1) {
    //echo "Invalid credentials...!";
    $message = "wrong credentials";
    echo "<script type='text/javascript'>alert('$message');</script>";
} else {
    // Authenticated, set session variables
    $user = $result->fetch_array();
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];

    redirect_to("profile.php?id={$_SESSION['user_id']}");
}
<?php
ob_start ();
if (isset ( $_POST ['submit'] )) {

    $email = $_POST ['email'];  
    $password = $_POST ['password'];
    $sql = "SELECT * from users WHERE email='$email' AND password='$password' limit 1";
    $result = mysql_query ( $sql );
    $num = mysql_num_rows ( $result );
    if ($num > 0) {
        while ( $rows = mysql_fetch_array ( $result ) ) {

            $username = $rows ['username'];
            $uid = $rows ['user_id'];
        }
        session_start ();
        $_SESSION ['user_id'] = $user ['id'];
        $_SESSION ['username'] = $user ['username'];
        header ( "location:profile.php?id=" . $_SESSION ['user_id'] );
    } else {
        echo "<p><b>Error:</b> Invalid username/password combination</p>";
    }
}
?>

如果您正在登錄頁面本身中處理此php代碼,請提供完整的html代碼。 因為自動刷新可能是html代碼本身的問題。

請粘貼完整的代碼,否則請嘗試替換

redirect_to("profile.php?id={$_SESSION['user_id']}"); 

與下面的行..

header("location:profile.php?id=".$_SESSION['user_id']);

不要忘記在您的php代碼頂部添加以下行。

ob_start();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM