您好我知道这是一个常见问题,但我认为我的代码没有任何问题,但我想知道为什么我的 $ _ SESSION ['myusername']; 没有显示当前登录的用户
下面是我的main.php:
<?php
session_start();
if(isset($_SESSION['myusername'])){
header("location: index.php");
}
echo "Hello " .$_SESSION['myusername'];
?>
我的checklogin.php
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="dbscholaris"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "main.php"
$_SESSION["myusername"] = $myusername;
$_SESSION["mypassword"] = $mypassword;
header("location:main.php");
}
else {
echo "Wrong Username or Password";
}
?>
请帮我找到我失踪的东西。感谢
答案 0 :(得分:0)
您必须将$ myusername和$ mypassword导出到$_SESSION
,如下所示:
$_SESSION["myusername"] = stripslashes($myusername);
$_SESSION["mypassword"] = stripslashes($mypassword);
你忘记了作业。此外,您还必须撤消该变量的mysql_real_esacpe_string()
。 (或者之前存储一个非转义版本。)
此外,您应该确保会话已启动。这可以通过
完成session_start();
在对$_SESSION
进行任何读取或写入之前或通过设置php ini指令
session.auto_start = 1
答案 1 :(得分:0)
尝试第一个代码
<?php
session_start();
if(isset($_POST['myusername'])){
$_POST['myusername'] = $_SESSION['myusername'];
header("location: index.php");
}
echo "Hello " .$_SESSION['myusername'];
?>
答案 2 :(得分:0)
我会解释它不允许你看到你的页面,因为你正在做if(isset($ _ SESSION ['myusername'])) 并不是 如果(!isset($ _ SESSION [ '名为myUsername'])) 这告诉php会话myusername是否不存在转到index.php else ignore