2017-05-23 100 views
-1

嗨,我寫的代碼,當我登錄我成功登錄並轉到我的願望頁面。但是會話不起作用。我想用用戶名更改登錄按鈕,但我失敗了。請檢查我犯的錯誤。使用php 5登錄腳本PDO

<?php 
start_session(); 
if(isset($_POST['login'])){ 
    $user_email = $_POST['user_email']; 
    $user_pass = $_POST['user_pass']; 
    echo $user_email. $user_pass; 
    $sqlQuery= 'SELECT * FROM user WHERE user_email = :user_email'; 
    $st= $conn->prepare($sqlQuery); 
    $st->execute(array('user_email' => $user_email)); 
    while ($row = $st->fetch()){ 
     $id =$row['id']; 
     $user_pass_hashed = $row['user_pass']; 
     $user_name = $row['user_name']; 
     if(password_verify($user_pass, $user_pass_hashed)){ 
      $_SESSION['id'] = $id; 
      $_SESSION['user_name']; 
      header('location: index.php'); 
      echo "<script type= 'text/javascript'>alert('Its Ok');</script>"; 
     }else{ 
      echo "<script type= 'text/javascript'>alert('Something went wrong');</script>"; 
     } 
    } 
} 
?> 

的index.php

<?php 
start_session(); 
    if(!isset($_SESSION['user_name'])) 
     echo'<li><a href="login.php" class="btn btn-red">Log In</a></li>'; 

    else 
      echo'<li><a href="admin.php" class="btn btn-red">Logged in</a></li>'; 
?> 
+0

它在session_start()內 – Ollaw

+0

'$ _SESSION [ 'USER_NAME'];'正在做什麼,你需要在那裏指定。 – chris85

+1

你的回聲在標題下永遠不會出現 –

回答

2

start_sessionsession_start();

但我擔心,爲什麼這

<?php 

start_session(); 

沒有把某種錯誤的?

更改爲

<?php 

    session_start(); 

爲了防止session already started PHP的通知, 做:

<?php 
if(!isset($_SESSION)){ 
    session_start();//only start if none exists 
} 
?> 

編輯: 更改此

if(password_verify($user_pass, $user_pass_hashed)){  
      $_SESSION['id'] = $id; 
      $_SESSION['user_name'];//this is not set. you need to assign a value 
      header('location: index.php');   
      echo "<script type= 'text/javascript'>alert('Its Ok');</script>"; 
     } 

有:

if(password_verify($user_pass, $user_pass_hashed)){  
      $_SESSION['id'] = $id; 
      $_SESSION['user_name'] = $user_name;//set current user's name 
      header('location: index.php');  
      echo "<script type= 'text/javascript'>alert('Its Ok');//header will override this echo.</script>"; 
     } 

您需要刪除標題下方的echo行。它永遠不會被執行。替代的方法來存儲成功的消息/失敗在會話變量,然後輸出它,然後取消它

+0

謝謝你的評論。 對不起,我在這段代碼中犯了這個錯誤,但在我寫的正確代碼中正確..請檢查其他代碼。 –

+0

我想你的問題已修復? – Akintunde007

+0

@sheikhhunny檢查我編輯部分的答案 – Akintunde007

0

我想它一定是

<?php 
if(!isset($_SESSION)){ 
    session_start(); 
} 
?> 

您設置了$ _SESSION [「USER_NAME」]但你不提供任何數據。

$ _SESSION ['id'] = $ id; $ _SESSION ['user_name'];

您可以檢查什麼是您的會話,如果你只是做

echo '<pre>; 
print_r($_SESSION); 
echo '</pre>; 

看到Print_r更多