954,568 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

about session

I am a newbie to php, i occasionally find a problem, I open the page "index.php" on a chrome browser, then I left for lunch, then I come back and click the link in page "index.php", it did head to "login.php", but laterly I find a record in my database. the username is null, in another words, the green colored code in main.php is executed somehow. I guess it's because the session have been expired when i came back, but why the session check did not work properly?

the code like this
the index.php

<?php
    session_start();
    if($_SESSION['username']=='')header("Location: login.php");
    
    echo "<a href='main.php'>home</a>"
?>



the main.php

<?php
   session_start();
   if($_SESSION['username']=='')header("Location: login.php");
   $username=$_SESSION['username'];
   $sql="insert into table1 values($username,"something else");
   $db->query($sql);
   ....
?>
SmallCucumber
Newbie Poster
12 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

firstly, if a session variable is NOT SET, you'll get an error when you try to test it for content. So isset() is useful.

diafol
Rhod Gilbert Fan (ardav)
Moderator
7,792 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 
firstly, if a session variable is NOT SET, you'll get an error when you try to test it for content. So isset() is useful.

thank you, i rewrite my code as:

if(!isset($_SESSION['username']) || $_SESSION['username']=='') header("Location:login.php");


but it still have a blank username record in the database.

SmallCucumber
Newbie Poster
12 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 
if(!isset($_SESSION['username']) || $_SESSION['username']==''){
   header("Location: login.php");
   exit();
}else{
   $username=$_SESSION['username'];
   $sql="insert into table1 values($username,"something else");
echo $username;
   //$db->query($sql);
}


try that to see if anything happens

diafol
Rhod Gilbert Fan (ardav)
Moderator
7,792 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 
if(!isset($_SESSION['username']) || $_SESSION['username']==''){
   header("Location: login.php");
   exit();
}else{
   $username=$_SESSION['username'];
   $sql="insert into table1 values($username,"something else");
echo $username;
   //$db->query($sql);
}

try that to see if anything happens

Thank you so much. I got it, header() will not block the execution of the rest codes.

SmallCucumber
Newbie Poster
12 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: