簡體   English   中英

PHP中的會話不起作用

[英]Sessions In PHP not working

好的,所以我讓用戶登錄,然后“如果成功”,我將他們重定向到index.php,我想從數據庫中顯示一些信息。

我的用戶已經過驗證並且可以登錄,但是我認為我的會話存在問題。

當我在index.php頁面上調用用戶名會話時,它不顯示任何信息。

我是php的新手,正在學習。 最近兩天,我一直在瀏覽本網站以查找問題的答案,但找不到任何有效的方法。

這是代碼

checklogin.php

<?php

    session_start();
    ob_start();
    include_once 'config.php';

    // Connect to server and select databse.
    try
    {
        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        $db = new PDO('mysql:host='.$host.';dbname='.$db_name.';charset=utf8', $username, $password);
    }
    catch(Exception $e)
    {
        die('Error : ' . $e->getMessage());
    }   

    // Define $myusername and $mypassword 
    $myusername = $_POST['myusername']; 
    $mypassword = $_POST['mypassword']; 

    // To protect MySQL injection
    $myusername = stripslashes($myusername);
    $mypassword = stripslashes($mypassword);

    $stmt = $db->query("SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'");

    // rowCount() is counting table row
    $count = $stmt->rowCount();

    // If result matched $myusername and $mypassword, table row must be 1 row
    if($count == 1){

        // Register $myusername, $mypassword and print "true"
        echo "true";
        $_SESSION['username'] = 'myusername';
        $_SESSION['password'] = 'mypassword';

    }
    else {
        //return the error message
        echo "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>Wrong Username or Password</div>";
    }

    ob_end_flush();
?>

的index.php

<?php
  session_start();

  if(!isset($_SESSION['username'])){
    header("location:main_login.php");
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="css/main.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
  <div class="form-signin">
    <div class="alert alert-success">You have been <strong>successfully</strong> logged in <?php echo $_SESSION['username']; ?>.</div>
    <a href="logout.php" class="btn btn-default btn-lg btn-block">Logout</a> </div>
</div>
<!-- /container -->
</body>
</html>

我將非常感謝您提供的任何幫助或指向可以提供幫助的文章的鏈接。

謝謝

肖恩

只需更改$ _SESSION ['username'] ='myusername'; 到$ _SESSION ['username'] = $ myusername;

暫無
暫無

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

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