We help IT Professionals succeed at work.

Using PHP to set a cookie array with 5 variables, then read the cookie on another page

mcgeorge40 asked
Last Modified: 2013-12-13
I have been googling "set cookie array with php" and the information is just so confusing for a beginner.

If anyone can be as specific as possible, I would appreciate it.  The website is www.azwm.com, but of course, the page with my experiment isn't posted yet-- plus it's "server side"

I need to do 2 things:

1.  Using PHP, set a cookie array for the longest possible allowed time-- using the 5 values:
// $city
// $shortstate
// $fullstate
// $country
// $zip

Each variable is assigned a string, of course.

2.  Next, when a page loads, I need to check to see if the above cookie array is there.  If it is, I would populate the same variables (if possible) with the data from the cookie.

If the cookie has not been set, then I need to populate the above 5 variables with my defaults.

Can anyone help?  I thank you in advance.
Watch Question


Oh-- by the way.  If setting 5 different cookies is easier and / or just as good, I would be happy to do that.  I keep getting syntax errors no matter what I seem to try.
Unlock this solution and get a sample of our free trial.
(No credit card required)


It doesn't like the "set cookie" function.  After I get the variable values, I plug them in the cookie just like so:

setcookie('geocookie', "city=$city|shortstate=$shortstate|fullstate=$fullstate|country=$country|zip=$zip", 2147483647);

At this point, I only want to set it.  But I get the following error:

Warning: Cannot modify header information - headers already sent by (output started at /home/geozoodl/public_html/save_user.php:9) in /home/geozoodl/public_html/save_user.php on line 211

Any idea why?

Line 211 is:  

setcookie('geocookie', "city=$city|shortstate=$shortstate|fullstate=$fullstate|country=$country|zip=$zip", 2147483647);

I'm sorry for the confusion!
The error was produced by the output of this file /home/geozoodl/public_html/save_user.php on line 9


That's weird.  This is line 9:

<meta name="keywords" content="geotarget, geotargeting, geo-targeting, geo targeted banner ads, geotargeted banners, geotarget ads, ip targeting, ip location targeting" />

Any ideas?

The setcookie function in php works by sending the cookie data with the headers. If headers have already been sent to the browser, the function returns that error because it's missed the chance to set the cookie.

The fix is to either switch to a javascript cookie-setting implementation, which doesn't rely on headers sent at the time the script is first loaded, or else move the setcookie function ahead of any other output (which can be any html code or an echo or header command, or anything else that produces output).


MasonWolf-- still confused why I cannot set something as simple as a cookie.

I have all of my php code right after the <head> tag.  That's what I should do right?

Here's the code.  Please tell me why I am getting:  

Warning: Cannot modify header information - headers already sent by (output started at /home/geozoodl/public_html/save_user.php:7) in /home/geozoodl/public_html/save_user.php on line 188

(line 188 is the cookie set)

-----  my code ----------


<!--------------- get data ---------------------->


$DatabaseServer = "localhost";
$Username = "geo";
$Password = "geo";
$DatabaseName = "geo";
$link = mysql_connect($DatabaseServer, $Username, $Password) or die('Could not connect: ' . mysql_error());

mysql_select_db($DatabaseName) or die('Could not select database');

if (getenv(HTTP_X_FORWARDED_FOR)) {
      $ip   = getenv('HTTP_X_FORWARD_FOR');
      $host = gethostbyaddr($ip);
    } else {
      $ip   = getenv('REMOTE_ADDR');
      $host = gethostbyaddr($ip);

 $tmp = explode(".", $ip);

            $w = (16777216 * $tmp[0]);
            $x = (65536 * $tmp[1]);
            $y = (256 * $tmp[2]);
            $z = $tmp[3];

<!--- explode and put IP back together again ---------->
$ipno =  $w+ $x + $y + $z;

$query = "SELECT * FROM ipcitylatlongzip WHERE $ipno <= endIpNum AND $ipno >= startIpNum";

$result = mysql_query($query) or die("IP2Location Query Failed");

// Retrieve the recordset (only one)
$row = mysql_fetch_object($result);

//assign variables to field names
$country = $row->country;
$abcountry = $row->countryShort;
$cityname = $row->city;
$countrylong = $row->country;
$zipcode = $row->zipcode;
$fullstate = $row->region;


<!----------------------get form values and set cookie ----------------------------->


if (strlen($_POST['shortstate2']) == 2){$shortstate = $_POST['shortstate2'];}

if($_POST['shortstate2']==""){$shortstate = "$shortdbstate";}else{$shortstate = $_POST['shortstate2'];}

$shortstate = strtoupper($shortstate);

if($_POST['city2']==""){$city = "$cityname";}else{$city = $_POST['city2'];}
//if($_POST['shortstate2']==""){$shortstate = "$shortdbstate";}else{$shortstate = $_POST['shortstate2'];}
if($_POST['countrylong2']==""){$country = "$countrylong";}else{$country = $_POST['countrylong2'];}
if($_POST['zipcode22']==""){$zip = "$zipcode";}else{$zip = $_POST['zipcode22'];}

// ----------------- variable names -----------------------
// $city
// $shortstate
// $fullstate
// $country
// $zip

// insert cookie
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(geocookie, "city=$city|shortstate=$shortstate|fullstate=$fullstate|country=$country|zip=$zip", $Month);


<meta tags here>

I took a couple of things that shouldn't matter...like an array with 50 state names in it.

This has me entirely stalled and I can't make heads or tails of this.  Isn't this basic stuff here?  Ugh!
Thank you in advance.


Oh.  And the page this is all on is save_user.php

No, your "setcookie" method must be before the first <html> tag.


Okay, all of the php code--- that determines the cookie value anyway--- is the first thing on the page.  Before the HTML tag; before the head tag; before everything.

I even changed the cookie into something very simple, with just one value.  I am STILL getting the following:

Warning: Cannot modify header information - headers already sent by (output started at /home/geozoodl/public_html/save_user.php:2) in /home/geozoodl/public_html/save_user.php on line 184

Line 184 is the set cookie function, of course.

I am ready to pull my hair out.  Should this be so difficult?!?  Could I be missing something right in front of my face?


I figured it out.  I had the php broken up into 2 parts.  Like this:
$city = detroit ?>

write cookie ?>


That was it.  Because I broke the code up.  That's the stupidest thing I can imagine for this failing.  But thank you very much!

Yeah, even a blank line counts as starting the output for a page. Weird, I know. Glad you got it working. No problems reading back the array then?


Masonwolf- can I ask you another question about this?  With this code:

$vars = explode('|',$_COOKIE['mycookie']);
foreach($vars AS $value)
       $value = explode('=', $value);

How do I fill the variables, $city, $fullstate, $shortstate, etc?  I don't understand this code; I am sorry.

Thank you in advance.


Oh, and I see you asked me about this very thing (reading the array), just as I was posting my last comment / question.  Thanks a lot for your help; I am so grateful.

$value[0] will contain the name of the variable to be set, and $value[1] will contain the value it should hold.

The line:
$$value[0] = $value[1];

creates a new variable in the name space the is named the same as $value[0]

So, if $value[0] = "city" and $value[1]="Seattle" then a new variable "$city" will be created with the value "Seattle". So you should be able to call your variables just by using their ordinary names. Simple, right?
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.