下面描述的當前代碼不起作用。我想在會話中存儲用戶名並將其顯示在主頁中。這是我用來存儲和顯示用戶名的代碼。當用戶名正確時,這將直接指向主頁。Php會話在我的代碼中不起作用
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" name="submit" class="btn btn-success" value="Login" />
<?php
session_start();
$error='';
if (isset($_POST['submit']))
{
$username = $_SESSION['username'];
$username = $_SESSION['login_user'];
if (empty($_POST['username']) || empty($_POST['password']))
{
echo "<script type='text/javascript'>alert('Username or Password is invalid')</script>";
}
else
{
$username=$_POST['username'];
$password=$_POST['password'];
$con = mysqli_connect("mysql.site","username","password","database");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$query = mysqli_query($con,"select * from userprofile where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1)
{
$_SESSION['username']=$username;
$_SESSION['login_user']=$username;
if (isset($_POST['rememberme'])) {
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', md5($_POST['password']), time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false, '/account', 'www.example.com');
setcookie('password', md5($_POST['password']), false, '/account', 'www.example.com');
}
header('Location: home.php');
}
else
{
echo "<script type='text/javascript'>alert('Invalid Username & Password')</script>";
header('Location: home.php');
}
mysqli_close($con);
}
}
?>
當會話爲空時,此代碼將導航到login(index.php)頁面。
home.php
<?php
if (!isset($_SESSION)) {
session_start();
}
if(!$_SESSION['username']) {
header('Location: index.php');
exit;
}
?>
此代碼是不是現在的工作,但是當我刪除此代碼它的工作。
if(!$_SESSION['username']) {
header('Location: index.php');
exit;
}
讓假定您的查詢工作正常並且你正在從數據庫中所需要的一切。在頁面開始處聲明session_start()。打開php代碼下面的html代碼。它應該工作。 –