longlost10
longlost10

Reputation: 57

Global Variable Does not hold in PHP

I have a page, header.php that, among many things, offers the user of my site a place to sign in. It loads, settings, database functions and a CSS file. In the settings file I declare a global variable $username. In header.php I have the following code:

if(!isset($username)){
  echo'<div class = "loginSpace">';
  echo'
  <form action = "checkLogin.php" method = "post">
  Username: <input type = "text" name = "username" size = 14/>
  <br>Password: <input type = "password" name = "pass" size = 14 />
  <input type = "submit" value = "Sign In"/>
  </form>
  </div>';
}
else{
     $result = mysql_query("SELECT * FROM {$db_prefix}Users WHERE Username = '{$username}'");
     $userInfo = mysql_fetch_array($result);
     echo '<div class = "loginSpace">
     Welcome ' . $userInfo['FirstName'] .'
     <form action = "index.php" method = "post"> '; 
     $username = "";
     echo'<input type = "submit" value = "Log out"/>
     </form>
     </div>';
     }

In checklogin, I have:

$username = $_POST['username'];
$password = $_POST['pass'];
require_once('Header.php');

The username is held and the proper "heading" shows up when you get redirected to checkLogin.php, however, if you click a link to go to another page of the site, the username is forgotten.

Am I forgetting something? Thanks.

Upvotes: 1

Views: 172

Answers (2)

GaurabDahal
GaurabDahal

Reputation: 876

i dont understand your question clearly but have you declared username as a global variable in header.php?? if so, in every page if you are including header.php, you first write,

global $header;

and then use the variable $header.

web pages are stateless, so to maintain state you can either use cookie or sessions or hidden fields.

Upvotes: 6

NullPoiиteя
NullPoiиteя

Reputation: 57322

in another link the username will be forgot since you are using the post if you want to access user name on ever page user SESSION instead

you should check first

if(isset($_POST['username']) && isset($_POST['pass']))  {
    $username = $_POST['username'];
   $password = $_POST['pass'];

}

and

$result = mysql_query("SELECT * FROM {$db_prefix}Users WHERE Username = '{$username}'");
                                                 ^---there should be space 

Upvotes: 1

Related Questions