Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass value from one php page to another using session

Tags:

post

php

session

I can pass values form one page to another but I need to pass value like this,

Page 1:

Page4.php

Page3.php

I need to pass the value in a text field in the Page1.php to a text field in Page2.php, since the form is not directly redirectly to page2, I am unable to pass the value, I tried session, form post method and few other methods but I am yet to succeed.

I would be very happy if you can help me with the code or some suggestions.

Thanks!

Edit..........

I found the answer, thanks for the help, it was actually a careless mistake on my part, I used $_post instead of $_session.

Its working now.

Thanks for the help.

like image 309
A Mohammed Hussain Avatar asked Dec 21 '22 15:12

A Mohammed Hussain


1 Answers

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}
like image 172
Fluffeh Avatar answered Jan 13 '23 14:01

Fluffeh