238

It seems pretty simple but I can't find a good way to do it.

Say in the first page I create a variable

$myVariable = "Some text";

And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).

How can I achieve this?

Thanks!

1

9 Answers 9

518

HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.

Session:

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.

GET and POST

You can add the variable in the link to the next page:

<a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>

This will create a GET variable.

Another way is to include a hidden field in a form that submits to page two:

<form method="get" action="page2.php">
    <input type="hidden" name="varname" value="var_value">
    <input type="submit">
</form>

And then on page two:

//Using GET
$var_value = $_GET['varname'];

//Using POST
$var_value = $_POST['varname'];

//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];

Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.

The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.

10
  • 2
    Thanks this helped, the problem was that I had a bunch of variables in the first page, so what I did was create an array with all those variables and send it to the next page using sessions.
    – Carlo
    Commented May 19, 2009 at 17:04
  • Schweet :) Glad I could help.
    – Jrgns
    Commented May 20, 2009 at 2:36
  • 6
    Nitpick: sessions in PHP generally are handled by cookies too. The session cookie is not a persistent cookie and usually simply only holds the session id. But it is still a cookie. Commented Jan 27, 2010 at 5:26
  • To elaborate on my own comment. The reason is that, because, as you said, HTTP is stateless. Therefor PHP still needs a way to identify the session. This is done by storing a cookie on the client with a session id. If cookies are disabled clientside, PHP sometimes utilizes $_GET vars to append the session id to links between pages. But this is generally considered insecure, and is therefor generally disabled of most webservers (php.ini). Commented Jan 27, 2010 at 5:38
  • @fireeyedboy PHP sessions can be propagated using GET and POST variables as well. At the end of the day, session simplify passing variables from one page to the next by having only one piece of data to transfer: the session id. That session id is then used to retrieved the previously saved data.
    – Jrgns
    Commented Feb 9, 2012 at 11:34
34

Thanks for the answers above. Here's how I did it, I hope it helps those who follow. I'm looking to pass a registration number from one page to another, hence regName and regValue:

Create your first page, call it set_reg.php:

<?php

session_start();

$_SESSION['regName'] = $regValue;

?>

<form method="get" action="get_reg.php">
    <input type="text" name="regName" value="">
    <input type="submit">
</form>

Create your second page, call it get_reg.php:

<?php

session_start();

$regValue = $_GET['regName'];

echo "Your registration is: ".$regValue.".";

?>

<p><a href="set_reg.php">Back to set_reg.php</a>

Although not as comprehensive as the answer above, for my purposes this illustrates in simple fashion the relationship between the various elements.

1
  • 14
    Your example works without sessions too and is in fact not getting the data via the sessions-mechanism (in get_reg.php). You are sending regName via a form with the get-method as explained by Jrgns. The variable is thus accessible at the get_reg.php page via the $_GET array.
    – metatron
    Commented Mar 11, 2012 at 14:11
20

Passing data in the request

You could either embed it as a hidden field in your form, or add it your forms action URL

 echo '<input type="hidden" name="myVariable" value="'.
     htmlentities($myVariable).'">';

or

echo '<form method="POST" action="Page2.php?myVariable='.
    urlencode($myVariable).'">";

Note this also illustrates the use of htmlentities and urlencode when passing data around.

Passing data in the session

If the data doesn't need to be passed to the client side, then sessions may be more appropriate. Simply call session_start() at the start of each page, and you can get and set data into the $_SESSION array.

Security

Since you state your value is actually a filename, you need to be aware of the security ramifications. If the filename has arrived from the client side, assume the user has tampered with the value. Check it for validity! What happens when the user passes the path to an important system file, or a file under their control? Can your script be used to "probe" the server for files that do or do not exist?

As you are clearly just getting started here, its worth reminding that this goes for any data which arrives in $_GET, $_POST or $_COOKIE - assume your worst enemy crafted the contents of those arrays, and code accordingly!

11

There are three method to pass value in php.

  • By post
  • By get
  • By making session variable

These three method are used for different purpose.For example if we want to receive our value on next page then we can use 'post' ($_POST) method as:-

$a=$_POST['field-name'];

If we require the value of variable on more than one page than we can use session variable as:-

$a=$_SESSION['field-name];

Before using this Syntax for creating SESSION variable we first have to add this tag at the very beginning of our php page

session_start(); 

GET method are generally used to print data on same page which used to take input from user. Its syntax is as:

$a=$_GET['field-name'];

POST method are generally consume more secure than GET because when we use Get method than it can display the data in URL bar.If the data is more sensitive data like password then it can be inggeris.

8

try this code

using hidden field we can pass php varibale to another page

page1.php

<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
 <input type="hidden" name="text" value="<?php echo $myVariable; ?>">
 <button type="submit">Submit</button>
</form>

pass php variable to hidden field value so you can access this variable into another page

page2.php

<?php
 $text=$_POST['text'];
 echo $text;
?>
0
7

Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.

1
  • Please consider improving the answer with sample code and links to reference material
    – Aurovrata
    Commented Nov 8, 2021 at 11:28
2
**page 1**
<form action="exapmple.php?variable_name=$value" method="POST"> 
    <button>
        <input  type="hidden" name="x">
    </button>
</form>`

page 2

if(isset($_POST['x'])) {
    $new_value=$_GET['variable_name'];
}
1

It works. Send data throw URL, without form.

$upit = "SELECT * FROM usluga";

            $data = $mysql->query($upit);

            while ($row = mysqli_fetch_object($data)) 
            {
                echo "<a href='"."index.php?tretmanId=$row->tretman_id"."'>$row->naziv</a>";
                echo "<br><br>";
            }

and you can get this value on the target page with "$_GET['name from URL']", like this

$TrermanIdFromUrl = $_GET['tretmanId'];
1

You can for example call the page you want by including variables in the url:

header("Location: ../signup.php?newpwd=passwordupdated");

And on your signup.php page, you would have

if (isset($_GET['newpwd']) && $_GET['newpwd'] == "passwordupdated") {
        //code here
    }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.