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);
   ....
?>

Recommended Answers

All 4 Replies

Member Avatar for diafol

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.

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.

Member Avatar for diafol
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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.