Jump to content

session cookies....


Alidad

Recommended Posts

I have a PHP Yahoo weather script consisting of a form where you input your zip code.  This gets a Yahoo weather xml document which displays on a second page.

 

This works fine, except the user must input his zip code each time he visits the site.  I'd like to customize it so users can enter their zip code once and have their local weather appear whenever they visit the page.

 

 

I have attached the fiels or you to test it, the weather codes is works great, but the session cookies is confused me, can anyone help me please.

 

you can download code thanks.

 

please help thanks.

 

 

 

[attachment deleted by admin]

Link to comment
Share on other sites

Firstly, it'd help if you clarified whether you want to save the zip code for a session (IE. as long as the browser isn't closed) or for an extended period of time (even if the browser IS closed).

 

The former can be accomplished with or without using sessions.

 

The latter can be accomplished without sessions.

 

If you're attempting the former you need to create a session at the start of your PHP script. This is accomplished using:

 

<?php
session_start();
?>

 

This code starts a brand new session if one doesn't exist. If, however, a session was previously started, it grants access to information available in the previous session.

 

When the user firsts submits their zip code, you can save the zip code using something like:

 

<?php
$_SESSION['zip'] = $_GET['zip'];
?>

 

Use something similar to store whether the temperature should be in Celsius or not.

 

You then only need to change your initial check here:

 

<?php if(!isset($_GET['zip'])) { ?>

 

...to also check for the session:

 

<?php if(!isset($_GET['zip']) && !isset($_SESSION['zip'])) { ?>

 

Alternatively, you can have the data last until the browser is closed without even using a session. To do this, create a cookie without an expiration time specified (or specify that time as 0, this will tell the browser to delete the cookie when the browser closes):

 

<?php
setcooke($name, $_GET['zip'], 0);
?>

 

The cookie can then be accessed via $_COOKIE[$name].

 

You can do something similar to save whether they want temperature in Celsius or not. Alternatively, you could use a separator to save all the information in one cookie and then split the string back into an array, but I'm not going to cover that here, you can probably google examples of it if you are interested.

 

PLEASE NOTE: you cannot create a cookie AFTER HTML is sent to the browser, cookies MUST be created before HTML is sent out. There's quite a few ways to prevent the server from sending HTML before you're finished with a process.

 

See: http://php.net/manual/en/book.outcontrol.php

And specifically: http://www.php.net/manual/en/function.ob-start.php

 

If you want to store the zip code for an extended period of time, you can do that using a non-session cookie. Create a cookie the same way as above, but set the expiration using a unix timestamp. You can set a cookie to delete in an hour, for example, by using time()+3600 (current time + 3600 seconds).

 

If you choose to use a cookie this way, you need to create a similar check as I showed above (the modified if statement) but instead of using $_SESSION you'll use $_COOKIE.

 

Whatever solution you choose, you'll need to modify:

 

<?php
$ret = weather($_GET['zip'], ($_GET['u'] == 'c'));
?>

 

To send the correct information to the weather function (as it might actually be stored in $_SESSION or $_COOKIE). One way to do this is to check if one (or the other) is set:

 

<?php
if (!isset($_GET['zip'])) {
   $ret = weather($_SESSION['zip'], ($_SESSION['u'] == 'c'));
}
else {
   $ret = weather($_GET['zip'], ($_GET['u'] == 'c'));
}

 

Replace $_SESSION with $_COOKIE if you do not use a session.

 

[EDIT] Incorrect code in the last example, corrected.

 

Also note, unless you script a way for the user to clear cookies created by your website or you offer them a chance to input a new zip code on the page that displays the weather, a user who inputs a wrong zip code has no way of correcting it until their cookie expires and is deleted.[/EDIT]

Link to comment
Share on other sites

ialsoagree;

 

Hi, first of all i want thanks so much for your help about the session and cookies, i read your comments few times to make sure i understand clear, and then is helped me when i typed your code on my editor instead of copied is helped me to undersand what is going on.

 

however, please see the code after i made change i honestly not sure if this works or not, becuase when i run that page, and enter that zip code then showing weather information, and then i pressed F5 for refreshed same page is loaded same weather information.

 

However, i'm not sure if that really works or not becuase of ($session) i'm still learning.

 

I still need your help PRETTY PLEASE, please see the code and is if that correct session and run to see if that works! i'm using the dreamweaver mx, and i can't tell if this session works in weather code after i executed. 

<?php session_start();?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">*{font-family:verdana,arial,sans-serif;font-size:10pt}</style>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>MyWeather</title>
</head>
<body>
<div>


<?php if(!isset($_GET['zip']) && !isset($_SESSION['zip'])) { ?>
<form method="get" action=""><div>
	Enter a Zip Code: <input name="zip" size="5"/><br/>
	Units: <label><input type="radio" name="u" value="f" checked="checked"/> Farenheit</label>
	<label><input type="radio" name="u" value="c"/> Celsius</label><br/>
  		<input type="submit" value="Submit"/>
</div></form>
<?php
}
else {
include('weather.class.php');
$ret = weather($_GET['zip'], ($_GET['u'] == 'c'));
echo "<table cellpadding=\"2\" cellspacing=\"4\">\n";
echo "\t<tr><td colspan=\"3\"><strong>".$ret[0]['location']."</strong></td></tr>\n";
foreach($ret as $day) {
	echo "\t<tr><td>".$day['when'].'</td><td><img src="i/'.$day['image'].'"/></td><td>'.$day['text'].'<br/>';
	if(isset($day['temp'])) {
		echo $day['temp'].', Windchill: '.$day['windchill'].'<br/>';
		echo 'Wind: '.$day['wind'].'<br/>';
		echo 'Humidity: '.$day['humidity'].'<br/>';
		echo 'Visibility: '.$day['visibility'].'<br/>';
		echo 'Preasure: '.$day['preasure'].'<br/>';
		echo 'Sunrise: '.$day['sunrise'].'<br/>';
		echo 'Sunset: '.$day['sunset'];
	}

	echo "</td></tr>\n";
}
echo "</table>\n";
}
?>

</div>
</body>
</html>

 

thanks so much

Link to comment
Share on other sites

I've read your above code, it appears the changes I proposed are NOT fully implemented.

 

Although you are starting a session, you're not saving the zip code to a $_SESSION array index (such as $_SESSION['zip']). Unless you save the information, it can't be accessed again later.

 

Further, you're not calling your weather function after an appropriate check to see where the zip code information should be coming from.

 

Both of these changes are detailed in my post above, including specific examples of how to do so.

 

It appears that English is not your primary language (although you do type it very well).

 

I would recommend that you go to the PHP website and access the documentation for your native language if this is possible:

http://www.php.net/docs.php

 

Under the category heading of "features" you should find a section on "sessions" (these may be slightly different when translated). This section details the use of sessions if you would like to learn how to implement sessions from a formal source.

Link to comment
Share on other sites

Although I myself would recommend cookies instead of sessions I assume you would prefer sessions. So here is the code.

<?php session_start();?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">*{font-family:verdana,arial,sans-serif;font-size:10pt}</style>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>MyWeather</title>
</head>
<body>
<div>


<?php
if (isset($_GET['zip']) && !empty($_GET['zip']) && isset($_GET['u']) && !empty($_GET['u'])) {
$_SESSION['zip']=(int) $_GET['zip'];
$_SESSION['u']=$_GET['u'];
}
if(!isset($_GET['zip']) && !isset($_SESSION['zip'])) { ?>
<form method="get" action=""><div>
	Enter a Zip Code: <input name="zip" size="5"/><br/>
	Units: <label><input type="radio" name="u" value="f" checked="checked"/> Farenheit</label>
	<label><input type="radio" name="u" value="c"/> Celsius</label><br/>
  		<input type="submit" value="Submit"/>
</div></form>
<?php
}
else {
include('weather.class.php');
$ret = weather($_SESSION['zip'], ($_SESSION['u'] == 'c'));
echo "<table cellpadding=\"2\" cellspacing=\"4\">\n";
echo "\t<tr><td colspan=\"3\"><strong>".$ret[0]['location']."</strong></td></tr>\n";
foreach($ret as $day) {
	echo "\t<tr><td>".$day['when'].'</td><td><img src="i/'.$day['image'].'"/></td><td>'.$day['text'].'<br/>';
	if(isset($day['temp'])) {
		echo $day['temp'].', Windchill: '.$day['windchill'].'<br/>';
		echo 'Wind: '.$day['wind'].'<br/>';
		echo 'Humidity: '.$day['humidity'].'<br/>';
		echo 'Visibility: '.$day['visibility'].'<br/>';
		echo 'Preasure: '.$day['preasure'].'<br/>';
		echo 'Sunrise: '.$day['sunrise'].'<br/>';
		echo 'Sunset: '.$day['sunset'];
	}

	echo "</td></tr>\n";
}
echo "</table>\n";
}
?>

</div>
</body>
</html> 

Link to comment
Share on other sites

cwarn23;

 

thank you for your help, im still learning abou the session and cookies, other member ialsoagree who wrote about the session and cookie and he is helpfull too just like you.

 

Due to my time enemy, i was wondering if there is chance that you can write code in cookie to so i can undersand both side of cookie and session myself to see what does differents thanks.

 

AM

Link to comment
Share on other sites

Although I haven't tested it the following code should work.

<?php //first line
if (isset($_GET['zip']) && !empty($_GET['zip']) && isset($_GET['u']) && !empty($_GET['u'])) {
$zip=(int) $_GET['zip'];
setcookie('sitedata',$zip.'~|~~|~'.$_GET['u'],time()+(60*60*24*365));
}
if (isset($_COOKIE['sitedata'])) {
$cookie=explode('~|~~|~',$_COOKIE['sitedata']);
$cookie['zip']=$cookie[0];
$cookie['u']=$cookie[1];
}
?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">*{font-family:verdana,arial,sans-serif;font-size:10pt}</style>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>MyWeather</title>
</head>
<body>
<div>


<?php

if(!isset($_GET['zip']) && !isset($_COOKIE['sitedata'])) { ?>
<form method="get" action=""><div>
	Enter a Zip Code: <input name="zip" size="5"/><br/>
	Units: <label><input type="radio" name="u" value="f" checked="checked"/> Farenheit</label>
	<label><input type="radio" name="u" value="c"/> Celsius</label><br/>
  		<input type="submit" value="Submit"/>
</div></form>
<?php
}
else {
include('weather.class.php');
$ret = weather($cookie['zip'], ($cookie['u'] == 'c'));
echo "<table cellpadding=\"2\" cellspacing=\"4\">\n";
echo "\t<tr><td colspan=\"3\"><strong>".$ret[0]['location']."</strong></td></tr>\n";
foreach($ret as $day) {
	echo "\t<tr><td>".$day['when'].'</td><td><img src="i/'.$day['image'].'"/></td><td>'.$day['text'].'<br/>';
	if(isset($day['temp'])) {
		echo $day['temp'].', Windchill: '.$day['windchill'].'<br/>';
		echo 'Wind: '.$day['wind'].'<br/>';
		echo 'Humidity: '.$day['humidity'].'<br/>';
		echo 'Visibility: '.$day['visibility'].'<br/>';
		echo 'Preasure: '.$day['preasure'].'<br/>';
		echo 'Sunrise: '.$day['sunrise'].'<br/>';
		echo 'Sunset: '.$day['sunset'];
	}

	echo "</td></tr>\n";
}
echo "</table>\n";
}
?>

</div>
</body>
</html> 

Link to comment
Share on other sites

cwarn23;

 

thanks so much for your help, both way is works great for me, i just made some changed and works great.

 

and now i'm learning both of them to see what does differents between (seesion and cookies). I have learned lots, is amazing.

 

again thanks so much for your help, i appreication.

 

AM

Link to comment
Share on other sites

  • 2 weeks later...

i tried use this code different way by put people who signup the forms in registration.php page or log in in login.php page and then create weathr session cookies by showing on other page such as index.php page.

 

However, I have tried this code by put seprate page, and is not sending any cookie and not showing weather infomration in index.php page after redirect to other page.

 

I have tested weather code to make sure that the weather zip code are sending data but for some reason is not sending. please use testig code as testing and see can anyone help me how to create weather session from two different pages!

 

<?php 

$error_message = 'Welcome!'; 
extract($_POST); //Extract $_POST Array into normal variables, like $zip 

if(isset($zip)){ //form actually entered? 
    if( preg_match( '#^\d{5}$#',  $zip) ){ //valid 5 digits zip? 
        $error_message = 'good'; 
    }else{ 
        $error_message = 'not valid zip code'; 
    } 
     
    if($error_message == 'good'){ 
        //here we get the weather from Yahooo 
        echo 'Get Weather!'; 
         
         
        exit(); //end script after show weather 
    } 
} 
     
?> 
<form method="post" action=""> 
<input type="text" name="zip" maxlength="5"> 
ZIP CODE 5 Digits (like: 12345)<br /> 
<input type="submit" name="zipsubmit" value="GET Weather"> 
</form> 
<?php 
    echo $error_message; 
?> 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.