Hey guys,

I got a problem with the value of the variable, which is not somehow lost when its value is passed through several pages

So basically in Step One the user first enters a value for the variable in a form, in this case it's "promoter", then the form is submitted, then it proceeds to Step Two, in which the user selects a few options and proceed to Step Three, which is the last step. Since this is just for an illustration of the problem, I emphasize on variable "promoter". But on the page of the last step (Step Three), the value of "promoter" is echoed out, but nothing is shown. So I am assuming its value is lost during these steps.

The following is the excerpts from Step One to Step Three, with emphasis on variable "promoter":

<?php

//Step One

//Database Credentials
include "../db_fns.php";

//Menu Functions
include "../menu_fns.php";

//User Functions
include "../user_fns.php";
session_start();

//link fns
include "../links_fns_2.php";
include "../specificities_fns_2.php";
// Make Session / Session Variables.
session_start();

//Database connection
$conn = db_connect_2();

if (isset($_SESSION['link']) AND !isset($_POST['Submit'])){
//retrieve link
if(is_string($_SESSION['link'])){
$link = unserialize($_SESSION['link']);
} else {
$link = $_SESSION['link'];
}

if($link){
$_SESSION['promoter_locus'] = $link->promoter;
}

$_POST = $_SESSION;
}elseif (isset($_POST['Submit'])) {

if(isset($_SESSION['link'])) {
//we need to unserialize the link
if(is_string($_SESSION['link'])){
$link = unserialize($_SESSION['link']);
} else {
$link = $_SESSION['link'];
}
}

//put $_POST variables into $_SESSION
$_SESSION = $_POST + $_SESSION;
unset($_SESSION['Submit']);


//retrieve promoter_locus id, if it does not exist we create a new one
//Using function from menu_fns.php

$link->pl_id = menu_retrieve_id("promoter_locus",$_POST['promoter_locus'],TRUE);

$step = $_SESSION['step'];
session_trash_();
$_SESSION['step'] = $step;
$_SESSION['link'] = serialize($link);
//check if we are fixing step one
if($_SESSION['step'] == 3){
//this means we already did step two and
//clicked edit step one on last page
header("Location: StepThree_2.php");
exit;
} else {
//this is to check that step one has been completed once we go to step 2
$_SESSION['step'] = 2;
header("Location: StepTwo_2.php");
exit;

}

} else {

session_trash_();
session_regenerate_id(true);

}


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="../css/css.css" rel="stylesheet" type="text/css" /></head>
<body>

<table width="100%" border="0" cellpadding="0" cellspacing="0" id="outerTable">
<tr>
<td valign="top" id="bodyContent"><div class="pageTitle">Submit Cre Transgenic Line - Step 1 of 3</div>
<p class="sectionTitle">Please complete the following information.</p>
<form name="Start" method="post" action="<?php echo $_SERVER['PHP_SELF'].'?';?>">
<p><span class="formLabelsS2">Promoter or Locus</span> </p>
<p class="S2Form">
<input name="promoter_locus" type="text" class="basicTextField" id="promoter_locus"
value="<?php echo $_SESSION['promoter_locus']; ?>" maxlength="255" />
</p>
</form>
</td></tr>
</table></body>
</html>


<?php

//Step Two


//Database Credentials
include "db_fns.php";

//Menu Functions
include "menu_fns.php";

//User Functions
include "user_fns.php";
include "comment_fns.php";
//link fns
include "links_fns_2.php";
include "specificities_fns_2.php";
// Make Session / Session Variables.
session_start();          

// Avoid people messing with the URL bar!!!
if($_SESSION['step'] != 2) {
    session_destroy();
    $_SESSION = array();
    session_regenerate_id();
    header("Location: StepOne_3.php");
    exit();
}

if(is_string($_SESSION['link'])){ 
    $link = unserialize($_SESSION['link']);
} else {
    $link = $_SESSION['link'];
}

//if next step has been pressed, check that atleast one
//specificity is created and that link with this id
//has not been submited to the database yet.
if (isset($_POST['Next'])){
        //make sure atleast 1 specificity is added
        if($link->num_specs){
            $_SESSION['step'] = 3;
            $_SESSION['link'] = serialize($link);
			header ("Location: StepThree_2.php");
            exit();
		}
}

if (isset($_POST['Add'])) {

	$CellType = menu_retrieve_id('cell_type',$_SESSION['cell_type'],TRUE);


	//we put the new specificity into the database.
    $added = $spec->insert_spec();

    if($added){
    //we reload the link to include new spec and then serialize it for future steps
        $link->select_specs();
    }else{
        $failed = 1;
	}  
}
?>

<!--Same html format as Step_one above, so only relative excerpt is shown-->

	<table width="100%" border="0" cellpadding="0" cellspacing="0" id="innerTable">
	  <tr>
		<td valign="top" id="bodyContent">
            <div class="pageTitle">Submit Cre Transgenic Line - Step 2 of 3</div>
				<form name="Search" id="Search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" >
				<p class="viewTitles" >Add Specificity:</p>
			    <p class="formLabelsS2"><br />Cell Type:</p>
	     		    <p class="S2Form">
              			<input name="cell_type" type="text" class="basicTextField" id="cell_type"
                        onkeyup="suggest_search('cell_type','cell_type_suggest','%'+$(this).val()+'%',$(this).attr('id'));"
                        value="<?php echo $_SESSION['cell_type']; ?>" maxlength="255" />
                        <div id="cell_type_suggest" class="suggestive_main_div" ></div>
            		</p>
				</form>
		</td>
	  </tr>
	</table>
<?php
$conn->close();
?>
</body>
</html>

<?php 

//Step Three

header('Pragma: no-cache'); 
header('Cache-Control: no-cache, must-revalidate'); 

// Database Credentials
include "../db_fns.php";

include "../links_fns_2.php"; 
include "../specificities_fns_2.php";

// Make Session
session_start(); // Start Session
$sid = session_id(); // Set Session As Variable

//connect to database
$conn = db_connect_2();

/*
    Here we retrieve all of the link information
*/
if(is_string($_SESSION['link'])){
    $link = unserialize($_SESSION['link']);
} else {
    $link = $_SESSION['link'];
}
$link->select_link();
//update link, set status 5 meaning never submitted
$link->status = 5;
$link->update_link();

?>

<!-- html has pretty much the same format as previous steps, so only excerpt is shown-->

	<table width="100%" border="0" cellpadding="0" cellspacing="0" id="innerTable">
	  <tr>

		<td valign="top" id="bodyContent"><div class="pageTitle">Submit Cre Transgenic Line - Step 3 of 3 </div>

		<tr>
              <td valign="top"><div align="left"><span class="formLabelsS2">Promoter or Locus:</span></div></td>
              <td><span class="S2Form">
              <?php 
                  echo $link->promoter."</td></tr>"; 
              ?>
              </span></td>
        </tr>
		</td>
	  </tr>
	</table>

I know these codes are very long, but I did my best here to show as much as possible with shortened codes so you can have the general picture of all three steps.

Please let me know if you need more clarification.

Thanks.

    You really should indent your code to make it readable, otherwise it's way too hard to see where an if block starts and ends. Also, do use php tags instead of code tags to get syntax highlighting.

    At one point you assign $SESSION to $POST. While you can do so and still create code that works, I recommend against putting data into $_POST that doesn't come from a post request.

    array + array makes no sense. You should possibly use array_merge, but I advice you to explicitly assign the things that should go into session. First off, only nun-numeric string keys are overwritten, while integer or numeric strings are appended (and thus keys being changed). Also, a user can create any post data they want, and you should not blindly add things to session.

    Moreover, you definitely need to sanitize user input. Here's a simple example on how to both only include post data that you allow, while also checking that the supplied data matches certain criteria, such as what characters and what string lengths are allowed. The code could of course be extended to give more meaningful error messages etc.

    session_start();
    # This defines what post fields are allowed, and also what regexp patterns to use for validation
    # You could of course turn the array values into arrays themselves, containing things like
    # 'pattern' => REGEXP_PATTERN, 'error_message' => MEANINGFUL_ERRORMESSAGE,
    # 'type' => string|int|float (to allow for typecasting since post data is always string)
    
    # This example allows 4-6 characters, a-z only for promoter
    # upper and lowercase letters, digits and underscore, 3-20 characters for name
    # amount has to be digits only, and at least one digits long.
    $post_fields = array('promoter' => '#^[a-z]{4,6}$#', 'name' => '#^[a-zA-Z0-9_]{3,20}#', 'amount' => '#^\d+$#');
    
    # example post data - these should all be ok
    $_POST = array('promoter' => 'alpha', 'name' => 'bravo', 'amount' => '10');
    
    $post_errors = array();
    foreach ($post_fields as $field => $pattern)
    {
    	if (isset($_POST[$field]))
    	{
    		if (preg_match($pattern, $_POST[$field], $m))
    			$_SESSION[$field] = $m[0];
    		else
    		{
    			$post_errors[] = 'Invalid input for ' . $field;
    		}
    	}
    }
    printf('<pre>%s</pre>', print_r($_SESSION,1));
    foreach ($post_errors as $v)
    	printf('<div style="color: red;">%s</div>', $v);
    
    
    # clear out $_SESSION for another example
    $_SESSION = array();
    
    # example post data - none of these will pass
    # first string is too long. second string contains invalid characters
    # the last contains non-digit characters
    $_POST = array('promoter' => 'string_too_long', 'name' => '!"#€fds', 'amount' => 'ten', 'unknown_field' => 'will not be included');
    
    $post_errors = array();
    foreach ($post_fields as $field => $pattern)
    {
    	if (isset($_POST[$field]))
    	{
    		if (preg_match($pattern, $_POST[$field], $m))
    			$_SESSION[$field] = $m[0];
    		else
    		{
    			$post_errors[] = 'Invalid input for ' . $field;
    		}
    	}
    }
    printf('<pre>%s</pre>', print_r($_SESSION,1));
    foreach ($post_errors as $v)
    	printf('<div style="color: red;">%s</div>', $v);
    
      Write a Reply...