Search⌘ K

Setting a Cookie

Explore how to set cookies in PHP to store user data such as names, allowing the browser to send this information back with subsequent requests. This lesson helps you understand the setcookie function, response headers, and how cookies maintain user state between pages.

Remembering the user’s name

To make the name available during the following requests, we should set a cookie. This way we can tell the browser to remember the user’s name and send it back to the server when the user makes the next request. Let’s see this in action first. Add the following lines to the beginning of name.php:

PHP
<?php
if (isset($_POST['name'])) {
setcookie('name', $_POST['name']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>

If $_POST['name'] is defined, we know that the user submitted the form. The name they submitted is in this variable: $_POST['name']. We should ...