Create an Array-Style Cookie in PHP
PHP Tutorials PHP Sessions PHP Cookies Create Cookie Array Create related cookie values Bracket notation creates related values that PHP can read as a nested cookie array on the next request.
<?php
$options = [
'expires' => time () + 3600 ,
'path' => '/' ,
'secure' => true ,
'httponly' => true ,
'samesite' => 'Lax' ,
];
setcookie ('Plus2netCookie[name]' , 'Alex' , $options );
setcookie ('Plus2netCookie[city]' , 'Hyderabad' , $options );
?> Cookie settings: Use Secure on HTTPS sites, HttpOnly when JavaScript does not need the cookie, and choose SameSite according to the cross-site behavior your application requires.
← DEMO of adding single data as Cookies
HTML code
<form method =post action =cookies_redirect_array.php >
<div class ='row' > <div class ='col-md-4' >Enter Your Name </div > <div class ='col-md-4' ><input type =text name =name class ='form-control' > </div > </div >
<div class ='row' > <div class ='col-md-4' >City </div > <div class ='col-md-4' ><input type =text name =city class ='form-control' > </div > </div >
<div class ='row' > <div class ='col-md-4' >State </div > <div class ='col-md-4' ><input type =text name =state class ='form-control' > </div > </div >
<div class ='row' > <div class ='col-md-4' >Zip </div > <div class ='col-md-4' ><input type =text name =zip class ='form-control' > </div > </div >
<div class ='row' > <div class ='col-md-4' > </div > <div class ='col-md-4' ><input type =submit value =Next class ='btn btn-danger' > </div > </div >
</form >
Code for page cookies_redirect_array.php
<?php
$name = $_POST ['name' ];
$city = $_POST ['city' ];
$state = $_POST ['state' ];
$zip = $_POST ['zip' ];
if (isset ($name ) and strlen ($name ) > 1 ){
$options = [
'expires' => time () + 3600 ,
'path' => '/' ,
'secure' => true ,
'httponly' => true ,
'samesite' => 'Lax' ,
];
foreach (['name' => $name , 'city' => $city , 'state' => $state , 'zip' => $zip ] as $key => $value ) {
setcookie ("Plus2netCookie[$key]" , $value , $options );
}
header ("Location: cookies_t2_array.php" );
}else {
echo " Input your name first and then click NEXT button
<input type='button' value='Back' onclick='window.history.back()' />" ;
}
?>
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.
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com
✖
We use cookies to improve your browsing experience. . Learn more