PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How do I use cookies with Foreach

 November 14, 2022     cookies, foreach, php     No comments   

Issue

I adopted code given in this code: https://www.w3schools.com/php/php_cookies.asp and How do I use cookies to store users' recent site history(PHP)?

and i changed the code with the link above

Example: user clicks on url

file.php?id=200&value=woman
file.php?id=150&value=woman
file.php?id=250&value=girl 

and this code is here:

$id = $_GET['id'];
$value = $_GET['value'];
$cookie_id = $id;
$cookie_value = $value ;
setcookie($cookie_id, $cookie_value, time() + (86400 * 30), "/");
if(isset($_COOKIE[$cookie_id])) {
    foreach ($_COOKIE[$cookie_id] as $cookie_id => $value) { 
        echo 'id: '.$cookie_id.' '; echo ', value: '.$cookie_id.' <br>'; 
    }
} else {
    echo 'Cookie named '.$cookie_id.' is not set!';
}

Out: the output of the code above should be as follows

id: 200, value: woman
id: 150, value: woman
id: 250, value: girl

Error: this error shows me this way.

Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/cookie.php on line 7

and also I found this code Foreach loop with cookies , but failed:

What could be the reason and what am I doing wrong?


Solution

Remove [$cookie_id] from $_COOKIE[$cookie_id]. Don't name index in foreach loop as prev variable name - $cookie_id. Name it as $ind=>$val. For debugging make print_r($_COOKIE); before loop and you'll see with what you can work further.



Answered By - mohsen
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing