Reputation: 157
I have got a session up and running in PHP, but for some reason when I click a page sometimes, the session seems to end unexpectedly. FOR EXAMPLE: I have a simple user login page (just username): INDEX.PHP
<h1>User Sign-In:</h1>
<form name="login" action="main.php" method="post">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
MAIN.PHP
<?php
session_save_path(trim(`echo ~`).'/php_sessions'); session_start();
$_SESSION['username']= $_POST["username"];
$username = $_SESSION['username'];
if(isset($_SESSION['username']))
{
}
else
header('Location:./index.php');
?>
<body>
<?php
echo "Hello, your username is: " . $_SESSION["username"];
?>
<a href="./main.php">Store</a> | <a href="./basket.php">Basket</a> | <a href="./about.php">About</a> | <a href="./logout.php">Logout</a>
<form name="select1"action="" method="GET">
<select name="higherorlower">
<option value="All">All</option>
<option value="greaterthan">Greater Than</option>
<option value="lowerthan">Lower Than</option>
</select>
Price:<input type="text" name="price"/>
<input type="submit" name="submit" value="Submit" />
BASKET.PHP
<?php
session_save_path(trim(`echo ~`).'/php_sessions'); session_start();
$username = $_SESSION['username'];
if(isset($_SESSION['username']))
{
}
else
header('Location:.');
?>
<body>
<?php
echo "Hello, your username is: " . $_SESSION["username"];
?>
<a href="./main.php">Store</a> | <a href="#">Basket</a> | <a href="./about.php">About</a> | <a href="./logout.php">Logout</a>
<h2>
You're currently on the basket page!
</h2>
So say I type in my username and it takes me to the MAIN.PHP fine and displays my username fine, I then click the basket page and it also displays my username fine, but when I click from the BASKET.PHP to the MAIN.PHP it looses the username and displays nothing....
I have no idea what is going on and any help would be greatly appreciated, thanks.
Upvotes: 1
Views: 944
Reputation: 11
Just modified your code at MAIN.php
. Now it should work.
session_start();
session_save_path(trim(`echo ~`).'/php_sessions');
if(!empty($_POST["username"])){
$_SESSION['username']= $_POST["username"];
$username = $_POST["username"];
}
if(!isset($_SESSION['username'])){
header('location: index.php');
}
Upvotes: 0
Reputation: 68526
but when I click from the BASKET.PHP to the MAIN.PHP it looses the username and displays nothing....
That is because you are assigning
$_SESSION['username']= $_POST["username"];
on your main.php
,since there is no POST value there (as of now) , it gets overwritten.
Change your code on your main.php
file like this
if(!isset($_SESSION['username']))
{
if(isset($_POST["username"]))
{
$_SESSION['username']= $_POST["username"];
$username = $_SESSION['username'];
}
else
{
header('Location:./index.php');
}
}
Upvotes: 1