简体   繁体   中英

php sessions are not being saved

I apologize for the wall of text but I've been banging my head against the wall around this problem for awhile so I'm gonna try to provide as much information as possible. I'm not quite sure if the problem I'm getting has to do with user sessions (I'm new to PHP), but that's what it seems to me.

I ask a user to enter his login information (id and password) to enter the system in ask_login.php :

<div class="login_box">
        <h1>Login</h1>
        <form method="POST" action="login.php">
        <p><input type="text" name="username" placeholder="UserID"></p>
        <p><input type="password" name="password" placeholder="Password"></p>
        <input type="submit" name="submit" value="Login"></p>
        </form>
</div>

If the login details (id and password) are found in the database the user gets logged in to his user portal (login.php) where he can check his details, exams dates, etc.. My problem is whenever I login, if I click for example on the details button to check the user details, it redirects me to my ask_login.php page asking for my login details again saying that I didn't enter any ID/Password details. I've tried removing the code where it checks if the login forms were submitted blank, and it eventually started working and I was able to click the 'Details' button or any other button, without getting redirected to ask_login.php. But now when I click on the 'Details' button my "Welcome, username" line doesn't show the username, which makes me think that it has something to do with php sessions. Furthermore, any query that I make won't show the result.

Here's my login.php code:

<?php
session_start();


$username = $_POST['username'];
$password = $_POST['password'];

if($username && $password) {
  $conn_error = 'Could not connect.';
  $mysql_db = '------';
  if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
  die($conn_error);
}
  $query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");

    $numrows = mysql_num_rows($query);

      if($numrows!== 0) 
      {
          while($row = mysql_fetch_assoc($query))
          {
            $dbusername = $row['id'];
            $dbpassword = $row['password'];
          }

          if($username==$dbusername && $password==$dbpassword) {
            //echo "You are logged in!";
            @$_SESSION['id'] = $username;
          }
          else {
            echo "<script>alert('Username/Password are incorrect');</script>";
            echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
            die();
            //die("Wrong username/password!");
          }
      }
        else {
            echo "<script>alert('User doesn't exist.');</script>";
            echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
            die();
           //die("That user doesn't exist!");
         }
}

    else if(empty($username) || empty($password)) {
   echo "<script>alert('You didn't enter an ID/Password');</script>";
    echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
    die();
    //die("Please enter an ID and password!");
}

?>



<!DOCTYPE HTML>

<html>
<head>
    <title>Logged in | FCUL</title>
    <link rel="stylesheet" href="css/stylesheet_loggedin.css" type="text/css"/>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <link rel="shortcut icon" href="img/vitor-20130904-favicon.ico"/>
</head>


<body>

            <div id="header">
                <br/>
                    <a href="index.php"><img src="/img/fcul_cent_logo_001.png" width="510" height="70"/></a>
            </div>


<div id="loggedinas">
<br/>

Welcome, 
<?php 
$result = mysql_query("SELECT nome FROM users WHERE id='$username'");
while($row = mysql_fetch_assoc($result)) {
    echo $row["nome"];
} 
?> 

( <?php echo $username;  ?> ) 
 <br/>


 <div id="logout">
 <a href="logout.php"><font size="2"><u>[Logout]</u></a></font></a>
</div>

<hr/>
</div>



 <?php
//FETCH USER'S BI
    if(isset($_POST['username'] )) {

    $ID = $_REQUEST['username'];

  $query = "SELECT bi FROM users WHERE id='$ID'";

      //if query is successful
    if($query_run = mysql_query($query)) {

      //if it returns 0 rows
    if(mysql_num_rows($query_run)==NULL) {
    echo "<script>alert('Unexpected Error 004');</script>";
    echo "<script language='javascript'>window.location = 'index.php';</script>";
    }

      while($query_row = mysql_fetch_assoc($query_run)) {
      $bi = $query_row['bi'];
      //echo $bi;
      }
  } 
}

?>



<br/>
<center>
<div id="buttons">

<form method="POST" action="login.php">
   <input type="submit" name="details" value="details">
    </form>

<?php
//**print user's BI if he clicks on 'Details' button**
    if($_POST['detalhes']){
    echo '<div id="content">' . $bi . '</div>';
}
?>


</div>
</center>
</body>
</html>

You are not checking if the user is already logged, so, after receiving your post from ask_login.php, when you click anything in your page $username and $userpassword will be null.

Just wrap all your code after session_start with

if($_SESSION['id'] === false)
{

    //Your code
    $username = $_POST['username'];
    $password = $_POST['password'];

    if($username &&...

}

you cannot access session on first time you insert it in $_SESSION['id'] = $username variable.
you can only access it on the second run of session_start();

try this.
1. make login.php
2. make welcome.php

try to separate the module where login.php will only process for checking the login process then if this condition success then

<?
if($username==$dbusername && $password==$dbpassword) {
    //echo "You are logged in!";
    $_SESSION['id'] = $username;
    header("location: welcome.php");
}
?>

in welcome.php

<? 
session_start();
// this is for the checking if user is loged in
if (!$_SESSION['id']) {
 header("location: ask_login.php");
 exit;
}
?>

wrap your code with this

if ($_SESSION['id']){
//your login checking here
};

eg

if ($_SESSION['id']){
if($username && $password) {
  $conn_error = 'Could not connect.';
  $mysql_db = '------';
  if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
  die($conn_error);
}
  $query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");

    $numrows = mysql_num_rows($query);

      if($numrows!== 0) 
      {
          while($row = mysql_fetch_assoc($query))
          {
            $dbusername = $row['id'];
            $dbpassword = $row['password'];
          }

          if($username==$dbusername && $password==$dbpassword) {
            //echo "You are logged in!";
            @$_SESSION['id'] = $username;
          }
          else {
            echo "<script>alert('Username/Password are incorrect');</script>";
            echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
            die();
            //die("Wrong username/password!");
          }
      }
        else {
            echo "<script>alert('User doesn't exist.');</script>";
            echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
            die();
           //die("That user doesn't exist!");
         }
}

    else if(empty($username) || empty($password)) {
   echo "<script>alert('You didn't enter an ID/Password');</script>";
    echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
    die();
    //die("Please enter an ID and password!");
}
}
?>

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