-3

i am using a script at front end, if a user logs in, it should render username in place of login button else it should remain the same. but my script is not not working....

<?php 
    if(!isset($_SESSION['txt_username']) || !isset($_SESSION['txt_pwd'])){
    echo "<a href='login.php'>Log in</a>"; 
    header("Location:login.php");
    else {echo $_SESSION['txt_username']}
    }
?>

2 Answers2

0

There are a couple of syntax errors. Properly formatting your code will help dramatically when trying to diagnose errors:

<?php 
if(!isset($_SESSION['txt_username']) || !isset($_SESSION['txt_pwd'])){
    //echo "<a href='login.php'>Log in</a>";                                          
    header("Location:login.php");
}else{
    echo $_SESSION['txt_username'];
}
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
  • 2
    You are going to suffer from the same (hidden) error. You can not print output before sending headers. – Lix Dec 05 '13 at 17:08
  • Oh? I stopped working with PHP a while back so I'm not in tune with the latest and greatest updates :P Could you provide a reference for that statement? – Lix Dec 05 '13 at 17:11
  • http://stackoverflow.com/questions/7934351/why-does-this-header-location-redirect-work-after-content-has-already-been-echoe – Samuel Cook Dec 05 '13 at 17:13
  • Ah, so you mean when the output is being buffered. In that case could could do something like that, but I don't believe it's related to PHP versions... Perhaps if a newer version changed the default settings. – Lix Dec 05 '13 at 18:46
0

The header function of php does the redirect immediatly when it finds that line. (it does other stuff also :) ) Read at: http://php.net/manual/en/function.header.php .

try this:

if(!isset($_SESSION['txt_username']) || !isset($_SESSION['txt_pwd'])){
    echo "<a href='login.php'>Log in</a>";                                          
else {
    echo $_SESSION['txt_username'];
}

In the ending: DO NOT KEEP THE PASSWORD IN $_SESSION!!!! . At least use md5() or some encryption on that password.

Adrian Mare
  • 99
  • 1
  • 5