Thursday, 5 October 2017

How to create a cookie and session with a php script


what are cookies :
Cookies are files stored on the user computer.They are used to store user data which is mainly used to identify a user whenever they visit the website again. A cookie can be set by using a function called:
                  "setcookie()".
 The setcookie() function can be used to set cookie in php.After setting the cookie make sure you call the function before any output can be displayed.   A COOKIE RESIDES ON THE USER'S COMPUTER
Parameters that are in the setcookie() function.
 setcookie{name,value,expire,domain};
NoteName:The name of the cookie set.
Value:The value of the cookie and ensure tou dont set sensitive information in it.
Expire:The expire date can be set with a UNIX time-stamp.
Domain:the specified domain where the cookie is available.
   Here's is a php script that uses the setcookie() function to create a cookie.Name:My first cookie, value:"Lorem ipsum", Expire:time() + (3600).The 3600 that is set in the time, means it the cookie willexpire in 1hour.

<?php
$name="MyFirstCookie"; 
$value = 'lorem ipsum'; 
$expire = time() + (3600); 
setcookie($name , $value, $expire); 
echo $_COOKIE[$name]; 
?>
The php code in the above example produce the following output.


To check if a cookie is set or not you can use a php isset() function.
<?php 
$name="MyFirstCookie"; 
$value = 'lorem ipsum'; 
$expire = time() + (3600); 
setcookie($name , $value, $expire); 
if(isset($name['MyFirstCookie'])){ 
echo "hi"; 
}else{ 
echo "welcome to the world of cookie"; 
?>




what are session:Session are used to store user information, which can be used accross many webpages.A session is started with the session_start function.SESSION INFORMATION RESIDES ON THE WEB SERVER

Session variable are set with the php global variable $_SESSION.
  SESSION INFORMATION RESIDES ON THE WEB SERVER
Here's is an example of a session.
<?php 
// Start the session
session_start();
?> 
<!DOCTYPE html>
<html>
<body>
<?php 
// Set session variables 
$_SESSION["name"] = "Session"; 
$_SESSION["Value"] = "ipsum dolor"; 
echo "Session variables are set.";
?>
</body>
</html>
The php code in the above exapmle shows the following output.

No comments:

Post a Comment