演示代码
index.php代码
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function automatic(){
var username=document.getElementById("username").value;
<?
if (is_array($_COOKIE['profile']) || is_object($_COOKIE['profile']))
{
foreach($_COOKIE['profile'] as $k=>$v) {
?>
var name1="<? echo $k;?>";
if(username=="<? echo $k;?>"){
document.getElementById("password").value="<? echo $v;?>";
}
<?
}
}
?>
}
</script>
<?
if(isset($_COOKIE['username'])){
echo '您已登录,用户名:'.$_COOKIE['username'];
echo "<br><a href=\"logout.php\">登出</a>";
}else{
?>
<form method="post" action="check.php">
<table width="300" border="1" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" align="center"><b>记住用户名和密码</b></td>
</tr>
<tr align="center">
<td>用 户 名:</td>
<td><input onchange="automatic()" type="text" id="username" value="<?php echo $_COOKIE['name'];?>" name="username"></td>
</tr>
<tr align="center">
<td>密码:</td>
<td><input type="text" id="password" name="password" ></td>
</tr>
<tr align="center">
<td>记住用户名和密码</td>
<td>
<?php
if($_COOKIE['remember'] == 1)
{?><input type="checkbox" name="remember" value="1" checked><?php }
else{($_COOKIE['remember'] == "")?><input type="checkbox" name="remember" value="1"><?php }?>
</td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="submit" value="提交" /></td>
</tr>
</table>
</form>
<?
}
?>
check.php
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$remember = $_POST['remember'];
//包含数据库连接文件
$conn = mysqli_connect('localhost','root','root','tuiguang')or ('error');
$result=mysqli_query($conn,"select * from user where username ='{$_POST['username']}' ");//查出对应用户名的信息,
while ($row=mysqli_fetch_array($result)) {//while循环将$result中的结果找出来
$dbusername=$row["username"];
$dbpassword=$row["password"];
}
if(isset($_POST['username']) && isset($_POST['password']) && $_POST['username']== $dbusername && $_POST['password']==$dbpassword ){
//登入成功
//设置$_COOKIE['username']有效期为30秒
setcookie(username, $password,time()+30);
if($remember == 1){
$profile='profile['.$username.']';
setcookie($profile, $password,time()+3600);
setcookie('remember',$remember,time()+3600);
}
echo $password;echo $password;
echo "登入成功";
header('location:index.php');
}else {
//登入失败
echo "对不起,用户名活密码填写错误!";
header('location:index.php');
}
// echo "<br>数组\$_COOKIE['profile']中的值";
// if (is_array($_COOKIE['profile']) || is_object($_COOKIE['profile']))
// {
// foreach($_COOKIE['profile'] as $k=>$v) {
// echo '<br>用户名:'.$k.'密码:'.$v;
// }
// }
// echo '<br/>';
// print_r(($_COOKIE['profile']));
}else{
echo "禁止直接访问!";
}
?>
logout.php
<?php
setcookie("username","$remember",time()-3600);
header('location:index.php');
?>
github源代码文件下载https://github.com/eyunzhu/php/tree/master/cookieEx

目前评论:0