While working in PHP, eventually you’ll want to be able to pass a variable, or piece of data, from one page… to another page.
After all, the power of variables are obvious on a single page – allowing great type–saving and re–use capabilties. But the true power of variables is their ability to be transferred to a completely different page, so they can be used in even more situations.
GET it from the URL
The quickest (but most limited) way to transfer variables is by a method called GET. With GET, you append the variables onto the URL of the page you want the variables to be transferred to:
http://www.matthom.com/contact.php?id=301&name=Matthom
The example above would give the contact.php page two variables to utilize: id, and name, whose values are 301, and Matthom, respectively.
You can add as many variables to the URL as you’d like.
Beware – sometimes you don’t want your variables to be shown “out in the open.” Also, you are limited to 255 characters in the URL, so the variables can’t contain too much information.
From contact.php, you can GET these two variables via PHP:
# GRAB THE VARIABLES FROM THE URL
$id = $_GET['id'];
$name = $_GET['name'];
POST it from a FORM
Another way to transfer variables, and by far the more robust way, is to grab them from a form.
Let’s say this is your form field code:
These two input boxes allow users to enter information. At process.php, you can grab the variables in the same way:
# GRAB THE VARIABLES FROM THE FORM
$searchtype = $_POST['searchtype'];
$searchterm = $_POST['searchterm'];
Notice the use of $_POST[] over $_GET[]. This is an important distinction.
While using the POST method, there are no limitations on how many characters you can include. Also, the variables are not visible in the URL.
My technical meanderings and other nonsense. Published since 2002. No, really. I'm *that* internet-old. I remember the days of
Good article, but one clarification: there is a limitation on how many characters you can include when using POST (or there generally is), dictated by the webserver (or by PHP). From memory PHP has a 2MB limit by default? although it’s possible to increase this.
Passing variables with $_GET and $_POST is good but only for certain things.
I use $_COOKIE for storing details such as Name, Email, WWW in the comment area. This is good because you don’t need to store anything on the server side.
Where as $_SESSION is good for storing more secure data. It’s like a cookie on the server side.
Remember to ALWAYS check data coming from a user, you may need to filter it etc to stop people from hacking or breaking things.
Questions from a novice PHP user:
Why is it that I can access values of variables on the page referred to in “action” on the form without making reference to $_POST? In other words, if my form has:
<form action=”results.php” method=”post”>
.. and selected “region” has a value of “6″..
Why is it that on results.php I can simply:
echo $region;
without using $_POST['region'] ? In fact, $_POST['region'] does not seem to be carrying a value.
Also, is there a way to combine this method of posting values AND having PHP code verify form data? The forms that I have seen with verification of data have an action which refers – not to the results page – but back to the page containing the form.
Thanks for any help you can offer.
Best regards, Peter
If ‘region’ is the NAME (‘name’ attribute) of one of your form elements, it should be accessible via
$_POST['region']– without a problem. The only thing that could prevent that (that I know of) is an older version of PHP – which only accepted$HTTP_POST_VARS['region']. Notice the difference in the variable names.I think PHP 4 (I could be wrong) started supporting the “short” format –
$_POST['region'].But… if you CAN access the form values by just using the variable –
$region– that should be the easiest way, anyway.The
actionattribute for the<form>element can request any file – including itself.Either way, to verify the form data with PHP, simple write some
ifstatements, which test to see if a certain value ($_POST['region']) is not set, IE:== ""… or you could do:if ( isset($_POST['region']) ) { code }what i’m trying to do is send a variable accross pages that can change values depending on some input like: link
where “variable” is a variable that can take any value. Is it possible in php? I will appreciate your help.
There is also another way to pass data through pages. You do this by using sessions.
I might seam unrelated but you are my best option…
I’m trying to create an online job application, using
FormMail 5.2 php script, and HTML page for the txt
input.
I got it to work just fine, with one page. Now since
the application is realy long, i would like to split
it into lets just say 4 .htm pages. The formhandler
in Front page lets me screate 4 different forms
ofcourse on 4 pages seperately, and I also know
how to link them… the only missing peace is the
hiden “stored” data from previous pages.
How can I access the already typed info, and send it
all through the form submit button together.
I have read about the sessions, GET vs. PUT.
Get would be insane to use for this long as appl.
Any clues on 4 .php pages instead,
where this code sounds promissing…
after grabing some string values with quotes(‘) and double quotes(“) from a variable using POST, and put them inside another form, like:
if a user entered double quotes(“) in the form and i need to repost the information into a new form with the quotes in it, the form will crop all information after the quote(“) because the form would look like this:
text entered by user: bobby the “madman”
the browser will parse the input line and think that the quote(“) before the word ’madman’ is the closing quote(“) for the value field. As a result, the browser will not display the information after the quote(“) before the word ’madman’.
the same problem happens when i use a single quote(’) to enclose the value field. the browser ignores any information after it parses the next single quote(’) in the value of the variable.
is there a way to display the whole information in the form?
Kitradin, you have to use the “opposite” quote-type (single or double), when using quotes in attribute values:
<input type="text" value="bobby the 'madman'" />
<input type='text' value='bobby the "madman"' />
what if they both have a single and double quotes? like
bobby’s website: “the madman”
You have to escape either the single or double quotes, depending on what your default is:
<input type="text" value="bobby's website: "the madman"" />Above, the default is double-quotes, as you can see the attribute values are in double quotes. Therefore, the double quotes around
"the madman"have to be escaped."escapes to"'escapes to'Does that help? Let me know…
we are linked with other websites. Clicking on the link user starting our registration form. On thrid page of our registration form we have an option to know about the refency of our site how can i do that
This is great feedback. Simple and to the point. It helped me fix a break in my PHP which calls a variable from a db. It was the only line missing.
check it out: http://www.atlantahomeindustries.com Click on properties. It shows the variable being passed.
From a learning amateur PHP coder … thank you!
Your step by step guide explains everything nicely.
I would like pass the value without using post,session,through URL also to other pages.
Can you give me idead about above criteria
Helping against injection – $id = (int)$GET['id']; cast value to int. $name = stripslashes($GET['name']); strip slashes placed there by magic quotes if they’re on. (They normally are)
then when adding – mysqlrealescape_string($name)
for security reasons, can a variable be passed on to a different page without using the GET method or a form or a cookie? cookies can be dangerous and sometimes turned off in some browsers, with the GET method data is exposed, with the form posting method it can be limited eg. having variables located in links..
Yes you can use PHP sessions (like server side cookies).
more info here.
This helped me solve a problem I was struggling with.
Thanks a ton.
Thank you! I couldn’t remember how to pass the form value into a php file.
Thank you for your help!
Thanx
Thank you very much, helped me a lot, nice info.
is there a way to pass variables without cookies, sessions and forms. Like passing from a.php to b.php.
i have a Poblum
what that
—–Html Code——-
—–PHP Code——-
< ?
$tvl=$_REQUEST['tvl'];
echo $tvl;
?>
now run Html
type Text Box : Im Mahesh from “Horana”
send me if
erangagb@yahoo.com
Thanks. This clarified an important point that was left out of an article on PHP and databases on the Devzone found on mysql.com by Kevin Yank. He left out this syntax:
$firstname = $_GET['firstname'];
to access the variables that are passed. I was gettingblanks until I came across your blog.
Just have to say a BIG thank you, Matt.
I spent all day trying to figure out why a php script worked on an old server and not on the new, then trawling the net and the php documentation for clues.
These two lines (with my own variable names) – and Bingo!
$id = $_GET['id'];
$name = $_GET['name'];
I discovered that the old server had php Version 4.3.9 and the new had 5.2.11
I’m assuming that the newer version is more precise?
Anyway, thank you for posting this magic article.
Keep up the good work!
i have sending through url like
<a href = 'de.php?cid=1 />actually in this file i havn’t intialized cid anywhere
but on other side i have written
<?php $cid = $_request('cid'); ?>i have tried get also
it is giving me call stack error.
can i pass a variable from one page to another if i goto the second page using header() function?
!--- index.php <?php mysql_connect("localhost", "root", "") or die(mysql_error()); echo "Connected to MySQL<br />"; mysql_select_db("technologies") or die(mysql_error()); echo "Connected to Database"; echo"<form action="result.php?tech=$[Tech_Name]" method="post">"; $query = "SELECT * FROM tech_table"; $result = mysql_query($query) or die(mysql_error()); echo"<select name="tech" multiple="multiple" >"; while($row = mysql_fetch_array($result)){ echo"<option value=".$row['Tech_Name'].">".$row['Tech_Name']."</option>";} echo"</select>"; echo"<input name="search" type="submit" value="Search" />"; echo"</form>"; ?> ------- here in results.php i need to send the Tech_Name and Tech_ID. where am able to send only Tech_ID with this code. !----result.php <?php $tech=$_REQUEST['tech']; echo "The selected technology was " .$tech; mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("technologies") or die(mysql_error()); $query = "SELECT * FROM .$tech"; $result = mysql_query($query) or die(mysql_error()); echo"<table width="400" border="1" align="center">"; echo "<tr><th>Tech ID</th>"; echo "<th>First Name</th>"; echo "<th>Last Name</th></tr>"; while($row = mysql_fetch_array($result)){ echo"<tr><td>"; echo $row['Tech_ID']; echo"</td><td>"; echo("<a href="details.php?code=" .$row["Tech_ID"] ."" title="click here to learn more about ".$row["First_Name"]."">" . $row["First_Name"] . ", </a>"); echo"</td><td>"; echo $row['Last_Name']; echo"</td></tr>"; } echo"</table>"; ?> ---------- !------details.php <?php $Lead_ID=$_REQUEST['code']; echo $Lead_ID; $Tech=$_POST['$tech']; echo $Tech; mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("technologies") or die(mysql_error()); $query="SELECT * FROM salesforce WHERE Tech_ID='$Lead_ID'"; $result=mysql_query($query) or die(mysql_error()); echo"<table width="400" border="1" align="center">"; while($row = mysql_fetch_array($result)){ echo"<tr><td>"; echo "<br/>"; echo $row["First_Name"]; echo " "; echo $row['Middle_Name']; echo " "; echo $row['Last_Name']; echo " "; echo "<br/>"; echo $row['Job_Title']; echo "<br/>"; echo $row["Email"]; echo "<br/>"; echo $row["Direct_Phone"]; echo "<br/>"; echo "<br/>"; echo "<p algin='right'>"; echo $row["Company_Name"]; echo "<br/>"; echo $row["Street"]; echo $row["City"]; echo $row["State"]; echo "<br/>"; echo $row["Country"]; echo $row["Zipcode"]; echo "<br/>"; echo $row["Phone"]; echo "<br/>"; echo "Fax: "; echo $row["Fax"]; echo"</p>"; echo"</td></tr>"; } echo"</table>"; ?>PLZ help….
Is it possible to use “#” in the variable? f.i.:
index.php?p=wie_zijn_wij.php#voor_wie
this variable is passed to the src of an Iframe it workes when using only index.php?p=wie_zijn_wij.php. when adding the achor link, it seems to forget to go there. I know that the anchor works, if i type wie_zijn_wij.php#voor_wie as url in the browser, it goes to the right place in the document.
The “#” is a comment designator, so it has to be escaped. Try:
index.php?p=wiezijnwij.php\#voor_wieOutstanding, thank you for your clear and concise info. I was able to fix my issue within about three minutes of reading this…
After converting from php 4.0 to php 5.3 , i cant pass varibles. The varibles does not get to traceprint.php. Did my web hosting installed php 5.3 incorrectly? Please help
< ?php
$myphrase = $_POST["myphrase"];
$ntrace = $_POST["ntrace"];
$nblank = $_POST["nblank"];
echo '
After converting from php 4.0 to php 5.3 , i cant pass varibles. The varibles does not get to traceprint.php. Did my web hosting installed php 5.3 incorrectly? Please help
New challenge: I only want to pass the variable name, not the value, and I’m passing directly to the index.php program, so I don’t need to specify the program. When I try:
http://website.com/?varname
I don’t get an error, and I suspect that “varname” is being detected by the program. Is there a way for me to retrieve that name?
My real goal is to pass a string value into my index.php program using as few characters as possible. So far, this is the shortest I can make the command:
http://website.com/?C=value
Is there a way to get this any shorter?