php怎么判断用户是否登录,php检测用户登录状态

发布时间:2020-06-07编辑:脚本学堂
php判断用户是否登录的一段代码,通过session检测用户的登录状态,需要的朋友参考下。

1、首页 index.php
 

复制代码 代码示例:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
session_start();
if(isset($_SESSION["name"])&&time()>$_SESSION['name'] + 1200){
echo "<hr>";
echo $_SESSION['name'];
echo "<hr>";
echo "welcome back";
}else //用户是否登录
echo "<script>alert('先登陆。。。!');location.href='login.html';;</script>";
?>

2、用户登录页 login.php
 

复制代码 代码示例:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
session_start();
$conn=mysql_connect("localhost","root","");
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$userName=$_POST['userName'];
$userPwd=$_POST['userPwd'];
//$userPwd=md5(trim($_POST['userPwd']));
mysql_select_db(mydb,$conn);
$sql = "SELECT * FROM TABLES where username='".$userName."' and password='".$userPwd."'";
$rows=mysql_fetch_array( mysql_query($sql));
echo $sql;
if(empty($userName)){
echo "用户名NULL";
}else if(empty($userPwd)){
echo "密码NULL";
}else{
if($rows['password']==$userPwd)
{
 
echo "<script>alert('登陆成功。。。!');location.href='index.php';;</script>";
$_SESSION['name']=$userName;
}
else {
echo "<script>alert('用户名或密码错误!!!!');history.back();</script>";
}
}
mysql_close($conn);
?>

3、用户登录信息页 login.html
 

复制代码 代码示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>php判断用户是否登录 - www.jb200.com</title>
</head>
<body>
<form name="login" method="POST" action="login.php" >
<fieldset style="color:blue;;position:absolute;top:20%;left:35%">
<legend>登录</legend>
<p>用户名 <input type="text" name="userName" id="userName" /></p>
<p>密 码 <input type="password" name="userPwd" id="userPwd" /></p>
<p>   
<input type="submit" value="登录" style="color:blue" />  
<input type="reset" value="重置" style="color:blue" />
</fieldset>
</form>
</body>
</html>