COOKIE/SESSION原理:
作业:独立完成新用户注册的过程 ,并详细会话的完整流程,以及注意事项
<?php
//根据用户操作,给出不同响应
//登录、注册、退出
$dbConfig =[
'type'=>'mysql',
'host' => 'localhost',
'dbname' => 'testsql',
'port'=>'3306',
'charset'=>'utf8',
'username' => 'zolo',
'password' => '123456'
];
//import variables into the current symbol table from an array
extract($dbConfig);
$db = new PDO("$type:host=$host;port=$port;dbname=$dbname;charset=$charset",$username,$password);
$sqlquery = "select * from `user`";
$stmt = $db->prepare($sqlquery);
$stmt ->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
// foreach($res as $user){
// printf('<pre>%s</pre>',print_r($user,true));}
session_start();
$method = $_GET['action'];
switch(strtolower($method)){
case 'login':
if($_SERVER['REQUEST_METHOD']=='POST'){
extract($_POST);
//echo "登录信息是:".$username.'<br>';
array_filter($res,function($user) use ($name,$password){
if($user['name'] == $name && $user['password'] == $password){
$_SESSION['name']= $name;
exit('<script>alert("登录成功");location.href="home.php"</script>');
}else{
exit('<script>alert("用户名或密码错误");location.href="login.php"</script>');
}
});
}else{
echo '登录错误';
}
break;
case 'register':
if($_SERVER['REQUEST_METHOD']=='POST'){
extract($_POST);
if($password == $confirpsw){
array_filter($res,function($user) use ($name,$password,$db){
if($user['name'] == $name){
//$_SESSION['name']= $name;
exit('<script>alert("用户已存在,请登录");location.href="login.php"</script>');
}else{
if($name && $password){
$sql = 'INSERT `user` SET `name` = ?,`password`= ?';
$stmt = $db->prepare($sql);
$stmt ->execute([$name,$password]);
$_SESSION['name']= $name;
exit('<script>alert("恭喜,注册成功");location.href="home.php"</script>');
}else{
exit('<script>alert("非法数据");location.href="register.php"</script>');
}
}
});
}else{
exit('<script>alert("两次输入密码不一致");location.href="register.php"</script>');
}
}
break;
case 'logout':
echo '设置session.name为空';
session_unset();
exit('<script>alert("退出成功");location.assign("home.php")</script>');
break;
}
代码流程图