Jump to content

Login and Cookies


ibnclaudius

Recommended Posts

Not sure if everything is working right because I am in the school computer and here I can not install apache / php / etc.

 

I'm not sure about how to use cookies.

 

Here is my code, any errors or suggestions just talk. Probably does not work, because as I said, not yet tested.

 

login.php

<?php

session_start();

include 'class.php';

if (isset($_POST['username']) && isset($_POST['password'])) {
$user  = new User($_POST['username']);
if ($user->exists()) {
	$login = $user->login($_POST['password']);
	if ($login) {
		$_SESSION['user_id'] = $login;
		session_write_close();
	} else {
		echo "Login failed.";
	}
} else {
	header("Location: register.php");
}
}

?>

<!DOCTYPE html>
<html>
<head>
	<title>Login Form</title>
</head>
<body>
	<form action="" method="post">
		<label for="username">Username: </label>
		<input type="text" name="username" /><br />
		<label for="password">Password: </label>
		<input type="password" name="password" /><br />
		<input type="submit" value="Submit" />
	</form>
</body>
</html>

 

class.php

<?php

class User {
protected $id;
protected $username;
protected $email;
protected $sql;

private $exists = FALSE;

public function __construct($username) {
	if (empty($username)) {
		throw new Exception('Username cannot be blank.');
	}

	$this->username = $username;
	$this->sql      = new PDO(DSN, DBUSER, DBPASS);
	$this->exists   = $this->validate();
}

private function createLoginToken($id) {
	$token   = $id . md5(microtime());
	$expires = new DateTime();

	$expires->add(new DateInterval('P30D'));

	$query = "INSERT INTO sessions (userID, token, expires)
		  VALUES (:id, :token, :expires)";
	$stmt  = $this->sql->prepare($query);

	$stmt->execute(array(':id'      => $id,
			     ':token'   => $token,
			     ':expires' => $expires->format('Y-m-d H:i:s')));

	setcookie('token', $token, $expires->getTimestamp(), '/');
}

private function hashPassword($password, $salt) {
	$string = PASSWORD_SALT . $password . md5($salt);
	$hashed = crypt($string, '$2a$12$' . substr(md5($salt), 0, 22));

	return $hashed;
}

private function validate() {
	$query = "SELECT COUNT(id)
		  FROM users
		  WHERE username = :username";
	$stmt  = $this->sql->prepare($query);

	$stmt->execute(array(':username' => $this->username));
	$count = $stmt->fetchColumn();

	return ($count > 0) ? TRUE : FALSE;
}

public function exists() {
	return $this->exists;
}

public function login($password, $remember = FALSE) {
	$query = "SELECT id, password, UNIX_TIMESTAMP(created) AS salt
		  FROM users
		  WHERE username = :username";
	$stmt  = $this->sql->prepare($query);

	$stmt->execute(array(':username' => $this->username));

	$row = $stmt->fetch(PDO::FETCH_OBJ);

	$hashed = $this->hashPassword($password, $row->salt);

	if ($row->password == $hashed) {
		if ($remember) {
			$this->createLoginToken($row->id);
		}
		return $row->id;
	}

	return FALSE;
}

public function random() {
	$random = mt_random(1000,9999);

	return $random;
}

public function registerUser($email) {
	if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
		throw new Exception('Email does not appear to be valid.');
	}
	$this->email = $email;

	$date   = new DateTime();
	$hashed = $this->hashPassword($pass->random(), $date->getTimestamp());

	$query = "INSERT INTO users (username, password, email, created)
		  VALUES (:username, :password, :email, :created)";
	$stmt  = $this->sql->prepare($query);

	$success = $stmt->execute(array(':username' => $this->username,
					':password' => $hashed,
					':email'    => $email,
					':created'  => $date->format('Y-m-d H:i:s')));

	return ($success === TRUE) ? $this->sql->lastInsertId() : FALSE;
}

public function verifyCookie($token) {
	$query = "SELECT userID
		  FROM sessions
		  WHERE token = :token
		  AND expires > NOW()";
	$stmt  = $this->sql->prepare($query);

	$stmt->execute(array(':token' => $token));

	return $stmt->fetchColumn();
}
}

?>

 

db.sql

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) DEFAULT NULL AUTO_INCREMENT,
`username` varchar(30) DEFAULT NULL,
`password` varchar(60) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL UNIQUE,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `sessions` (
`id` int(11) DEFAULT NULL AUTO_INCREMENT,
`userID` int(10) DEFAULT NULL,
`token` varchar(50) DEFAULT NULL,
`expires` datetime DEFAULT NULL,
KEY `userID` (`id`,`userID`,`token`,`expires`),
KEY `token` (`id`,`userID`,`token`,`expires`),
PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Link to comment
https://forums.phpfreaks.com/topic/252916-login-and-cookies/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.