Cookie headers must be sent before page output.
<?php
setcookie('Plus2netCookie', 'plus2net.com', [
'expires' => time() + 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
?>Secure on HTTPS sites, HttpOnly when JavaScript does not need the cookie, and choose SameSite according to the cross-site behavior your application requires.<form method=post action=cookies_redirect.php>
Enter Your Name <input type=text name=name class='form-control'>
<input type=submit value=Next class='btn btn-danger'>
</form>
Code for page cookies_redirect.php
<?php
$name = trim((string) filter_input(INPUT_POST, 'name', FILTER_UNSAFE_RAW));
if ($name !== '' && mb_strlen($name) <= 80) {
setcookie('Plus2netCookie', $name, [
'expires' => time() + 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
header('Location: cookies_t2.php');
exit;
}
?>
Tutorial on PHP Cookies Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.