Page created 8 May 2005, updated 13 June 2008.
PHP ProgrammingPage 3 This article is about using cookies with PHP. COOKIE PROBLEMS It's easy to create a Cookie, but if you use comas, semi-colons, or white spaces, you will have to 'escape' the characters. In reality, you will probably collect the data from a form, and somebody is bound to enter a character, which needs to be escaped. Therefore, it makes sense to always escape the cookie data. ENCODE AND DECODE To escape a string you use the ' rawurlencode() ' function. This is the equivalent to the 'Escape' function in JavaScript. To restore the data, you use the ' rawurldecode ' function. CREATING A COOKIE At the time, I thought it would be a good idea to use a 'Function' to encode the string. The idea being that I might want to use the function for another script. The script uses 3 strings, $name, $address, $mail, and separates them with '||', before combining them into $str. <?php //==================================== Encoder function encode( $str ){ $res=rawurlencode($str); return $res; } //======================================= Set variables $name = "My Name"; $address = "My Address"; $mail = "jim@daftwat.biz"; //================================================ Create Cookie $str = $name . "||" . $address . "||" . $mail; $code = encode( $str ); setcookie( "cook1", $code ); ?> RESTORING THE DATA The script below returns the data from the cookie, back to the original strings, $name, $address, and $mail. <?php //=================================== Decoder function decode( $str ){ $res = rawurldecode( $str ); return $res; } //======================================== Get cookie $code1 = $_COOKIE['cook1']; $code2 = decode( $code1 ); //=================================== Create array $code3 = split( "[||]" , $code2 ); //===================================== Restore original data $code3[0] = $name; $code3[1] = $address; $code3[2] = $mail; //================================ Print values echo( $name . "<br>" ); echo( $address . "<br>" ); echo( $mail . "<br>" ); ?> NOTES In case you're wondering why I used '||' to separate the strings, my reasoning is that it is very unlikely that somebody would enter "||" into a form field. If they do, it will create an extra string, and create an error. I dare say that some idiot will read this and start typing "||" into every form on the Internet. What ever you do, don't vote for him (could it possibly be a girl?). The cookie is set to last for the session only. If you want it to remain, you will have to set the date. For example: setcookie( "cook1", $code, time() + 36000 ); JAVASCRIPT Since all programming languages are similar, I decided to create a similar script using JavaScript. It is located, of course, in the JavaScript section.
|