An Overview of the PHP setcookie() Function

php setcookiePHP was made to facilitate server-side programming for web developers. Initially, it was known as the Personal Home Page; however, the recursive acronym PHP Hypertext Pre-processor stuck later. The power of PHP lies in its simplicity. It provides a clear and concise programming interface to either construct web pages or standalone web applications.

Another very interesting feature of PHP is that it converts all the PHP code to HTML when it is rendered by the browser. PHP can be thought of as a set of directives for an HTML parser, informing it of data that must be fetched from the server and then displayed on the browser.

Learn PHP programming from scratch through a course at Udemy.com

Cookies are necessary for modern browsers, because they help preserve data that is needed by some websites for customized information. This can be a basic email client such as Hotmail that fetches email specific to a user who has logged in.

It’s tiresome if you have to enter your username and password every time you want to access your mail. Therefore, it’s easier to store usernames and passwords for future visits in a cookie. The information is textual and is stored in files with a .cookie extension. These files are saved by the browser and retrieved when needed.

To jump right into PHP cookies, you need to know to know a little bit about PHP coding.  We will begin with the syntax for the setcookie() function in PHP and then start off with a little programming so that you can understand its use better.

Syntax

setcookie(name, value, expire, path, domain, security);

The arguments or the parameters for the setcookie() function are:

  • Name – The name of the cookie that will be later saved in an environmental variable called HTTP_COOKIE_VARS. HTTP_COOKIE_VARS is an array from which the cookies can be retrieved.
  • Value – Since cookies are textual files, the value should be a series of alphanumeric characters such as numbers or letters. E.g. 17625, 10/09/89, alpha123, etc.
  • Expire – Sets the expiry date of the cookie in seconds. This is necessary since cookies are temporary files that are needed only during a specific session. If this parameter is not set, then the cookie will expire after the browser is closed and cannot be accessed unless the setcookie() function is used again. E.g. 3600.
  • Path – This is the path to the directory or directories for which the cookie will be valid. This ensures that the cookies are not misused. If a single forward slash is used for this parameter, then it indicates that the cookie is valid in all directories of the web server. E.g. /bin/src or simply /
  • Domain – For very large websites encompassing various departments or organizations, the domain name ensures consistency and location transparency. E.g. www.google.com, outer.inner.sources, etc.
  • Security –Setting this parameter as 1 tells the browser to retrieve cookies using secure HTTPS. If it is set as 0, it will use HTTP.

New to PHP? Learn the basics at Udemy.com

Examples

The syntax of the setcookie() function can be understood better with the following example:

<?php
   setcookie("name", "Robert", time()+1800, "/","", 0);
   setcookie("age", "24", time()+1800, "/", "",  0);
print “<html>”;
print “<head>”;
print “<title>Cookies in PHP</title>”;
print “</head>”;
print “<body>”;
print “Name and Age SET”;
print “</body>”;
print “</html>”;
?>

The following is an explanation for the above code:

  1. PHP code should always be enclosed between “<?php” and “?>” even if it is a separate PHP file you are creating.
  2. The setcookie() function follows the standard syntax and has the following parameters:
  • Name – name, age
  • Value – Robert, 24
  • Expiry – time() + 1800, which essentially means that the cookie is valid for half an hour from the current system time
  • Path – / (valid in all directories of the web server)
  • Domain – [default], which uses the current host and domain name
  • Security – 0 (indicating HTTP transmission without security)
  • It is important to observe that the setcookie() function is called before any HTML code is written
  • The body of the HTML code has a single PHP statement which prints “Name and Age SET” on the browser window

Even though the code above creates a cookie, it does nothing since you haven’t used the cookies. Now, let’s see how this can be done as well:

<?php
   setcookie("name", "Robert", time()+1800, "/","", 0);
   setcookie("age", "24", time()+1800, "/", "",  0);
print “<html>”;
print “<head>”;
print “<title>Using Cookies in PHP</title>”;
print “</head>”;
print “<body>”;
print “Name and Age SET”;
print “Name is “;
print $_COOKIE["name"]."<br />";
print “Age is ”;
print $_COOKIE["age"]."<br />";
print “</body>”;
print “</html>”;
?>

Now, what the code above does is:

  1. Sets the “name” and “age” cookies with specific values like “Robert” and “24” respectively
  2. Prints “Name and Age SET” on the browser window
  3. Goes ahead with more PHP code and prints “Name is Robert” and then on the next line “Age is 24”
  4. The cookies are accessed using an environmental variable $_COOKIE[]:
  • An environmental variable is set when the browser starts a new session for a client
  • The environmental variables are used by the browser for internal functions such as detecting the platform of the client, whether it supports Flash, whether the client has ever visited the site, etc.
  • Cookies can be accessed either using the environmental variable $_COOKIE[“name_of_cookie”] or $HTTP_COOKIE_VARS[“name_of_cookie”]
  • The value of the cookie can be used directly using the syntax above or saved in a variable for later use.

Take a course at Udemy.com and get a better understanding of the PHP programming language.

Conclusion

PHP is a language that was developed to keep the average programmer in mind – someone who has basic knowledge about web programming but a very good knowledge about general programming. The setcookie() function is useful when you need to store values when the user returns to a website. Use this example code when you want to allow your users to store values such as a login account name, preferences for site layout and the last time the user visited your site.