如何在php后端使用session

时间:2017-07-13 08:38:35

标签: php angularjs session

我正在使用PHP后端开发AngularJs应用程序,我实现了身份验证步骤,现在我正在尝试在身份验证后在另一个视图中显示经过身份验证的用户的数据。以下是我实现会话的两个files.php:第一个(login.php)由登录功能调用,第二个(info.php)由其他函数调用以显示用户数据。

即使我在一些关于会话和令牌的教程中读到的内容超过两周,我仍然无法显示用户数据。 你能帮帮我吗?

的login.php

<?php  
session_start();
$data = json_decode(file_get_contents("php://input"));

 $connect = mysqli_connect("localhost", "root", "", "test");  

 if(count($data) > 0)  

 { 

$Email=mysqli_real_escape_string($connect, $data->Email);
$mdp=mysqli_real_escape_string($connect, $data->mdp);

$query = 'SELECT * FROM `client` WHERE (EmailClient = "'.$Email.'" AND   mdp= "'.$mdp.'")';

$q = mysqli_query($connect , $query);

if(mysqli_num_rows($q) > 0 )
  { 
       $token = md5($Email.time()."51395+81519851");
       $query = "UPDATE client SET token = '".$token."' WHERE EmailClient = '".$Email."'";
       mysqli_query($connect , $query);
       $_SESSION["logged_in"] = true; 
       $_SESSION["token"] = $token; 
       $_SESSION["naam"] = $Email; 
       $result['code'] = 200;
       $result['message'] ='Logged In';
       $result['email'] =$Email;
       $result['role'] = 'client';
       $result['token'] = $token;

       $resultstring=json_encode($result);
       $resultstring=str_replace("null", '""', $resultstring);
       echo $resultstring;
       exit;
  }


       $result['code'] = 603;
       $result['message'] ='The username or password are incorrect!';



$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring;
exit;
}

?>

info.php的

<?php  
session_start();
 $connect = mysqli_connect("localhost", "root", "", "test");  

 $output = array();  
 $query = "SELECT NomClient,PrenomClient,EmailClient FROM client WHERE token = '".$_SESSION['token']."'";
 $result = mysqli_query($connect, $query);  
 if(mysqli_num_rows($result) > 0)  
 {  
      while($row = mysqli_fetch_array($result))  
      {  
           $output[] = $row;  
      }  
      echo json_encode($output);  
 }  

 ?>  

1 个答案:

答案 0 :(得分:0)

如果在info.php中登录了函数,则需要添加一个检查,例如:

<?php 
      session_start();
      if ($_SESSION["logged_in"] == false) 
      {
          echo "you need to be logged in to view this page!"; 
          die();
      }