问题
I have this loginform.php with this part of code (this was called from index.php with a login form):
include("config.php");
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "" || $password == "")
{
echo "Either username or password field is empty.";
echo "<br/>";
echo "<a href='index.php'>Go back</a>";
}
else
{
$result = mysql_query("select * from users where user_username='$username' and user_password='$password'",$conn)
or die("Could not execute the select query.");
$row = mysql_fetch_assoc($result);
if(is_array($row) && !empty($row))
{
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
}
else
{
echo "Username and password do not match.";
echo "<br/>";
echo "<a href='index.php'>Go back</a>";
}
if(isset($_SESSION['valid']))
{
header("Location:index.php?");
}
}
}
but after that it should've shown again the index.php without the login form
index.php had this code to display the user after successful login:
<?php
if(isset($_SESSION['valid']))
{
include("config.php");
$result = mysql_query("select * from users",$conn);
echo "Welcome ".$_SESSION['valid']. "! <a href='logout.php'>Logout</a><br/>";
}
else
{
require('./loginform.php');
}
?>
with this code the login form do not showed up but instead not showing anything. It should display the user that had logged in. I dont know what I missed. Im a newbie at php. Please help. sorry, please assumed that there is a session start at all file.
回答1:
You have to add session_start() before checking the existence of the session variable.
<?php
session_start();
if(isset($_SESSION['valid']))
....
session_start() creates a session or resumes the current one.
来源:https://stackoverflow.com/questions/19476873/isset-didnt-work-after-login-with-session-set-to-valid