Link to home
Start Free TrialLog in
Avatar of akashj
akashj

asked on

Passing variables to more than one page

Hi all,

Not sure if I'm being stupid here but am I correct in assuming a $get/$post variable can be passed through to more than just one page?
I can pass it to one page without any issues but it loses it when going to the next page.

My task is to select an option from a dropdown box on page1 but pass it through to almost 15 pages before it lets go of it.

I've tried session variables etc but it still loses it (checked by echoing out the result)

Thanks
Avatar of orsobruno
orsobruno

In such cases it is better to use the cookie.

e.g.

$_COOKIE["checked"] = $selection_option_value;
Avatar of Loganathan Natarajan
did you use hidden field to post it to another page?
Avatar of akashj

ASKER

I'll give cookie a go and see how that goes

As for hidden field - no... I was under the impression a simple declaration of the variable using the $get function would just hold it in memory until it was cleared
That might be another test I can do with the hidden field though
Avatar of akashj

ASKER

My concern with cookies is browser/IT support as its an internal site
Avatar of akashj

ASKER

I should also note that when I say between pages...the first page is a button that posts it but from there on, it is a number of redirects and NOT manual intervention to go from page B to C if that makes sense.
This is why it probably isn't working as I'm not physically posting something between redirects
you can do with hidden, it means, you have to use form method, post .. and then you can check each page and again you have to post it..?
Avatar of akashj

ASKER

but how does it post the variable across if it is using a redirect function?
I may have found another issue which may answer this in that a test for sessions does not actually seem to store the variable.
I'm going to log another post for this now
In that case, you can pass the value through redirect function URL itself.

for example,

. '?link=yes&value1=222';?>]Click Here
On every page call this

<?php

session_start();

$_SESSION['name'] = $_POST['name'];

?>

The session will be passed on to the other pages and it can be retrieved on any page as well.

Thanks
Parag
"I've tried session variables etc but it still loses it (checked by echoing out the result)"

Either your session is not working or you have a logic error in your code.  Please install this script and run it.  If the counter increments, your session is almost certainly OK.
<?php // RAY_session_test.php
error_reporting(E_ALL);

// MAN PAGE HERE: http://us.php.net/manual/en/function.session-start.php

// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// SEE IF THE SUBMIT BUTTON WAS CLICKED
if (isset($_POST['fred']))
{
    // SEE IF THE CHEESE VARIABLE IS SET IN THE SESSION ARRAY
    if(!isset($_SESSION['cheese']))
    {
        // IF CHEESE IS NOT SET, SET IT TO ONE
        $_SESSION['cheese'] = 1;
    }
    else
    {
        // IF CHEESE IS SET, ADD ONE TO IT
        $_SESSION['cheese']++;
    }
}
// END OF SCRIPT - SUPPRESS NOTICES IN THE HTML PART
error_reporting(E_ALL ^ E_NOTICE);
?>
<html>
<head>
<title>Session Test</title>
</head>
<body>
Currently, $_SESSION["cheese"] contains: <?php echo $_SESSION['cheese']; ?> <br/>
<form method="post">
<input type="submit" value="click" name="fred">
</form>
</body>
</html>

Open in new window

Here is how to take a form input variable and put it into the session.  Install this on your server and run it to see the moving parts.  You can try using this script with redirects, links to other scripts, etc.  Just be sure that you have...

session_start();

... as the first element on each script.  Unconditionally.  Always.  Every script.

You can use var_dump() to visualize any data structure.  If you echo "<pre>" before var_dump() it will be easier to read.

HTH, ~Ray
<?php // RAY_prepopulate_forms.php

// SET ERROR REPORTING SO WE CAN IGNORE UNDEFINED VARIABLE NOTICES
error_reporting(E_ALL ^ E_NOTICE);

// ALWAYS START THE SESSION UNCONDITIONALLY AT THE TOP OF THE PAGE
session_start();

// IF ANYTHING HAS BEEN POSTED
if (!empty($_POST))
{
    // COPY THE POSTED INFORMATION TO THE SESSION
    $_SESSION['POST'] = $_POST;
    
    // DISPLAY THE CONTENTS OF THE ARRAYS TO SIMULATE PROCESSING THE DATA
    echo "<pre>" . PHP_EOL;
    echo "POST: ";
    var_dump($_POST);
    echo "SESSION: ";
    var_dump($_SESSION);
    
    // ALL DONE
    die("HIT THE BACK KEY NOW");
}

// IF NOTHING HAS BEEN POSTED, DROP INTO HTML AND PUT UP THE FORM
?>
<form method="post">
YOUR NAME: <input name="name" value="<?php echo $_SESSION["POST"]["name"]; ?>" />
<input type="submit" />
</form>

Open in new window

Avatar of akashj

ASKER

Right bit of progression here
I've got the entire site fully working with your help BUT
this query still stands if it is IE6 or IE7.

Through IE8, Chrome and Firefox, the sessions are passing through to different pages without any issues.
In IE6 and IE7, it loses the variable/session as soon as a redirect is done.

I've tried the counter script above which DOES work in IE6/7 but we're not redirecting anywhere.
If I then add a 5 second auto-redirect to another page after your counter page, the session is lost on the next page unless I use the above working browsers
Please post the script that is failing, thanks.
Avatar of akashj

ASKER

Here you go
This works fine in other browsers remember

One other thing is all these header lines...something I found on a thread here which did not work but I've left them in there anyway

Another thing to note is within the office, we do NOT have the Privacy tab under IE6 - I am trying to find out more information about this but because the same policy applies on the IE8 machines and that works fine...I've somewhat discounted it
These are my test scripts:
Page 1 is a simple $post via a drop down so I won't paste this in as it is a bit complex connecting to a sql server table to get the values.

Page 2:
<html>
<head>
<meta http-equiv="refresh" content="0.5; URL=testvariable2.php">
</head></html>  
<?php 
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
header("Set-Cookie: SIDNAME=ronty; path=/; secure");
header('Cache-Control: no-cache');
header('Pragma: no-cache');
error_reporting(E_ALL);
//print 'Here is page two, and my session variable: '; 
session_start(); 
$ba = $_REQUEST['ba'];
  $_SESSION['b_area'] = $ba;
//print $ba;
//print $_SESSION['b_area']; 
exit; 
//session_destroy();
error_reporting(E_ALL ^ E_NOTICE);
?>

After 0.5 seconds, this redirects to page3:
<?php 

header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
header("Set-Cookie: SIDNAME=ronty; path=/; secure");
header('Cache-Control: no-cache');
header('Pragma: no-cache');
error_reporting(E_ALL);
print 'Here is page two, and my session variable: '; 
session_start(); 

//$ba = $_REQUEST['ba'];
//print $ba;
print $_SESSION['b_area']; 
exit; 
 // or this would remove all the variable in the session 
 session_unset(); 

 //destroy the session 
 session_destroy(); 
error_reporting(E_ALL ^ E_NOTICE);
?>

Open in new window

You need to make some important changes here.  To see why, please run this script (copied from above) without the meta-refresh.  The error messages probably flashed past so quickly during the redirect that you could not see them.

It is a law of HTTP that all headers must come first before any browser output.  The first line of HTML is browser output, so this script violates that law when it tries to send headers and set cookies.
<html>
<head>
<!-- <meta http-equiv="refresh" content="0.5; URL=testvariable2.php"> -->
</head></html>  
<?php // RAY_temp_akashj.php
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
header("Set-Cookie: SIDNAME=ronty; path=/; secure");
header('Cache-Control: no-cache');
header('Pragma: no-cache');
error_reporting(E_ALL);
//print 'Here is page two, and my session variable: '; 
session_start(); 
$ba = $_REQUEST['ba'];
  $_SESSION['b_area'] = $ba;
//print $ba;
//print $_SESSION['b_area']; 
exit; 
//session_destroy();
error_reporting(E_ALL ^ E_NOTICE);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm sure the next question is going to be, "Why did it work in some browsers?"  This is a bit of speculation, but it's a fairly common mistake.  All browser instances share the same cookie jar (and therefore the same session) by default.  So if you have an instance of FF open and you login to a site, then open another instance of FF - either window or tab - the second instance will be immediately logged in.  So if you were testing with multiple copies of the browser running, it could have caused some of the erratic success / failure pattern you observed.

Best regards, ~Ray
Avatar of akashj

ASKER

Odd,
I can't get this working under IE6
I wonder if this is indeed a policy issue in which case unless there is a workaround....
I know IT will not change it.

I'll give it a few more tweaks and see how it goes
IIRC IE6 has some ugly stuff about how it uses headers.  Here is my "force download" script.  Note what I had to leave out to get MSIE browsers to work.
<?php // RAY_force_download.php
error_reporting(E_ALL);



// A FILE TO DOWNLOAD - THIS LINK COULD COME IN THE URL VIA $_GET, OR COULD BE GENERATED INSIDE THE SCRIPT
$url = "http://www.google.com/intl/en_ALL/images/logo.gif";

// USE CASE
force_download($url);




// FUNCTION TO FORCE A DOWNLOAD FROM A FILE
function force_download($filename)
{
    // GET A NAME FOR THE FILE
    $basename = basename($filename);

    // GET THE CONTENTS OF THE FILE
    $filedata = file_get_contents($filename);

    if ($filedata)
    {
        // THESE HEADERS ARE USED ON ALL BROWSERS
        header("Content-Type: application-x/force-download");
        header("Content-Disposition: attachment; filename=\"$basename\"");
        header("Content-length: ".(string)(strlen($filedata)));
        header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

        // THIS HEADER MUST BE OMITTED FOR IE 6+
        if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
        {
            header("Cache-Control: no-cache, must-revalidate");
        }

        // THIS IS THE LAST HEADER
        header("Pragma: no-cache");

        // FLUSH THE HEADERS TO THE BROWSER
        flush();

        // CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
        ob_start();
        echo $filedata;
    }

    // ERROR
    else
    {
        die("ERROR: UNABLE TO OPEN $filename");
    }
}

Open in new window

Avatar of akashj

ASKER

Beginning to agree with you
On a simple google of php ie6 and session ie6, a lot comes up for IE6 and 7
Problem is, there does not seem to be a solution.

I'm not entirely clear what you meant from your last code - I need to force the headers or...?

Annoying thing is the IT guys ARE upgrading to IE8...but in January so I've got no choice but to find some sort of workaround.

My only workaround at present is that I scrap the idea and rework the system in that it gives you two "breaks" where the user selects their variable.  This means it would take longer but also a user cannot just apply their variable and let it be.
At present, it is just the once and then you leave the system to do its business (providing its on IE8)
Have you tried leaving out the "Cache Control" header?
Avatar of akashj

ASKER

Nope didn't help
And whats worse...without doing anything at all, IE8 no longer works either!
Chrome does however as dose FF.  Checked timestamps and even restored a backup from the 21/10 when I got it initial working with your help.

Baffled is not even close to what I explain this strangeness!

OK in theory if we talk about other ways.... How would you design a site that would take a user set variable from a frontpage via a dropdown list and push it all the way through to 5 pages until the end when it clears it?
Bearing in mind these 5 pages would be redirect jumps on a timer.
Avatar of akashj

ASKER

I'll update later tonight but I've once again got it working
For a minute, I started to think that there is some delay in storing the session and it picks up suddenly -
I started using your script fix in post 33727326 and removed all HTML redirects but replaced it by redirect within the PHP with the delay.

I then broke the script so it would redirect to a page that would simply echo the session - this worked.
Lastly, I tested this in IE6 and it actually worked in there.
Thinking of this session delay, I went to another PC with IE6 and it works there too.

I'm fixing all the other pages now to use your fix + the php redirect and will do a test at the end.
For now, I'm taking some advice you gave me last time to almost echo the session/result in each jump so I know where it is breaking - time consuming but this might just be getting me to closing this project!

Thanks again for your help and I will update shortly :)
Regarding this:

"OK in theory if we talk about other ways.... How would you design a site that would take a user set variable from a frontpage via a dropdown list and push it all the way through to 5 pages until the end when it clears it?"

I would almost certainly want to use the session array.  That is what it is for - to preserve state between pages.  Sounds like you're on the right track.
Avatar of akashj

ASKER

Thank you once again for all the help
So far everything is working perfectly ... until IE8 upgrade I'm sure :)
You should still be OK at IE8.  The cookie and session handlers are pretty well standardized by now.  Thanks for the points, ~Ray