How do I share a PHP variable between multiple pages?

隐身守侯 提交于 2021-02-04 06:49:58

问题


The idea/goal:

I have a username and password inside a text file on my computer. The form on the index page allows the user to sign in with their username and password. The login page is where PHP is used to validate the user entered info with the info which i have on my local text file. Directly after the user entered info match my text file info the user is redirected to a Home page where they're name is displayed with a welcome message.

The Problem:

Everything up until the validation works. The issue is that when i redirect the user to Home.php I can't display their username. How would i display their username after all the validation? Is there anyway i can permanently store their username in a variable that will be accessible across all my pages?

The Index.php page with the form

The login page that validates the form info with the info i have on my local text file


回答1:


Use $_SESSION -!

session_start();
$_SESSION['username'] = $_POST['username'];

You of course want to filter/sanitize/validate your $_POST data, but that is outside of the scope of this question...

As long as you call session_start(); before you use $_SESSION - the values in the $_SESSION array will persist across pages until the user closes the browser.

If you want to end the session before that, like in a logout button --- use session_destroy()




回答2:


You can start a session and put the form values into the $_SESSION variable, which will be available on all pages.

// On the page where your form is submitted:
session_start();
$_SESSION['name'] = $_POST['name'];

// On the page where the user is redirected:
session_start();
echo $_SESSION['name'];

Note that in reality you would probably want to include some form validation too!




回答3:


I agree with @Clément Malet & @Hammerstein. Sessions and/or cookies.

<?php 
    // always need this
    session_start();

    // set the value
    $_SESSION['username'] = 'Person';
?>

<?php
    //get session data
    echo $_SESSION['username'];

   // output: Person
?>



回答4:


  1. Start a php session on each page right after the opening php tag:

    session_start();

After you determine that the name and password work, and before you do the redirect, add this line:

$_SESSION['name'] = $name;

On any subsequent pages, just echo something like this:

echo "Welcome ".$_SESSION['name'];



回答5:


Use session variables

set:

session_start();
$_SESSION['username'] = "user1";

get:

session_start();
$username = $_SESSION['username'];


来源:https://stackoverflow.com/questions/25316186/how-do-i-share-a-php-variable-between-multiple-pages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!