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!
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;
}
}