Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Try to retrieve a user with the given username from the database.
- $query = "SELECT user_id, unencrypted_password, is_admin FROM public.user WHERE username = :username";
- $query_params = array(':username' => $username);
- try{
- $stmt = $pdo->prepare($query);
- $result = $stmt->execute($query_params);
- }
- catch(PDOException $ex){
- echo '<span style="color: red">ERROR! Code: 009</span>';
- exit;
- }
- $row = $stmt->fetch();
- // When no user with the given username exist, the login fails
- if(!$row){
- $error = 1;
- } else {
- // Else get the unencrypted database from the result set
- $unencrypted_password = $row['unencrypted_password'];
- // Check that the password entered matches the one in the database.
- if($password == $unencrypted_password){
- // When true start a new php session (creates PHPSESSID cookie among other things)
- session_start();
- // Save the user id and whether the user is an administrator or not as session variables
- $_SESSION['user_id'] = $row['user_id'];
- $_SESSION['is_admin'] = $row['is_admin'];
- // When the remember me checkbox was activated in the login form, create a session_id cookie and more
- if($rememberMe) {
- // Generate new session ids until a unique session id is generated
- while(1){
- $possible_session_id = bin2hex(openssl_random_pseudo_bytes(16));
- $query = "SELECT 1 FROM public.user WHERE session_id = :session_id";
- $query_params = array(':session_id' => $possible_session_id);
- try{
- $stmt = $pdo->prepare($query);
- $result = $stmt->execute($query_params);
- }catch(PDOException $ex){
- echo '<span style="color: red">ERROR! Code: 005</span>';
- exit;
- }
- $row = $stmt->fetch();
- // When no row was found with this session id
- if(empty($row)){
- // The session id is unique and the script must no longer generate new session ids
- $session_id = $possible_session_id;
- break;
- }
- }
- // Set the session id of the logged in user to the generated session id
- $query = "UPDATE public.user SET session_id = :session_id WHERE user_id = :user_id";
- $query_params = array(':session_id' => $session_id, ':user_id' => $_SESSION['user_id']);
- try{
- $stmt = $pdo->prepare($query);
- $result = $stmt->execute($query_params);
- }catch(PDOException $ex){
- echo '<span style="color: red">ERROR! Code: 006</span>';
- exit;
- }
- // Set the new session id as session variable and as value of the session cookie
- setcookie("session_id", $session_id, time()+259200, "/chat/");
- }
- } else {
- // When the passwords don't match, the login fails
- $error = 1;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement