Cookie:入力されたIDを次回アクセスまで覚える



《HTML》

<?php
if (isset($_COOKIE['my_id'])) {
	$myId = $_COOKIE['my_id'];
} else {
	$myId = '';
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>入力されたIDを次回アクセス時まで覚える</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrap">
<div id="head">
<h1>入力されたIDを次回アクセス時まで覚える</h1>
</div>
<div id="content">
<form action="sample17.php" method="post">
<dl>
<dt>ID</dt>
<dd><input type="text" name="my_id" id="my_id" value="<?php echo $myId; ?>"></dd>
<dt>パスワード</dt>
<dd><input type="password" name="password" id="password"></dd>
<dt>IDの保存</dt>
</dl>
<p><input type="checkbox" name="save" id="save" value="on"><label for="save">IDを保存する</label></p>
<input type="submit" value="送信する">
</form>
</div>
</div>
</body>
</html>


PHP

<?php
$myId = $_POST['my_id'];
$password = $_POST['password'];
$save = $_POST['save'];

// Cookieに保存
if ($save == 'on') {
	setcookie('my_id', $myId, time() + 60 * 60 * 24 * 14);
	$message = 'ログイン情報を記録しました';
} else {
	setcookie('my_id');
	$message = '記録しませんでした';
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>入力されたIDを次回アクセス時まで覚える</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrap">
<div id="head">
<h1>入力されたIDを次回アクセス時まで覚える</h1>
</div>
<div id="content">
<p style="margin-top: 200px">
<p><?php echo $message; ?></p>
<p><a href="./sample17_input.php">戻る</a></p>
</p>
</div>
</div>
</body>
</html>