Cookies hold text that you can store on the user's computer and retrieve later. You can set cookies using the setcookie function: setcookie(string name [, string value [, int expire [, string path [, string domain [, int secure]]]]]) This function defines a cookie to be sent to the user's machine. Here is what the various parameters mean:
Note that cookies are part of the HTTP headers sent to the browsers, and so they must be sent before any other output from your script. This means that you should place calls to this function before any other output, including <HTML> and <HEAD> tags. If some output exists before calling this function, setcookie may fail and return FALSE. If setcookie runs successfully, it will return trUEbut that does not indicate whether the user accepted the cookie. Here's an example. In this case, we're going to create a cookie named message that will hold the text "No worries.", and we do that with setcookie: <?php setcookie("message", "No worries."); ?> This PHP goes at the beginning of the script phpsetcookie.php, as you can see in Example 9-1. Example 9-1. Setting a cookie, phpsetcookie.php<?php setcookie("message", "No worries."); ?> <HTML> <HEAD> <TITLE> Setting a cookie </TITLE> </HEAD> <BODY> <CENTER> <H1> Setting a cookie </H1> Cookie has been set! Look at <A HREF="phpgetcookie.php">phpgetcookie.php</A> next. </CENTER> <BODY> </HTML> This page appears in Figure 9-1, where PHP has sent the cookie to the browser, and it's already been set. Figure 9-1. Setting a cookie.Now the cookie's been set, but how do we read it? When the user clicks the hyperlink in this page, he or she will be redirected to phpgetcookie.php, which is coming up in the next chunk. |