我和Alex正在学习PHP。我有两个名为.. file1.php和file2.php的文件。我在file1.php中有一个变量,我想在file2.php中引用它,我该怎么做?我知道这对你们大多数人来说都是一个愚蠢的问题,但我对此并不熟悉,而且我正在努力学习。提前谢谢,我将为您提供我的代码。
File1.php
<?php
if(isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$passwordmd5 = md5($password);
if(!empty($username) && !empty($password)){
$query = "SELECT `id` FROM `users` WHERE `username` = '$username' AND `password` = '$passwordmd5'";
if($queryrun = mysql_query($query)){
$query_num_rows = mysql_num_rows($queryrun);
if($query_num_rows == 0){
echo 'Invalid username and password';
} else if($query_num_rows == 1){
echo $user_id = mysql_result($queryrun, 0, 'id');
$_SESSION['user_id']=$user_id;
header('Location: index.php' . $username);
}
} else {
echo 'Enter a username and a password';
}
}
?>
File2.php
<?php
require 'core.php';
require 'connectdb.php';
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
echo '<a href = "logout.php"><input type = "submit" id = "logreg" value = "Logout" /></a>';
}else{
echo '<a href = "loginregister.php"><input type = "submit" id = "logreg" value = "Login/Register" /></a>';
}
?>
基本上,File1.php是网站的登录表单,我输入用户名并提交,如果我成功提交并登录,我希望我的按钮从&#34;登录/注册&#34更改;到#34;欢迎,&#34;,我该怎么办? 简而言之,如何将我在File1.php中输入的$ username变量传输到File2.php? 例如..我按下登录/注册按钮,我输入Alex作为用户名,输入123作为密码,然后按登录按钮。 (那将在file1.php中完成)考虑到用户和密码是正确的,我移动到file2.php而不是登录/注册按钮,我想要一个新按钮,或div(无论如何)显示与文本&#34;欢迎,亚历克斯&#34;或&#34;欢迎, - 用户名 - &#34;。我怎么能这样做?
答案 0 :(得分:2)
您需要在file2.php代码中包含session_start。如果file1.php不是第一页,您还需要在其开头添加session_start。
<?php
session_start();
require 'core.php';
require 'connectdb.php';
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
echo '<a href = "logout.php"><input type = "submit" id = "logreg" value = "Logout" /></a>';
}else{
echo '<a href = "loginregister.php"><input type = "submit" id = "logreg" value = "Login/Register" /></a>';
}
?>