A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer. They are typically used to keeping track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time. A cookie is created at the server-side and saved to the client browser. Each time when a client sends a request to the server, the cookie is embedded with the request. In such a way, the cookie can be received on the server-side.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie() function needs to be called prior to any output generated by the script otherwise the cookie will not be sent.
Syntax :
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:
- Name: It is used to set the name of the cookie.
- Value: It is used to set the value of the cookie.
- Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
- Path: It is used to specify the path on the server for which the cookie will be available.
- Domain: It is used to specify the domain for which the cookie is available.
- Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.
Setting a Cookie in PHP
The
setcookie()
function is used to set a cookie in PHP. Make sure you call the function before any output generated by your script otherwise cookie will not set.
<?php
// Setting a cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>
Accessing Cookies Values
The PHP
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"]; $_COOKIE
superglobal variable is used to retrieve a cookie value.
?>
Removing Cookies
You can delete a cookie by calling the same
setcookie()
function with the cookie name and any value (such as an empty string) however this time you need the set the expiration date in the past.
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Cookies Example
login.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="card border-danger"> <div class="card-body text-center" id="msg"> </div> </div> <br> <script type="text/javascript"> function cookiesEnabled() { var cookiesEnabled = (navigator.cookieEnabled) ? true : false; return cookiesEnabled; } if (!cookiesEnabled()) { document.getElementById("msg").innerHTML = "Kindly Enable your Cookies First"; } </script> <h2>Cookies in PHP</h2><br> <form action=""method="post"> Username: <input type="text" name="un" value="<?php if(isset($_COOKIE['member_login'])){ echo $_COOKIE['member_login']; } ?>"><br><br> Password: <input type="text" name="pw" value="<?php if(isset($_COOKIE['member_login'])){ echo $_COOKIE['member_pwd']; } ?>"><br><br> Remember Me: <input type="checkbox" name="check"<?php if(isset($_COOKIE['member_login'])) { ?> checked <?php } ?> ><br><br> <input type="submit" name="b1" Value="LOGIN"> </form> </div> </body> </html> <?php
session_start(); include 'connection.php'; if(isset($_POST['b1'])) { $uname= $_POST['un']; $pwd= $_POST['pw']; $rem= $_POST['check']; $query = "select * from secetable where username='$uname' && password='$pwd'"; $data = mysqli_query($conn, $query); $totRec = mysqli_num_rows($data); if($totRec==1) { if(!empty($_POST['check'])) { setcookie('member_login',$uname,time()+60*60*1); setcookie('member_pwd',$pwd,time()+60*60*1); } else { if(isset($_COOKIE['member_login'])) { setcookie('member_login',''); } if(isset($_COOKIE['member_pwd'])) { setcookie('member_pwd',''); } } $_SESSION['user_name'] = $uname; $_SESSION['last_login'] = time(); header('location:home.php'); }else { echo "Login Failed"; } } ?>
Note: Enable the cookies first by configuring your browser otherwise it will show Error on login screen. "Enable Cookies first".
As we also add script to check wheather cookies are enable or note.
<script type="text/javascript"> function cookiesEnabled() { var cookiesEnabled = (navigator.cookieEnabled) ? true : false; return cookiesEnabled; } if (!cookiesEnabled()) { document.getElementById("msg").innerHTML = "Kindly Enable your Cookies First"; } </script>After successfully login into login.php, the cookies are saved in the browser. You can verify it in the browser setting.
Cookies in Browser Settings
|