PHP新用户自动登录

皇家奶酪1

我一直在尝试登录系统,并且已经构建了一个相当不错的(基本,但不错)的系统。我似乎无法上班的一件事是,在提交注册表格后(显然是在插入用户的情况下)让注册用户自动登录。

这是我的尝试:

*编辑:添加了完整的类,login.tpl.php和myProfile.php。对于所有代码段,我深表歉意!

登录类别:

<?php
class login
{
    protected $_email;
    protected $_password;
    protected $hash;

    protected $_db;
    protected $_user;   

    public function __construct(PDO $db)
    {
        $this->_db = $db;
    }

    public function validate()
    {
        $query = $this->_db->prepare('SELECT * FROM users WHERE email=?');
        $query->execute(array($this->_email));

        if ($query->rowcount() > 0)
        {
                $user = $query->fetch(PDO::FETCH_ASSOC);

                if (password_verify ($this->_password , $user['password']))
                {
                    return $user;
                }
        }

        return false;
    }

    public function login($email, $password)
    {
        $this->_email = $email;
        $this-> _password = $password;

        $user = $this->validate();
        if ($user)
        {
            $_SESSION['user_id'] = $user['id'];
            return $user['id'];
        }
        return false;
    }   

    public function createUser($first_name, $last_name, $email, $password)
    {
        $this->hash = password_hash($password, PASSWORD_BCRYPT);

        $query = $this->_db->prepare("INSERT INTO users (email, password, first_name, last_name) VALUES (:email, :password, :first_name, :last_name)");
        $query->execute(array(
        ":email"=> $email,
        ":password"=> $password,
        ":first_name"=> $first_name,
        ":last_name"=> $last_name));
    }

    public function logout()
    {
        session_destroy();
    }

    public function getUserData()
    {
        $this->_user = $_SESSION['user_id'] ;

        $query = $this->_db->prepare('SELECT * FROM users WHERE id=?');
        $query->execute(array($this->_user));
        return $query->fetch(PDO::FETCH_ASSOC);
    }

    public function uploadPicture($uploaded)
    {
        $targetPath = $_SERVER['DOCUMENT_ROOT'];    $targetPath .= "/wdv441/userLogin/app/views/img/";
        $pathinfo = pathinfo($uploaded['name']);
        $filesize = $uploaded['size'];
        $fileName = "profilePic". $this->_user . ".png";
        $ok = 1;
        $KB = 1024;
        $MB = 1048576;

        if ($filesize > 400*$KB)
        {
            echo "File too big.";
            $ok = 0;
        }
        else
        {
            if (move_uploaded_file($uploaded['tmp_name'], $targetPath . $fileName))
            {
                echo "File " . $fileName . " has been uploaded.";
            }
            else
            {
                echo "File not uploaded";
            } 
        }       
    }

    public function getPicture()
    {
        $targetPath = $_SERVER['DOCUMENT_ROOT'];    $targetPath .= "/wdv441/userLogin/app/views/img/";
        $fileName = "profilePic". $this->_user . ".png";
        $image = null;

        if (file_exists($targetPath . $fileName))
        {
            $image = $fileName;
        }
        else
        {
            $image = "default.png";
        }
        return $image;
    }

}

?>

register.php:

<?php
require_once($loginClassPath);
session_start();

if (empty($_SESSION['user_id']))
{
    try {
        $pdo = new PDO($dsn, $db_username, $db_password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch (PDOException $e){
        echo "Error connecting to database. Error" . $e->getmessage;
    }

    if ($pdo)
    {
            $loginClass = new login($pdo);

            if (isset($_POST['submit']))
            {
                $allFields = $_POST['first_name'] . $_POST['last_name'] . $_POST['email'] . $_POST['password'];

                if(!empty($allFields))
                {
                    if($loginClass->createUser($_POST['first_name'] , $_POST['last_name'] , $_POST['email'] , $_POST['password']))
                    {
                        if ($user_id = $loginClass->login($_POST['email'], $_POST['password'])) 
                        {
                            header('Location: myProfile.tpl.php');
                            die();
                        }
                    }
                }       
                else
                {
                    $errMsg = "red";
                }
            }

    }
}
else
{
    header('Location: myProfile.tpl.php');
    die();
}

?>

register.tpl.php:

<?php 
$errMsg=""; 

require_once($registerPath);
?>

<html>
<head>

<title>User login</title>
</head>
<body>

    <div style="text-align:center; margin-left:auto; margin-right:auto;"> 
        <h3>Please Fill out all fields below: </h3>
        <form method="post" action="<?php echo htmlspecialchars($_SERVER['SCRIPT_NAME']); ?>">

        <span style="color:<?php echo $errMsg; ?>;">All fields are required</span>
        <p>First Name: </p>
        <input type ="text" name="first_name" />
        <p>Last Name: </p>
        <input type ="text" name="last_name" />
        <p>Email: </p>
        <input type ="text" name="email" />
        <p>Password: </p>
        <input type="password" name ="password"/>
        <p><input type="submit" name ="submit" value="Register"/></p>
        </form>
    </div>

</body>
</html>

login.tpl.php

<?php 
$errMsg=" "; 

require($loginPath);

?>

<html>
<head>

<title>User login</title>
</head>
<body>
    <div style="text-align:center; margin-left:auto; margin-right:auto;"> 
        <h3>Please login below: </h3>
        <form method="post" action=<?php echo htmlspecialchars($_SERVER['SCRIPT_NAME']); ?>>
            <span style="color:red;"><?php echo $errMsg ?></span>
            <p>Username: </p>
            <input type ="text" name="email" />
            <p>Password: </p>
            <input type="password" name ="password"/>
            <p><input type="submit" name ="login" value="Login"/></p>
            <p>Don't have an account? <a href="register.tpl.php">Register here</a>!</p>
        <form>
    </div>

</body>
</html>

当前,当新用户注册时,它将把用户踢到登录屏幕。这是因为当它重定向到“ myProfile.php”时,为了使人们登录,我在“ myProfile.php”中包含以下代码:

myProfile.php:

<?php           
require_once($loginClassPath);
session_start();

if (!empty($_SESSION['user_id']))
{
    try 
    {
        $pdo = new PDO($dsn, $db_username, $db_password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch (PDOException $e)
    {
        echo "Error connecting to database. Error" . $e->getmessage;
    }
        if ($pdo)
        {
            $loginClass = new login($pdo);
            $userData = $loginClass->getUserData();

            if (isset($_GET['logout']))
            {
                if ($_GET['logout'] == 'yes')
                {
                    $loginClass->logout();
                    header('Location: login.tpl.php');
                    die();
                }
            }

        }
}
else
{
    header('Location: login.tpl.php');
    die();
}

?>

我的问题基本上是我哪里出问题了?我在这里关闭还是离开基地?

如果已经有与此类似的问题,我事先表示歉意,我环顾了一会儿,但找不到任何对我有帮助的问题。如果我没有提供足够的信息,请告诉我!

在此先感谢大家!

皇家奶酪1

我想到了!我修改了类createUser函数以执行以下操作:

public function createUser($first_name, $last_name, $email, $password)
{
    $this->_email = $email;
    $this-> _password = $password;
    $this->hash = password_hash($password, PASSWORD_BCRYPT);

    $query = $this->_db->prepare('SELECT * FROM users WHERE email=?');;
    $query->execute(array($this->_email));

    if ($query->rowcount() > 0)
    {
        echo "An account with that email already exists";
    }
    else
    {
        $query = $this->_db->prepare("INSERT INTO users (email, password, first_name, last_name) VALUES (:email, :password, :first_name, :last_name)");
        $query->execute(array(
        ":email"=> $email,
        ":password"=> $hash,
        ":first_name"=> $first_name,
        ":last_name"=> $last_name));
        $id = $this->_db->lastInsertId();

       $_SESSION['user_id'] = $id;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章