doupeizheng3918 2015-03-25 04:48
浏览 16
已采纳

PHP新用户自动登录

I've been playing around with login systems and I've got a pretty good (basic, but good) one built. One thing that I just can't seem to get to work is to have a registered user be logged in automatically after submitting the registration form (and the user being inserted, obviously).

Here is my attempt:

*Edit: Added full class, login.tpl.php, and myProfile.php. I apologize for all of the code snippets!

login class:

<?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>

Currently, when a new user registers, it kicks the user to the login screen. This is because when it redirects to "myProfile.php" I have the following code in the "myProfile.php" in order to make people sign in:

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();
}

?>

My question is basically where am I going wrong? Am I close or way off base here?

I apologize in advance if there is already a question similar to this, I looked around for a while but couldn't find anything that helped me. If I didn't supply enough info, please let me know!

Thanks in advance guys!

  • 写回答

1条回答 默认 最新

  • drtiwd06558 2015-03-25 17:36
    关注

    I figured it out! I modified the class createUser function to do the following:

    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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line