如何在多个页面之间共享PHP变量? [英] How do I share a PHP variable between multiple pages?

查看:176
本文介绍了如何在多个页面之间共享PHP变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想法/目标:

我的计算机上的文本文件中有一个用户名和密码.索引页面上的表单允许用户使用其用户名和密码登录.在登录页面上,PHP用于使用我在本地文本文件中拥有的信息来验证用户输入的信息.用户输入的信息与我的文本文件信息匹配后,用户立即被重定向到主页,其中显示他们的名字并显示欢迎消息.

问题:

一切,直到验证成功为止.问题是,当我将用户重定向到Home.php时,我无法显示其用户名.完成所有验证后,我将如何显示其用户名?无论如何,我可以将他们的用户名永久存储在一个变量中,该变量可以在我所有页面上访问吗?

具有以下格式的Index.php页面

用于验证表单信息与我在本地文本文件中拥有的信息的登录页面

解决方案

使用$_SESSION-!

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

您当然想过滤/清理/验证您的$ _POST数据,但这超出了此问题的范围...

只要在使用$_SESSION之前调用session_start();-$_SESSION数组中的值将在页面中保留,直到用户关闭浏览器为止.

如果您想在此之前结束会话,例如在注销按钮中---使用session_destroy()

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

解决方案

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()

这篇关于如何在多个页面之间共享PHP变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆