Jul 02 2017
Jul 02, 2017

How to Set Cookies in PHP (PDO) using AJAX

Categorised in:

From the previous tutorial we already have our files and functions we need for a login form. In this tutorial we will use the same code and we will add some more functions and files to set up a Cookie and filter the information entered by users.

If you didn’t watch the previous tutorial you can find it on YouTube.

Our config.php file stays the same as in the previous tutorial:

<?php
class Connection extends PDO
{
    public function __construct()
    {
        parent::__construct("mysql:host=localhost;dbname=tutorial", 'root', '',
		array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        $this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }
}
?>

Please find in the previous post the SQL code to create a table in the database and to insert a new user.

Alright. So we have our login.php file which is located in /ajax/ folder => /ajax/login.php

The old code looks like this:

<?php
require_once('../config.php');
class User{
	function LogIn($nickname,$password){
		$db = new Connection;
		$user = $db -> prepare("SELECT id FROM users WHERE nickname = :name AND password = :pass");
		$user -> execute(array(
			'name' => $nickname,
			'pass' => $password
		));
		if($user -> rowCount() > 0){
			$con = 'Hi, '.$nickname;
		}else{
			$con = 'The nickname or Password is incorrect!';
		}
		return $con;
	}
}

$User = new User;
echo $User -> LogIn($_POST['nickname'],$_POST['password']);
?>

In our last tutorial the script from this file would check if there is any user with a nickname and password matching the user input and output an error message in case there is not such a user.

Now, what we want to do is to check if the user entered any information and if it did then we want to set up a cookie with a session if the user entered the right nickname and password. We will create another function which will generate a session for cookie. We will set up a cookie with this session and we will insert it in the database. Also, we want to have a filter to filter out any dangerous information and after the cookie is set up we will show a “Welcome” sentence and redirect the user, after 1.5 seconds, to the main page where the login form is.

Replace your code from login.php file with the following code:

<?php
require_once('../config.php');
class User{
	// generate a session
	function Session($length=6){
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
		$code = ""; 
		$clen = strlen($chars) - 1; 
		while (strlen($code) < $length){ 
			$code .= $chars[mt_rand(0,$clen)];
		}
		return $code;
	}
	// filter the information from Login form.
	function filter($str){
		//convert case to lower
		$str = strtolower($str);
		//remove special characters
		$str = preg_replace('/[^a-zA-Z0-9]/i',' ', $str);
		//remove white space characters from both side
		$str = trim($str);
		return $str;
	}
	function LogIn(){
		// check if the user entered any information
		if (isset($_POST['nickname'])) { $nickname = $_POST['nickname']; if ($nickname == '') { unset($nickname);} }
		if (isset($_POST['password'])) { $password = $_POST['password']; if ($password == '') { unset($password);} }
		if(empty($nickname) || empty($password)){
			$con = 'All fields are required!';
		}else{
			// connect to the database
			$db = new Connection;
			// let's get the user session
			$session = $this -> Session(10);
			// filter the information
			///$session = $this -> filter($session);
			$nickname = $this -> filter($nickname);
			$password = $this -> filter($password);
			// select the user with nickname and password entered
			$user = $db -> prepare("SELECT id FROM users WHERE nickname = :name AND password = :pass");
			$user -> execute(array(
				'name' => $nickname,
				'pass' => $password
			));
			// if the user were found
			if($user -> rowCount() > 0){
				$con = 'Welcome, '.$nickname;
				// update user session
				$update_user_sess = $db -> prepare("UPDATE users SET session = :user_session WHERE nickname = :user_nickname");
				$update_user_sess -> execute(array(
					'user_session' => $session,
					'user_nickname' => $nickname
				));
				// set up the cookie
				setcookie("session", $session, time()+60*60*24*30, "/", NULL);
				// redirect to the main page using JavaScript
				echo("<script>setTimeout("location.href = '/index.php';",1500);</script>");
			}else{
				// if the user weren't found
				$con = 'The nickname or Password is incorrect!';
			}
		}
		return $con;
	}
}
// assign the User object to $User variable
$User = new User;
// Output the LogIn() function from User Object
echo $User -> LogIn();
?>

Pay attention to the comments.

Alright! According to this code, if the user entered valid information, it is redirected to index.php, where the login form is located.

Now, we will open our index.php file and add some PHP code there. We will check if the user has the cookie from login.php. If the session from cookie match with the session from the database it means that the user went through the login form using a valid information and it also means that the user is online. The script will show “You are online!” with an exit link instead of login form.

So, the index.php file with the new code looks like this:

<?php
// get the connection to the database
require_once('config.php');
class LogIn{
	// function which will check if the user is online or offline
	function UserOnline(){
		// check if there is any cookie in the browser
		if(isset($_COOKIE['session'])){
			$db = new Connection;
			// filter the cookie
			$user_sess = preg_replace('/[^a-zA-Z0-9]/i',' ', $_COOKIE['session']);
			// select the user with the cookie from it's browser
			$get_user = $db->prepare('SELECT id FROM users WHERE session = :user_session');
			$get_user -> execute(array('user_session' => $user_sess));
			// check if any user was found
			if($get_user -> rowCount() > 0)
				return TRUE;
			else
				return FALSE;
		}else
			return FALSE;
	}
}
?>
<html>
	<head>
		<title>Login</title>
		<link rel="stylesheet" href="/css/style.css" type="text/css" >
		<script type="text/javascript" src="/js/jquery-3.2.1.min.js"></script>
		<script type="text/javascript" src="/js/javascript.js"></script>
	</head>
	<body>
		<div id="container">
			<?php
			$Login = new LogIn;
				// call the function which will check
				// if any user was found with the cookie from it's browser
				if($Login -> UserOnline() == TRUE){
					echo "You are online!<br /><br />
					<a href='exit.php'>Exit!</a>";
				// if there is no such user we show the login form
				}else{
			?>
			<div class="response"></div>
			<form id="login" action="" method="POST">
				<input type="text" name="nickname" placeholder="Nickname" /><br />
				<input type="password" name="password" placeholder="Password" /><br />
				<input type="submit" value="Enter" />
			</form>
			<?php } ?>
		</div>
	</body>
</html>

As you already understood we need another exit.php file which will delete the cookie and session in case the user clicked the exit link.

The exit.php file looks like this:

<?php
require_once('config.php');
	// filter the information from Login form.
function filter($str){
	//convert case to lower
	$str = strtolower($str);
	//remove special characters
	$str = preg_replace('/[^a-zA-Z0-9]/i',' ', $str);
	//remove white space characters from both side
	$str = trim($str);
	return $str;
}
$db = new Connection;
$user = $db -> prepare("UPDATE users SET session = :new_session WHERE session = :current_sess");
$user -> execute(array(
	'new_session' => NULL,
	'current_sess' => filter($_COOKIE['session'])
));
setcookie('session', '', time() - 60*60*24*30, '/');
header('Location: /index.php');
die();
?>

I also made some changes in /css/style.css file. It looks like this now:

#container{
	margin: 50px auto 0;
	padding: 10px;
	background: #3e6692;
	border: 1px solid #444;
	text-align: center;
	width: 20%;
	color: #FFFFFF;
}
#container a{
	color: #fff;
	text-decoration: none;
}
#container a:hover{
	text-decoration: underline;
}
.response{
	margin-bottom: 5px;
}
input[type="text"], input[type="email"], input[type="password"], input[type="file"], select {
	margin-bottom: 10px;
    background-color: #fff;
    box-sizing: border-box;
    border-radius: 2px;
    color: #333;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    float: none;
    font-size: 16px;
    border: 1px solid #ccc;
    padding: 6px 10px;
    height: 38px;
    width: 100%;
    line-height: 1.3;
}
input[type="submit"] {
    background-color: #eee;
    border: 1px solid #ddd;
    color: #333;
    font-size: 1em;
    padding: 10px 15px;
    cursor: pointer;
}
input[type="submit"]:hover{
	background-color:#ddd;
	border:1px solid #ddd;
	color:#333;
	font-size:1em;
	padding:10px 15px;
}

The /js/javascript.js file stays the same:

$(document).ready(function() {
	// here we get our form id from index.php 
	// (<form id="login" action="" method="POST">)
	var login = $('#login');
	// here we get the div class from index.php
	// in this div the AJAX will output the response which mens
	// that will show there the result from /ajax/login.php
	var response = $('.response');
	login.on('submit', function(e) {
		e.preventDefault();
		// here is our ajax function wich looks like this:
		$.ajax({
			// here is the location to our php file which will be called by AJAX
			url: '../ajax/login.php',
			// the data will be sent using POST method
			type: 'POST',
			// data type is HTML
			dataType: 'html',
			data: login.serialize(),
			// so here before we get any response from it is going to show "Loading..."
			beforeSend: function() {
				response.fadeOut();
				response.fadeIn();
				response.html('Loading...');
			},
			// if the data was successfully sent
			// then it shouw the result in our "response" div
			success: function(data) {
				response.html(data).fadeIn();
				login.trigger('reset');
			},
			error: function(e) {
				console.log(e)
			}
		});
	});
});

That’s it for now! Thank you for your interest and remember that the reason of these tutorials is to help you grow your knowledge in web development. Feel free to subscribe for my youtube chanel and watch more video tutorials.