|
home—lects—exams—hws
D2L—breeze (snow day)
From PHP Visual Quickstart Guide by Larry Ullman
Originally based on notes by Jack Davis (jcdavis@radford.edu)
We have discussed cookies, and in particular how setting a cookie "userID" can help us (the server) keep track of repeated visits from the same browser&user. (If you leverage that with having the server keep a database for each user, then this gives us history that can cross browsers.)
Self-assessment: Why does the following not print out 2.50?
<?php // before any html has been printed: setcookie('hamburger-price', 2.50); ?> ⋮ <p> The going rate for hamburgers is $<?php printf("%.2f", $_COOKIE['hamburger-price'] ); ?>. </p> |
$_SESSION['first_name'] = "Marc"; $_SESSION['age'] = 35; |
A smaller example is at page0.php. A similar (but more varied) example is at lect09a-ch09-login.php.
Gotcha:setcookie sets a cookie relative to the current directory, but the session cookie (by default) is relative to root. So to destroy the session cookie, you must pass'/' (by default) as the 4th argument tosetcookie .Better, rather than assuming that session-cookies use / as the cookie-path, you should look up what the path for session-cookies is, using
session_get_cookie_params :
$myParams = session_get_cookie_params(); echo "The default path of cookies is ", $myParams['path']; print_r($myParams); setcookie( session_name(), '', 1, $myParams['path'] ); // note that sadly, php doesn't let you just do this in one line: // setcookie( session_name(), '', 1, session_get_cookie_params()['path'] ); // Syntax error!
home—lects—exams—hws
D2L—breeze (snow day)
©2012, Ian Barland, Radford University Last modified 2012.Nov.21 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |