Domanda

I'm developing a php application and i have a problem retaining session values. I have two files, one is a sidebar (sidebar.php) and a home page (home.php). I have included the sidebar on the home page. There are login controls on the sidebar and i can successfully login. I know it has successfully logged in because it shows me a message Welcome 'username'. But when i go to the home page, the welcome 'username' part is not shown as the session values are destroyed. instead the login form is shown. Why is that?

This is the home page (sidebar.php)

<?php require_once('connections.php'); ?>
<?php
// if the login button is clicked
if (isset($_POST['btnLogin']))
{


$myusername=$_POST['textusername'];
$mypassword=$_POST['textpassword'];

$result=mysql_query("SELECT * FROM users_table WHERE username='$myusername' and password='$mypassword'");

$count=mysql_num_rows($result);

if($count>=1)
{

$_SESSION['username'] = $row["username"] ;
$_SESSION['userid']= $row["ID"];

}
else 
{ 

//Any code here

}

}
?>

<div class="col-md-12 right-aside">  

<?php


if (isset($_SESSION['userid']))
{
echo Welcome : " .  $_SESSION['username'];
echo "  <a href='logout.php'> | Logout</a>";
}

else //if session is not set
{

echo 'Some html for login form';

}

?>
</div> 

The following is the home page (home.php)

<?php include("head.php"); ?> 
<body>
<div class="container container-body">
        <div class="row">
          <div class="col-md-9 main-content">
             <div class="row">                               

               <p>Some Text Here</p>

             </div><!-- /.row -->
          </div><!-- /.main-content -->
        <div class="col-md-3">

  <div class="row">
      <?php include 'sidebar.php';?>      
  </div>

 </div>

È stato utile?

Soluzione

Are you starting a session in home.php? You must call session_start() at the first line of every php script in which you want to access session variables.

Try adding this in top of home.

<?php
session_start();
//Then do your work

Then even if session_start is called again in head.php or sidebar.php , it will be ignored, as the session was already started.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top