Problem with Session Variables

I have a form that submits to itself using sessions and a captcha image but for some reason, the sessions variable ‘captcha’ is not being retained through the submit. I’ve included the code below and it’s all just blurring together on me now. I can enter the code correctly a hundred times but because the captcha variable is not retaining, it echos back that the code is incorrect. Please help!

The pertinent code is near the bottom.

	if (!isset($_REQUEST['id'])) {
	} else {
		include_once "../config/config.php";
		$id = $_REQUEST['id'];
		$query = "SELECT * from tbl_properties WHERE p_mls = '".$id."'";
		$result = mysql_query($query);
		// retrieve values
		$p_mls = trim(mysql_result($result,0,"p_mls"));
		$p_price = trim(mysql_result($result,0,"p_price"));
		$p_lease = trim(mysql_result($result,0,"p_lease"));
			// 0 = For Sale Only
			// 1 = For Sale and Lease
			// 2 = For Lease Only
		$p_leaseprice = trim(mysql_result($result,0,"p_leaseprice"));
		$p_address = trim(mysql_result($result,0,"p_address"));
		$p_city = trim(mysql_result($result,0,"p_city"));
		$p_zip = trim(mysql_result($result,0,"p_zip"));
		$p_lattitude = trim(mysql_result($result,0,"p_lattitude"));
		$p_longitude = trim(mysql_result($result,0,"p_longitude"));
		$p_bedrooms = trim(mysql_result($result,0,"p_bedrooms"));
		$p_fullbaths = trim(mysql_result($result,0,"p_fullbaths"));
		$p_halfbaths = trim(mysql_result($result,0,"p_halfbaths"));
		$p_gspaces = trim(mysql_result($result,0,"p_gspaces"));
		$p_gtype = trim(mysql_result($result,0,"p_gtype"));
		$p_stories = trim(mysql_result($result,0,"p_stories"));
		$p_yearbuilt = trim(mysql_result($result,0,"p_yearbuilt"));
		$p_sqft = number_format(trim(mysql_result($result,0,"p_sqft")));
		$p_lotsize = number_format(trim(mysql_result($result,0,"p_lotsize")));
		$p_subdivision = trim(mysql_result($result,0,"p_subdivision"));
		$p_blurb = trim(mysql_result($result,0,"p_blurb"));
		$p_keywords = trim(mysql_result($result,0,"p_keywords"));
		$p_desc = trim(mysql_result($result,0,"p_desc"));
		$p_district = trim(mysql_result($result,0,"p_district"));
		$p_elem = trim(mysql_result($result,0,"p_elem"));
		$p_middle = trim(mysql_result($result,0,"p_middle"));
		$p_high = trim(mysql_result($result,0,"p_high"));
		$p_pool = trim(mysql_result($result,0,"p_pool"));
		$p_spa = trim(mysql_result($result,0,"p_spa"));
		$p_views = trim(mysql_result($result,0,"p_views"));

		// process values
		switch ($p_gtype) {
			case 1: $p_gtype = "Attached"; break;
			case 2: $p_gtype = "Detached"; break;
			case 3: $p_gtype = "Open Spaces"; break;
			case 4: $p_gtype = "Carport"; break;
			case 5: $p_gtype = "Parking Garage"; break;
			case 6: $p_gtype = "Other"; break;

		$cmquery = "SELECT comm_name, taxrate, hoadues FROM tbl_communities WHERE comm_id = ".$p_subdivision;
		$cmresult = mysql_query($cmquery);
		$p_comm = trim(mysql_result($cmresult,0,"comm_name"));

		$equery = "SELECT school_name,school_lat,school_lon FROM tbl_schools WHERE school_id = ".$p_elem;
		$eresult = mysql_query($equery);
		$p_elem = trim(mysql_result($eresult,0,"school_name"));
		$elem_lat = trim(mysql_result($eresult,0,"school_lat"));
		$elem_lon = trim(mysql_result($eresult,0,"school_lon"));

		$mquery = "SELECT school_name,school_lat,school_lon FROM tbl_schools WHERE school_id = ".$p_middle;
		$mresult = mysql_query($mquery);
		$p_middle = trim(mysql_result($mresult,0,"school_name"));
		$middle_lat = trim(mysql_result($mresult,0,"school_lat"));
		$middle_lon = trim(mysql_result($mresult,0,"school_lon"));

		$hquery = "SELECT school_name,school_lat,school_lon FROM tbl_schools WHERE school_id = ".$p_high;
		$hresult = mysql_query($hquery);
		$p_high = trim(mysql_result($hresult,0,"school_name"));
		$high_lat = trim(mysql_result($hresult,0,"school_lat"));
		$high_lon = trim(mysql_result($hresult,0,"school_lon"));

		switch ($p_pool) {
			case 1: $p_pool = "In Ground Pool"; break;
			case 2: $p_pool = "Above Ground Pool"; break;
			case 3: $p_pool = "Neighborhood Pool Only"; break;
			case 4: $p_pool = "Private Club Pool"; break;
			case 5: $p_pool = "No Pool"; break;

		switch ($p_spa) {
			case 1: $p_spa = "In Ground Spa"; break;
			case 2: $p_spa = "Above Ground Spa"; break;
			case 3: $p_spa = "Neighborhood Spa Only"; break;
			case 4: $p_spa = "Private Club Spa"; break;
			case 5: $p_spa = "No Spa"; break;
		switch ($p_lease) {
			case 0:
				$displayprice = "$".number_format($p_price);
			case 1:
				$displayprice = "$ ".number_format($p_price)." or $".number_format($p_leaseprice)." / month";
			case 2:
				$displayprice = "$".number_format($p_leaseprice)." / month";
		if ($p_gspaces > 0) { 
			$displaygarage = $p_gspaces." Car ".$p_gtype;
		} else {
			$displaygarage = "None";

	// Include WordPress 
	define('WP_USE_THEMES', false);

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">

<html xmlns=""
	<head profile="">
		<title><?php echo $p_address.", ".$p_city.", Texas  ".$p_zip;?></title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta name="robots" content="index, follow" />
		<meta name="description" content="<?php echo $p_blurb;?>" />
		<meta name="keywords" content="<?php echo $p_keywords;?>" />
		<link href="../config/styles.css" rel="stylesheet" type="text/css" media="all" />
		<link href="../config/effects.css" rel="stylesheet" type="text/css" media="all" />
		<link href="../config/shadowbox.css" rel="stylesheet" type="text/css" media="all" />

		<!--[if IE 6]>
			<script src="../config/pngfix.js" type="text/javascript"></script>
			<script src="../config/menu.js" type="text/javascript"></script>
			<link href="../config/ie6.css" rel="stylesheet" type="text/css"  media="all"  />
		<!--[if IE 7]>
			<link href="../config/ie7.css" rel="stylesheet" type="text/css"  media="all"  />
		<!--[if IE 8]>
			<link href="../config/ie8.css" rel="stylesheet" type="text/css"  media="all"  />
		<style type="text/css">
			* { }
			label { width: 10em; float: left; }
			label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
			.submit { margin-left: 12em; }
			em { font-weight: bold; padding-right: 1em; vertical-align: top; }
		<script type="text/javascript" src="../config/cufon-yui.js"></script>
		<script type="text/javascript" src="../config/Museo_Slab.font.js"></script>
		<script type="text/javascript" src="../config/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="../config/jquery.tweetable.js"></script>
		<script type="text/javascript" src="../config/shadowbox.js"></script>
		<script type="text/javascript" src=""></script>
		<script type="text/javascript" src="../config/jquery.validate.js"></script>
		<script type="text/javascript">
			function initialize() {
				var myLatlng = new google.maps.LatLng(<?php echo $p_lattitude;?>,<?php echo $p_longitude;?>);
				var myOptions = {
					zoom: 13,
					scrollwheel: false,
					center: myLatlng,
					mapTypeId: google.maps.MapTypeId.ROADMAP
			var map = new google.maps.Map(document.getElementById("prop_canvas"), myOptions);
			var image0 = '../images/pin.png';
 			var latlon0 = new google.maps.LatLng(<?php echo $p_lattitude;?>,<?php echo $p_longitude;?>);
    		var marker0 = new google.maps.Marker({ position: latlon0, map: map, icon: image0, title: '<?php echo $p_address;?>' }); 

			var image1 = '../images/school_ico.png';
 			var latlon1 = new google.maps.LatLng(<?php echo $elem_lat;?>,<?php echo $elem_lon;?>);
    		var marker1 = new google.maps.Marker({ position: latlon1, map: map, icon: image1, title: '<?php echo $p_elem;?> Elementary' }); 
 			var latlon2 = new google.maps.LatLng(<?php echo $middle_lat;?>,<?php echo $middle_lon;?>);
    		var marker2 = new google.maps.Marker({ position: latlon2, map: map, icon: image1, title: '<?php echo $p_middle;?> Junior High' }); 
 			var latlon3 = new google.maps.LatLng(<?php echo $high_lat;?>,<?php echo $high_lon;?>);
    		var marker3 = new google.maps.Marker({ position: latlon3, map: map, icon: image1, title: '<?php echo $p_high;?> High School' }); 


		<script type="text/javascript">

			$('#tweets').tweetable({username: 'bvre', time: true, limit: 3});
			    overlayOpacity:		.7


	<body onload="initialize()">
		<div id="wrapper">
			<div id="header">
				<div class="col-full">
					<div id="logo">
						<a href="/" title=""><img src="../images/logo.png" alt="At Home in Katy" /></a>
						<h1 class="site-title"><a href="/">At Home in Katy</a></h1>
					<div id="account-nav">
							<li>Welcome, Brian.</li>
						<div class="fix"></div>
						<div id="search">
							<?php include_once "../i_netbar.php";?>
				<div class="fix"></div>
				<div id="navigation" class="col-full">
					<div id="nav-home" class="fl">
						<a href="../"><img src="../images/home.png" alt="Homepage" /></a>
					<ul id="main-nav" class="nav fl">
						<li><a href="../blogpress/" title="Blog">Blog</a></li>
						<li class="current_page_item"><a href="./" title="Listings">Listings</a></li>
						<li><a href="../communities/" title="Communities">Communities</a></li>
						<li><a href="../buyers/" title="Buyers">Buyers</a></li>
						<li><a href="../sellers/" title="Sellers">Sellers</a></li>
						<li><a href="../investors/" title="Investors">Investors</a></li>
						<li><a href="../reo/" title="REO">REO</a></li>
						<li><a href="../joinkw/" title="Join KW">Join KW</a></li>
						<li><a href="../reports/" title="Free Reports">Free Reports</a></li>
						<li><a href="../aboutus.php" title="About Us">About Us</a></li>
					<div class="fix"></div>
		<div id="main_body">
			<div id="container" class="col-full">
				<div id="content" class="col-full">
					<div id="page" class="about-us">
						<div id="main" class="col-right">
							<div id="breadcrumb" class="col-right">
								<span class="trail"><a href="../">Home</a></span>
								<span class="trail"><a href="./">Featured Listings</a></span>
								<strong><?php echo $p_address;?></strong>
							<div class="fix"></div>
							<img src="../photos/<?php echo $p_mls;?>.jpg" width="710" height="300" alt="<?php echo $p_address;?>" />
								<h1><?php echo $p_address;?></h1>
							<div class="content">
								<div class="contentsub1">
									<h2>About This Property</h2>
									<?php echo $p_desc;?>
								<div class="contentsub2">
									<h2>Property Map</h2>
									<div id="prop_canvas"></div>
								<div class="fix"></div>
								<h2>Property Photos</h2>
								<div id="gallery">
										$p = 0;
										$total = 15;
										while ($p <= $total ) {
											echo "<a href=\\"../photos/".$p_mls."_".$p.".jpg\\" rel=\\"lightbox[props]\\" title=\\"".$p_address."\\">";
											echo "<img class=\\"thumb\\" src=\\"../photos/".$p_mls."_".$p."_t.jpg\\" width=\\"75\\" height=\\"53\\" alt=\\"".$p_address."\\" border=\\"0\\" /></a>";
								<hr class="divide" />

								<div id="fb-root"></div><script src=";xfbml=1"></script><fb:comments numposts="3" width="710" publish_feed="true"></fb:comments>
							<div class="fix"></div>
							<hr class="divide" />

							<div class="disclaimer"> 
								The information above has been obtained from sources believed reliable. While we do not doubt its accuracy we 
								have not verified it and make no guarantee, warranty or representation about it. It is your responsibility 
								to independently confirm its accuracy and completeness. Any projections, opinions, assumptions, or estimates 
								used are for example only and do not represent the current or future performance of the property. The value 
								of this transaction to you depends on tax and other factors which should be evaluated by your tax, 
								financial, and legal advisors. You and your advisors should conduct a careful, independent investigation 
								of the property to determine to your satisfaction the suitability of the property for your needs.  
								Information presented herein is subject to change without notice.

					<!-- /#main -->
					<div id="sidebar" class="col-left">
						<div class="primary">
							<div class="widget">
								<h3>The Details</h3>
									<li class="priceico"><a name="price"><?php echo $displayprice;?></a></li>
									<li class="houseico"><a name="subdivision"><?php echo $p_comm;?></a></li>
									<li class="bedico"><a name="bedrooms"><?php echo $p_bedrooms;?> Bedrooms</a></li>
									<li class="bathico"><a name="bathrooms"><?php echo $p_fullbaths."/".$p_halfbaths;?> Bathrooms</a></li>
									<li class="carico"><a name="garage"><?php echo $displaygarage;?></a></li>
									<li class="testico"><a name="stories"><?php echo $p_stories;?> Story</a></li>
									<li class="histico"><a name="yearbuilt">Built in <?php echo $p_yearbuilt;?></a></li>
									<li class="sfico"><a name="sqft"><?php echo $p_sqft;?> Sq. Ft.</a></li>
									<li class="sfico"><a name="lotsize"><?php echo $p_lotsize;?> Sq. Ft. Lot</a></li>
									<li class="poolico"><a name="pool"><?php echo $p_pool;?></a></li>
									<li class="poolico"><a name="spa"><?php echo $p_spa;?></a></li>
						<div class="primary">
							<div class="widget">
								<h3>Send Info</h3>
									if (isset($_POST["propid"])) {
									echo "S:".$_SESSION['captcha'];
						   				if(($_SESSION["captcha"] == $_GET["seccode"]) && (!empty($_SESSION["captcha"])) ) {
											// retrieve entered values
											$name = trim($_POST["name"]);
											$phone = $_POST["phone"];
											$email = trim($_POST["email"]);
											$property = trim($_POST["propid"]);
											$stamp = time();
											// add to database
											$sql = "INSERT INTO tbl_requests SET
												name = '$name',
												phone = '$phone',
												email = '$email',
												type = 1,
												property = $property,
												timestamp = $stamp";
											$result = mysql_query($sql);
											if (!$result) { // if a database error occurs stop
							  					error("A error occurred while logging your request. ".
If this error persists, please ".
												"contact $admin_email.");
											} else { // otherwise - send the request email
												echo "<p>The information you requested has been sent!  You should receive it shortly at the email address you supplied.</p>";
						   				} else {
						      					echo "<p>The security code (".$_POST['seccode'].") you entered does match code provided (".$_SESSION['captcha'].").</p>";
												echo "<p><a href=\\"#\\" title=\\"Go Back\\" onclick=\\"history.go(-1)\\">&laquo; Go Back and Try 
									} else {

								<p class="sendcap">Send me more information about this property right now:</p>
								<form id="myform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
										<input class="sideinput required" style="background: #FFFFFF url(../images/name_bg.gif) right center no-repeat;" type="text" name="name" id="name" value="" /> 
										<input class="sideinput required phoneUS" style="background: #FFFFFF url(../images/phone_bg.gif) right center no-repeat;" type="text" name="phone" id="phone" value="" /> 
										<input class="sideinput required email" style="background: #FFFFFF url(../images/email_bg.gif) right center no-repeat;" type="text" name="email" id="email" value="" /> 
										<input class="captcha required" type="text" name="seccode" />
										<img alt="Captcha" src="../config/smallcaptcha.php" style="vertical-align: middle"/> 

										<input type="hidden" name="propid" value="<?php echo $p_mls;?>" />
										<button type="submit" style="margin-left: 5px;" class="positive" name="save">Send Now!</button>
						<?php include_once "../i_join.php";?>

						<div class="primary">
							<div class="widget">
								<a rel="shadowbox;width=480;height=345;player=swf" class="postimg" title="Property Tour" href=";hl=en_US&amp;fs=1&amp;rel=0&amp;autoplay=1">
								<img src="../photos/<?php echo $p_mls;?>_0.jpg" alt="Property Tour" title="Property Tour" width="148" /></a>

					<div class="fix"></div>
	<?php include_once "../i_footer.php";?>

Isolate the code which is causing the problem.

Create a test case which fails every time, which contains the absolute minimum of html markup, dont put things into a database, just echo them onto the page.

Tell us what it does echo to the page, tell us what you want it to echo to the page.

Post the code and your expectations here.

In my experience, in the majority of cases following this normal debugging procedure will help you turn up the problem on your own - and when you start thinking like that you will also develop in small incremental steps too.

Here’s the funny thing… when I isolate just the specific code that does this, it works: ala here:

And when I move the session_start(); statement to just before before the if/then statement in the real document, it works although it gives me the ‘headers already sent’ error.

When the ‘session_start’ is at the top of the page, it doesn’t work. Could the fact that this form is on a page that also returns database values be interfering? I’m still at a loss despite at least a little bit of sleep.

Good on you, nothing must be output to the browser prior to sending any headers, not even a space.

Another trick to try and adopt is to do var_dump() on any variable upon which you are doing a conditional check, like when your code forks.

This often reveals that what you think a variable state is, has been interpreted differently by PHP and then your conditional simply does not work.

eg do a var_dump( $_REQUEST[‘id’] );

if that turns out to be:

boolean false;

then you could make sure you are checking like for like with

if( $_REQUEST[‘id’] === false ) {
// now you know you are not losing your sanity

heres and oldie but goodie:

and type testing is covered in the manual here:

The $_REQUEST[‘id’] portion of this page is not in question - that all works beautifully - the only portion of this that fails is this form.

Although $_SESSION[‘captcha’] is being set on original page load, when the page is submitted to itself (and subsequently processed) - the $_SESSION[‘captcha’] variable goes blank and hence the comparison fails.

thanks for your help thus far!
my brain hurts.

OK - i narrowed down my problem to the Wordpress connection:

// Include WordPress 
define('WP_USE_THEMES', false);

Take this out and it works fine. Leave it in - no dice. Session variable goes by by.
Googled the problem and tried the fixes - but still nada.

Any ideas?


I am not posting solutions for you as you can tell, because there is clearly so much going on, I am just trying to help you debug what you have.

This may not be your case, but, a frequent cause of the dreaded ‘headers already sent’ message is that somewhere you are throwing an error such as a Notice or Warning.

Turning off error reporting may solve this temporarily, but really you should find the error and fix it. How about you take a look in your php error log?