PHP Introduction | Page Transitions, Cookies, and Sessions | Basics of Using Cookies

Web applications sometimes need to preserve certain information continuously. For example, if login information is not kept, a page will no longer be able to tell who the user is. Therefore, maintaining user information is very important when writing Web applications.

There are several ways to do this, and the method used to “store information on the Web browser side” is called a “cookie.” A cookie is very small data that can be stored in the browser. Cookies allow each Web site to store small pieces of information in the browser. If data is kept there, it can be retrieved and used as needed.

Cookies cannot store very large data. The point to be careful about is that the number and maximum size of cookies that can be stored differ by browser. As a rough minimum line, the condition of “up to 20 cookies and 4096 bytes per site” is clear in current browsers, so if the amount is below that, there should be no problem. It is not recommended to store large data in cookies. Remember that the browser may not store it.

When using cookies, reading and writing use different approaches, so be careful. First, cookie writing, or saving, uses the function setcookie. It is specified as follows.

setcookie(name, value, expiration date);

The first argument, name, is the name of the cookie to save. You can give it any suitable name. The second argument is the actual value to save. The third argument specifies when the cookie should be discarded. It specifies a timestamp for the deletion time, which is the elapsed seconds from January 1, 1970.

The expiration date can be omitted. If it is omitted or 0 is specified, the cookie is automatically deleted when the browser closes.

Next is loading cookies. This can be read from the associative array $_COOKIE, which is provided by the PHP system. It is written as follows.

$variable = $_COOKIE[cookie name];

You can retrieve a cookie by specifying its name like this. Be careful that changing the value of $_COOKIE does not change the cookie. In other words, you can only read values from it. This is the same as $_POST and similar arrays.

Trying Cookies

Let us look at an example that uses cookies.

<?php
    if ($_POST != null){
        $str = $_POST['text1'];
        setcookie("mycookie",htmlspecialchars($str),time() + 60 * 1);
        header("Location: ./index.php");
    }
?>
<!DOCTYPE html>
<html lang="ko">
    <head> 
        <meta http-equiv="Content-Type"
            content="text/html; charset=UTF-8" /> 
        <title>sample page</title>
    </head>
    <body>
        <h1>Hello PHP!</h1>
        <p>
            <?php
                $cookie = $_COOKIE['mycookie'];
                echo "Cookie information: {$cookie}";
            ?>
        </p>
        <hr>
        <form method="post" action="./index.php">
            <input type="text" name="text1">
            <input type="submit" value="Submit">
        </form>
        <hr>
    </body>
</html>

This example stores the text written in the input field into a cookie. Write anything and submit it. The stored cookie content is displayed in the cookie information area.

Here, saving and loading the cookie are written in different <?php ?> tags. The following part performs the cookie operation.

setcookie("mycookie",htmlspecialchars($str),time() + 60 * 10);

The third argument gets the current timestamp with the time function and adds the number of seconds for 10 minutes. In other words, it sets the cookie to be discarded after 10 minutes. Cookie loading is done as follows.

$cookie = $_COOKIE['mycookie'];

This loads the cookie value. If that cookie has already been deleted, the value becomes null.

There is one point to be careful about when using cookies: at the stage where setcookie is called, the cookie is not yet saved.

Cookies are exchanged using HTTP headers. setcookie actually adds cookie storage information to the header. Therefore, like the header function, it must be called before headers have been output. After headers have been sent, executing setcookie cannot store the cookie.

When cookie information is added to the header by setcookie, it is sent to the browser, and the cookie is created and saved when the browser reads it. After that, when the page of that site is accessed, the browser sends the cookie information to the Web server, and the stored value can be obtained in $_COOKIE.

In other words, when setcookie is executed, the cookie does not exist yet; it can be obtained starting from the next visit. The same applies when changing a cookie value: the change is applied from a later visit.

Looking at the example code above, you can see that after setcookie, the header function is used to move back to the same page. This makes the page revisit itself after saving the cookie, so the cookie can be used immediately.