#56: Creating a "Welcome Back, Username!" Message with Cookies

One cheap parlor trick that many websites employ is displaying "Welcome back" to returning users. If you tell the site your name, it can greet you by name.

To illustrate one way to do this, here is a script that can store user information in a cookie and display the cookie if available:

<?php
if (isset($_REQUEST["user_name"])) {
    setcookie("stored_user_name", $_REQUEST["user_name"], time() + 604800, "/");
    $_COOKIE["stored_user_name"] = $_REQUEST["user_name"];
}
if (isset($_COOKIE["stored_user_name"])) {
    $user = $_COOKIE["stored_user_name"];
    print "Welcome back, <b>$user</b>!";
} else {
    ?>
    <form method="post">
    User name: <input type="text" name="user_name" />
    </form>
    <?php
}?>

Accessing ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.