0

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);
   ....
?>
2
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by SmallCucumber
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.

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.

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.

Edited by SmallCucumber: n/a

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

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

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.