Lesson PHP 02 Sessions & Cookies
Lesson PHP 02 Sessions & Cookies
Session (, -. )
Sessions
Session - Variables are kept on a server in files. Path of the file is defined in the php.ini file.
session.save_path = "C:/TEMP"
Example:
page1.php
<?php
session_start();
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
?>
page2.php
<?php
session_start();
echo $_SESSION['favcolor'] . "<br />";
// green
echo $_SESSION['animal'] . "<br />";
// cat
echo date('Y m d H:i:s', $_SESSION['time']) . "<br />";
?>
Destroying a Session
If you wish to delete some session data, you can use the unset()
or the session_destroy() function.
<?php
session_start();
session_unset();
// or unset($_SESSION['favcolor']);
?>
<?php
session_start();
// You can also completely destroy the session by calling:
session_destroy();
// it will reset your session and
// you will lose all your stored session data.
// or $_SESSION = array();
?>
Cookies
Variables are kept on the user computer
Create a Cookie
setcookie (name, value, expire, path, domain);
// This function must appear BEFORE the <html> tag.
name value expire path -
Example:
- Create a Cookie
// We will create a cookie named "user" and assign the value "Alex Porter" to it.
// And the cookie should expire after one hour.
setcookie("user", "Alex Porter", time()+3600);
- Print an individual cookie
echo $_COOKIE["user"];
// or
echo $HTTP_COOKIE_VARS["user"];
- Delete a Cookie
setcookie("user", "");
header
void header ( string string [, bool replace]);
<?php
// HTTP/1.1
?>
<?php
header("Location: http://www.example.com/"); // Redirect browser
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf for download
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in ex.pdf
//readfile('ex.pdf');
?>
no cache
<?php
// Date in the past
header("Expires: Mon, 23 May 1995 02:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
?>