创建会话用户登录php

时间:2013-11-03 21:44:37

标签: php mysql session login

我一直坚持如何为登录的用户创建会话。我得到了检查的一部分,以确保登录信息与数据库信息相对应,但是仍然坚持如何获取电子邮件地址和存入会话。这是我的PHP代码如下。

<?php include '../View/header.php';
session_start();
require('../model/database.php');
$email = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT emailAddress FROM customers WHERE emailAddress ='$email' AND password = '$password'";
$result = mysql_query($sql, $db);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['emailAddress'];
}

mysql_free_result($result);

?>

4 个答案:

答案 0 :(得分:1)

尝试以下内容。

请注意,此mysql连接类型已被折旧,请查找PDO。此外,您还需要阅读sql注入,因为这不安全。

<?php 
    //always put session_start() at the top of the file
    session_start();

    include('../View/header.php');
    require ('../model/database.php');

    $email = $_POST['username'];
    $password = $_POST['password'];  

    $sql = "SELECT emailAddress FROM customers WHERE emailAddress = '$email' AND password = '$password'";
    $result = mysql_query($sql, $db);

    if(!$result){
        echo "DB Error, could not query the database\n";
        echo 'MySQL Error: ' . mysql_error();
        exit;
    }

    while($row = mysql_fetch_assoc($result)) {
        echo $row['emailAddress'];
        $_SESSION['email'] = $row['emailAddress'];
        $_SESSION['batmansName'] = "Bruce Wayne";
    }

    mysql_free_result($result);

?>`
<a href="anotherFile.php">Click to output the contents of our session :)</a>

anotherFile.php

<?php

    //always put session_start() at the top of the file
    session_start();

    //print out everything that we have stored in the session
    print_r($_SESSION);

    echo "<br /><br />";

    echo "Session email: ".$_SESSION['email']."<br />";
    echo "Batman's real name: ".$_SESSION['batmansName']."<br />";


?>

答案 1 :(得分:0)

你的头文件是否有任何输出?如果是这样,您需要将session_start置于其前面,以便设置标题。如果没有这样做,您的会话数据将不会被保留。

接下来,要在会话中存储数据,我们使用$_SESSION超全局

$_SESSION['email'] = $row['emailAddress'];

答案 2 :(得分:0)

  1. 在打印任何内容之前启动会话
  2. 使用$ _SESSION存储用户数据
  3. 示例:

    session_start();
    include '../View/header.php';
    require ('../model/database.php');
    $email= $_POST['username'];
    $password= $_POST['password'];  
    $sql    = "SELECT emailAddress FROM customers WHERE emailAddress ='$email' AND password = '$password'";
    $result = mysql_query($sql, $db);
    
    if (!$result) {
        echo "DB Error, could not query the database\n";
        echo 'MySQL Error: ' . mysql_error();
        exit;
    }
    
    if ($row = mysql_fetch_assoc($result)) {
         $_SESSION['user_address'] = $row['emailAddress'];
    }
    
    mysql_free_result($result);
    

答案 3 :(得分:0)

首先,请阅读SQL注入:http://de.wikipedia.org/wiki/SQL-Injection,因为您的代码存在重大安全问题

其次,在包含标题之前,您必须先调用session_start();,如果在调用之前已将任何内容发送到浏览器,则无效。