Source Code for /public/appendix-samples/remember-my-name.php
<?php
if( isset( $_POST['name'] ) ) {
setcookie( 'name', $_POST['name'], time() + 60 * 60 * 24 * 1 );
header( 'Location: ' . $_SERVER['REQUEST_URI'] );
die();
}
$has_name = isset( $_COOKIE['name'] );
$name = $has_name ? $_COOKIE['name'] : 'Stranger';
?>
<h1>Hello, <?php echo htmlspecialchars( $name ); ?>!</h1>
<p>
Welcome to my website.
<a href="/demo-harness.php?file=public/appendix-samples/remember-my-name-here-too.php">I made a second page</a>
which will also address you by name; take a look!
</p>
<h2>What's your name?</h2>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<label for="name">Name:</label>
<input type="text" id="name" name="name" autofocus
<?php if( $has_name ) { echo 'value="' . htmlspecialchars( $name ) . '"'; } ?>
>
<button type="submit">👋 Hi!</button>
</form>