Here's an idea, hope it helps...
<?php
// this must be called before ANY output!
function set_zip($value) {
global $error;
// set cookie and set $error if if fails
if($value && setcookie('zip',$value)) {
return true;
}
$error = 'Error: cookie not set';
return false;
}
function is_zip($value) {
// filter untrusted variable (good habit to get in to)
preg_match("/([0-9]{5}-{0,1}[0-9]{0,4})/",$value,$match);
$zip = $match[1];
if($zip) {
return $zip;
} else {
return false;
}
}
// init variables
$ask_for_zip = false;
$zip = false;
// is cookie set?
if($_COOKIE['zip']) {
// check if cookie is valid zip code and assign to $zip
$zip = is_zip($_COOKIE['zip']);
// zip value sent to script?
} else if($_GET['zip']) {
$zip = is_zip($_GET['zip']);
set_zip($zip); // you can check this, ie if(set_zip($zip)), to see if it worked or not
// must ask for zip
} else {
$ask_for_zip = true;
}
?>
<html>
<head>
<title>sample script</title>
<script language="javascript">
<!--
function get_zip() {
var zip = window.prompt("Please enter your zip code");
var sendTo = eval("'<?php print $_SERVER['PHP_SELF'] ?>?zip=' + zip");
if(sendTo) {
location.href = sendTo;
}
return false;
}
// -->
</script>
<body<?php if($ask_for_zip) { print " onload='get_zip();'"; } ?>>
<?php
printf("The zip code is %s",
$zip
);
?>
</body>
</html>