It appears pretty simple but I can not find a good method to do it. Say in the first page "page1.php" I created a variable

$myVariable = "Some text";

And the form's action for that page is "page2.php". So on 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).

Thanks!

php variables session cookie 

Nov 17

1 Answers

Http and https is stateless connection, however you did or you saw on previous page, is completely unconnected with the current page. but if you are using something like GET/POST methods, Sessions or cookies, then its quite easy to use on another page, hear is all example for your use.

Session:

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

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

Note: Don't forgot to run session_start(); statement on both pages before you do access with the $_SESSION .

Cookie:

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

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

GET 

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

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

This will create a GET variable.

GET OR POST:

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="variablename" value="var_value">
    <input type="submit">
</form>

And then on page two:

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

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

//Using GET, POST.
$var_value = $_REQUEST['variablename'];

 

answered Dec 02


Login and Submit Your Answer
Browse other questions tagged  php  variables  session  cookie or ask your own question.