2017-03-20 23 views
1

下面描述的當前代碼不起作用。我想在會話中存儲用戶名並將其顯示在主頁中。這是我用來存儲和顯示用戶名的代碼。當用戶名正確時,這將直接指向主頁。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; 
    } 
+0

讓假定您的查詢工作正常並且你正在從數據庫中所需要的一切。在頁面開始處聲明session_start()。打開php代碼下面的html代碼。它應該工作。 –

回答

2

嘗試這樣的事情,除去第一if條件,然後再更改第二if條件

<?php 
    session_start(); 
    if(!isset($_SESSION['username'])) { 
     header('Location: index.php'); 
     exit; 
    } 

?> 
+1

當我從home.php刪除這些行「if(!isset($ _ SESSION ['username'])){header('Location:index.php'); exit;}; 它從登錄頁面重定向到home – Udhayakkrishna

+0

當我使用上面的代碼,它不會重定向從登錄到家 – Udhayakkrishna

+0

檢查'$ _SESSION ['用戶名']'有一個值,刪除'if'然後只是回顯它 – Swellar