Monday, May 16, 2016

PHP Session & PHP Cookies

PHP Session & PHP Cookies


PHP Session


A session is a way to store information (in variables) to be used across multiple pages.

Unlike a cookie, the information is not stored on the users computer.




Sample Code & Output

<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php

// Set session variables$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";

// Echo session variables that were set on previous pageecho "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>


</body>
</html>

Output:
Session variables are set. 
Favorite color is green.
Favorite animal is cat.



PHP Cookies


What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.


Syntax
setcookie(name, value, expire, path, domain, secure, httponly);


Sample Code & Output

<?php

         $cookie_name = "user";
         $cookie_value = "John Doe";
         setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day


         if(!isset($_COOKIE[$cookie_name])) {
             echo "Cookie named '" . $cookie_name . "' is not set!";
         } else {
             echo "Cookie '" . $cookie_name . "' is set!<br>";
             echo "Value is: " . $_COOKIE[$cookie_name];
         }


         echo "<strong>Note:</strong> You might have to reload the page to see the value of the                      cookie";

?>


Ref :


No comments:

Post a Comment