Using PHP variables on multiple pages - php

Is it possible to use a variable from one page in a piece of code on another? e.g. submit a form on one page and on the second page use a PHP script to add the data from the form to a MySQL table
Thanks for all the help

Your best bet would be to use PHP's session functions. That way if the user navigates away from your page and then comes back, the session variables will still be there (provided the session hasn't expired). You can get more information here -- PHP Sessions. Basically all you have to do is call
session_start();
at the top of each php page (before anything is outputted to the browser) where you want to have access to the session variables. You can then set/retrieve a variable using
// set
$_SESSION['varname'] = "something";
// retrieve
$somevar = $_SESSION['varname'];

This is what the GET and POST 'super' globals are for.
http://www.tizag.com/phpT/postget.php

The script that generates the form does not have to be the script the processes the form. all it takes is for the FORM tag to point to the correct script. The only caveat is that whatever page you submit the form data to also has to then generate some suitable output (unless you do a AJAX POST).
If you're instead asking if two page executions can handle the same POSTed data, well that is quite a different question. At a simplistic level, you can have the first include() the second so it has access to all the same data. A bit more advanced is to re-create the original POST and synthesize a POST. This will probably require some JavaScript assistance. Another approach is to use PHP's session feature and put the value aside so a later script has access to it. This relies on the user then following the correct link, however!

Use session to access your variable to the second/other page.
Example:
index.php
<?php
session_start();
$_SESSION['yourData'] = 'yourData';
?>
=========================================================================
second_page.php
<?php
echo $_SESSION['yourData'];
?>
You may try this one. Visit this link for more details. Or PHP's official website.

Related

PHP Session - Values Randomly NOT Being Written

I am building a site that combines ajax and PHP to create dynamic forms that load/validate/submit in-page. I am using a combination of PHP session variables with custom handlers, $.post, and $().load to accomplish this. I build my forms in individual php pages (they are very large) and then load them into a section of my main page.
At the top of my main page I start a session like so:
<?php
require("inc/SecureSession.php"); // Custom handlers
session_save_path($_SERVER['TEMP']); session_start();
?>
Then in each form page I start a session and generate a token variable, like so:
<?php
require("inc/SecureSession.php"); // Custom handlers
session_save_path($_SERVER['TEMP']); session_start();
$_SESSION['token'] = rand();
?>
This token variable gets inserted as a hidden field at the bottom of the form page, and should write to the session.
However, I've found that session variables set in dynamically loaded (or posted) pages do not seem to consistently stay set. They work within the scope of the form page but then do not always carry over back to the main page. I thought this might be because they were not actually accessing the right session, but it seems all session variables outside the form page can be accessed within the form page.
So I am stumped. The PHP handler I am using is the one here: http://www.zimuel.it/en/encrypt-php-session-data/
Edit: When I load one of the form-pages directly, it writes 100% of the time. It is only when I load a form via jQuery that it gets wonky.
Edit2: The issue wasn't that I was declaring the code in the wrong order. I did some research and found that I am supposed to declare the save path and handler functions before I start the session. The issue appears to have been either that I opened php with "

Passing data between webpages

I have a webpage with a form on it. The heading of the form is this:
<form name="sw" METHOD ="POST" ACTION="logger1.php">
After some event has happened, a javascript function submits the form like this:
document.forms["sw"].submit();
The php file logs the data from the form in a text file on the server, and then redirects the browser to another page. My issue is that I want to examine one of the values in the form from the previous page on the page that the browser is redirected to. I am completely lost. help!
Have you considered using sessions? The $_SESSION[] array might keep your previously posted variable between pages.
Basically all the form information is being passed to the "logger1.php" file in the POST method.
So you need to see what the code in the "logger1.php" file is and see exactly how the file is redirecting once it's done doing what it does.
Then you can possibly append the variable you want passed on to the redirect method in the GET method.
Lets say the variable you want to pass on is:
$_POST['Some_variable']
and the redirect method is something like:
header('Location: some_file.php');
then you can append it this way:
header('Location: some_file.php?variable_name='.$_POST['Some_variable']);
You can append ?info=hello to the end of the URL it redirects to, then retrieve it in PHP with $_GET['info']
You can't. The information is not passed when the browser is redirected so there is no way to access it.
I think the best way to do this would be to store the value in a database. If you are using ASP.NET the easiest way to do this would be to set up a SQL Server Express database. They are free until you go over 10GB.
Cant you put the variable that you want to look at as a get variable added to the url of the redirected page like so http://yourdomain/thepage.php?var=variable

PHP permanent variable, but changeable?

This is more a question on php theory, and wondering how this scenario would be done..
So I have a gallery which has pagination, all done through reloading the page through $_GET.
I want the ability for a user to change the amount of images are displayed on a page (basically my LIMIT). I have this working, however when they go to the next page, the php reloads, and the pagecount gets reset back to default.
Is there a way to store this variable through $_POST to another page when they choose the page count, and then every time the page re-loads, it will grab that variable, so it is not re-set?
Excuse my noobiness. Hopefully this makes sense
I believe you are looking for session variables
<?php
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>
http://www.tizag.com/phpT/phpsessions.php
What you want are PHP sessions, which
...consists of a way to preserve certain data across subsequent accesses
See the PHP docs for more information.
Whenever you make a request to the server, pass along all the variables that you need. So if you're changing the limit by submitting a form, pass along the page number as a hidden form field:
<select name="limit">...</select>
<input type="hidden" name="pageNum" value="<?= htmlspecialchars($pageNum) ?>" />
Or if you're changing the limit with a link, pass along the page number as another URL argument:
Limit 10
Then you can read it on the server using $_POST["pageNum"] or $_GET["pageNum"].
I don't recommend storing things like this in the session. If you do, you'll prevent people from having multiple windows open to different pages. It's best to pass everything in the request (i.e. the form or link).

PHP: Pass non-form variables between pages?

I have a page. The user submits the page and sends it to a PHP results page. It works fine. Now, I want the results page to link to another page, and for the elements on that page to depend on what was on the results page. I know how to pass form variables to another page, but I don't know anything about passing non-form variables.
From my searching on the web, my best guess is that I should be passing by URL. Is this correct? If so, a possible problem: the page I want the results page to pass to will have a form, and the user will go to yet another results page by clicking submit (the form data will be sent by POST). Can I send the non-form data (the old results page variable) along with the form data, if the user is going to the other page using POST?
I strongly suggest using sessions. It's not that hard to learn, php makes it VERY easy using http://php.net/session_start and the $_SESSION variable.
Advantage is that you will not have to submit a form on every click, and no information will be displayed in plain text in the URL.
There are several options. However, the easiest may be to simply pass the data on using hidden input fields.
Other options would be using the session, storing to a database between forms, or some combination therein.
If you are going to use POST to go to the next page the most simple option is to include the data you want to send along using an input type="hidden" element in your form.
You might consider using a session to pass the data along.
You can embed the non-form data into the second form as hidden fields. To make sure that it is also passed in the link, you can just add it to the URL as a query string, like:
http://..../blah.php?var1=val1&var2=val2
as long as the data you're passing can fit into a URL. Be sure to urlencode() anything you're appending to the URL.
<?php
start_session();
$_SESSION['Foo'] = 'Bar' // Add stuff here.
?>

Back button re-submit form data ($_POST)

My problem is that the back button causes the browser to say something like "Page expired" when the previous page was created by a form.
Example:
page1: form submitted with search
criterias ($_POST request, form
points to page2)
page2: Receives $_POST request and
show result (list of user with links,
points to page3)
page3: Show user profile
Now when the visitor clicks the back button in the browser it will show something like "Page expired".
Instead the previous page should be shown with no warnings (page2, with the userlist)
How are your strategies to get around this behavior?
If you are submitting a form with search parameters, you are trying to get some data, not modify some.
So, you should use the HTTP GET method, and not POST : POST should be used when you intend to create/modify data, and GET should be used when you intend to fetch some data.
Or, if you have some create/modify operation that has to be done :
The form first POSTs to a first page
That page does some operations (like writing something to a database)
And then redirects to another page, using a Location HTTP header.
It's that last page, that's queries by the browser using a GET requests, that displays the data fetched from the parameters received in the URL.
See the Post/Redirect/Get page on wikipedia, about this.
Use the Post/Redirect/Get (PRG) Pattern.
This applies to PHP and IE8.
Not only must you set cacheing to private, but you must remove the 4 cacheing headers and this can only be done with PHP 5.3. In PHP 5.2 you can only set the 4 headers to blank values if using the Zend Framework's setHeader() method. For some reason is not sufficient on IE8 to set the 4 header values to empty values. Here's the code for PHP 5.3:
header_remove("Expires");
header_remove("Cache-Control");
header_remove("Pragma");
header_remove("Last-Modified");
Send a Location header in the script you POSTed to, pointing to the page that comes after.
Don't use POST for search. Search can safely be done with GET since it won't alter anything.
You can use session to do this.
eg.
$_SESSION['name'] = $_POST['name'];
Remember to unset your variables after the process is complete to optimize memory usage.

Categories