PHP Cookies Sessions
PHP Cookies Sessions
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.
< htmI>
< body>
<?ph p
i !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];
</body>
</htmI>
< htmI>
< body>
<?php
i !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];
</body>
</htmI>
Delete a Cookie
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
< htmI>
< body>
<?php
echo "Cookie ’user’ is deleted.";
</body>
</htmI>
PHP Sessions
A session is a way to store information (in variables) to be used across
multiple pages.
When you work with an application, you open it, do some changes, and then
you close it. This is much like a Session. The computer knows who you are.
It knows when you start the application and when you end. But on the
internet there is one problem: the web server does not know who you are or
what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used
across multiple pages (e.g. username, favorite color, etc). By default,
session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are
available to all pages in one application.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $ SESSION.
<?php
// Start the session
session start();
</body>
</htmI>
<?php
// to change a session variable, just overwrite it
$ SESSION["favcolor"] = "yellow";
print_r($ SESSION);
</body>
</htmI>
Destroy a PHP Session
To remove all global session variables and destroy the session,
use session unset() and session destroy():
<?ph p
session_start();
< !DOCTYPE htmI>
<htmI>
<body>
<?php
// remove all session variables
session_unset();
<htmI>
<head>
<titIe> Forms Handling in PHP</titIe>
</head>
<body>
<h1>Addition of two numbers: </h 1>
<form action="form_process.php" method="POST">
Enter Number 1: <input type="text" name="num 1"
id="num1"/> <br>
Enter Number 2: <input type="text" name="num2"
id="num2"/> <br> <br>
<button type="submit">ADD</button>
</form>
</body>
</html >
<?php
$n1 = $_POST['num 1'];
$n2 = $_POST[’num2’];
$sum = $n1 +$n2;