PHP Reference

Quick Reference

The PHP setcookie() function defines a cookie to be sent along with the rest of the HTTP headers.

<!DOCTYPE html>
<?php
$cookie_name = 'user';
$cookie_value = 'Johnny Shay';
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
    echo "The cookie named '" . $cookie_name . "' is not set!";
}
else {
    echo "The cookie '" . $cookie_name . "' is set!<br>";
    echo "The value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Syntax

setcookie(name, value, expire, path, domain, secure, httponly)

Parameters

ParameterDescription
nameSpecifies the name of the cookie (required)
valueSpecifies the value of the cookie
expireSpecifies when the cookie expires; the value, time()+86400*30, will set the cookie to expire in 30 days; if this parameter is omitted or set to 0, the cookie will expire at the end of the session, when the browser closes (default is 0)
pathSpecifies the server path of the cookie; if set to "/", the cookie will be available within the entire domain; if set to "/php/", the cookie will only be available within the php directory and all sub-directories of php (the default value is the current directory that the cookie is being set in)
domainSpecifies the domain name of the cookie; to make the cookie available on all subdomains of example.com, set domain to "example.com"; setting it to www.example.com will make the cookie only available in the www subdomain
secureSpecifies whether or not the cookie should only be transmitted over a secure HTTPS connection; TRUE indicates that the cookie will only be set if a secure connection exists (default is FALSE)
httponlyIf set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages); this setting can help to reduce identity theft through XSS attacks (default is FALSE)

PHP Notes:

  • When using PHP, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent
  • Arrays count starting from zero NOT one; so item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.