?
Solved

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

Posted on 2007-09-28
15
Medium Priority
?
337 Views
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.
0
Comment
Question by:mcgeorge40
  • 9
  • 5
15 Comments
 

Author Comment

by:mcgeorge40
ID: 19982753
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.
0
 
LVL 13

Accepted Solution

by:
MasonWolf earned 2000 total points
ID: 19982939
Ok, I think this is doable. You basically need to write 2 functions. The first sets your cookie, and the second interprets your cookie.

First, setting your cookie:

setcookie('mycookie', "city=$city|shortstate=$shortstate|fullstate=$fullstate|country=$country|zip=$zip", 2147483647);
//2147483647 is the maximum value that can be contained by a 32 bit signed integer - it's equivalent to the date Jan 18 or 19 (depending on time zone), 2038
 
Now, to read your cookie, use this code:

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

Author Comment

by:mcgeorge40
ID: 19983094
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!
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 5

Expert Comment

by:administradores
ID: 19983660
The error was produced by the output of this file /home/geozoodl/public_html/save_user.php on line 9
0
 

Author Comment

by:mcgeorge40
ID: 19984707
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?
0
 
LVL 13

Expert Comment

by:MasonWolf
ID: 19984722
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).
0
 

Author Comment

by:mcgeorge40
ID: 19984829
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 ----------


html>

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


<?php

$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 ----------------------------->


<?php







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>
</head>

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.
0
 

Author Comment

by:mcgeorge40
ID: 19984840
Oh.  And the page this is all on is save_user.php
0
 
LVL 13

Expert Comment

by:MasonWolf
ID: 19984889
No, your "setcookie" method must be before the first <html> tag.
0
 

Author Comment

by:mcgeorge40
ID: 19984939
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?
0
 

Author Comment

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

<?php
write cookie ?>

<html><head>

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!
0
 
LVL 13

Expert Comment

by:MasonWolf
ID: 19985042
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?
0
 

Author Comment

by:mcgeorge40
ID: 19985067
Masonwolf- can I ask you another question about this?  With this code:

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

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

Thank you in advance.
0
 

Author Comment

by:mcgeorge40
ID: 19985106
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.
0
 
LVL 13

Expert Comment

by:MasonWolf
ID: 19985422
$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?
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
The viewer will learn how to count occurrences of each item in an array.
Use Wufoo, an online form creation tool, to make powerful forms. Learn how to choose which pages of your form are visible to your users based on their inputs. The page rules feature provides you with an opportunity to create if:then statements for y…
Suggested Courses
Course of the Month15 days, 16 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question