Payne's PHP Notes

Back to Payne's PHP Notebook.

7. Cookie, Session

Cookie:

Source Code Result
// Should before <html>
<?php
setcookie("cookieName", "cookieValue", time()+3600*24);
?>

<html>
...
<?php
echo "Cookie Value: " . $_COOKIE["cookieName"] . "<br />";

print_r($_COOKIE);
?>
Cookie Value:
Array ( )
// Delete a cookie by setting the expiration time.
setcookie("cookieName", "", time()-100);
 

Session

Source Code Result
// Should before <html>
<?php
session_start();

if(isset($_SESSION["count"]))
{
    $_SESSION["count"] += 1;
}
else
{
    $_SESSION["count"] = 1;
}
?>

<html>
<body>
<p>Count:
<?php echo $_SESSION["count"]; ?>
</p>
</body>
</html>
Count: 1
// Delete some session data.
unset($_SESSION["count"]);

// Destroy this session.
session_destroy();