Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer variables between PHP pages

Tags:

variables

php

I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.

like image 970
chustar Avatar asked Oct 27 '08 16:10

chustar


People also ask

How do I move a variable from one page to another?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

How do I pass a value from one page to another in PHP with session?

This will ensure that we can safely access the variable defined in other page, by just using $_SESSION['name']. In printName. php file, echoing the session name variable prints the name we have inputted from user in another page. So, this is how you pass variables and values from one page to another in PHP.


2 Answers

Try changing your session code as this is the best way to do this.

For example:

index.php

<?php
session_start();

if (isset($_POST['username'], $_POST['password']) {
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['password'] = $_POST['password'];
    echo '<a href="nextpage.php">Click to continue.</a>';
} else {
    // form
}
?>

nextpage.php

<?php
session_start();

if (isset($_SESSION['username'])) {
    echo $_SESSION['username'];
} else {
    header('Location: index.php');
}
?>

However I'd probably store something safer like a userid in a session rather than the user's login credentials.

like image 145
Ross Avatar answered Nov 08 '22 23:11

Ross


I Agree with carson, sessions should work for this. Make sure you are calling session_start() before anything else on any page you want to use the session variables.

Also, I would not store password info directly, rather use some kind of authentication token mechanism. IMHO, it is not intrinsically unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.

like image 23
ZombieSheep Avatar answered Nov 08 '22 23:11

ZombieSheep