PHP

SIMPLE EXAMPLES OF USING COOKIES IN PHP

* COOKIES ARE NOT SAVED ON THE     SERVER! * PHP SENDS OUT A “SET-COOKIE” HTTP     HEADER. * BROWSER SAVES A "COLOR=RED"     COOKIE. setcookie("Color", "Red");

SET COOKIE

01

RETRIEVE COOKIE

02

* BROWSER SENDS "COLOR=RED" COOKIE     TO THE SERVER.  * PHP READS AND PARSES COOKIES INTO     THE $_COOKIE SUPERGLOBAL. var_dump($_COOKIE); echo $_COOKIE["Color"];

SETTING ARRAYS

03

SERIALIZE OR JSON ENCODE ARRAY TO STRING FIRST! setcookie("ARRAYA", serialize(["Foo", "Bar"])); setcookie("ARRAYB", json_encode(["Hello", "World"]));

UNSERIALIZE OR JSON DECODE TO GET THE ARRAY BACK $arra = unserialize($_COOKIE["ARRAYA"]); $arrb = json_decode($_COOKIE["ARRAYB"]);

THERE’S NO “DELETE COOKIE” FUNCTION, JUST SET COOKIE EXPIRE DATE TO -1 OR ANYTIME IN THE PAST setcookie("Color", null, -1);

DELETE COOKIE

04