In formal projects, there will basically be applications with authorization control, such as RBAC permissions, etc. This article helps novices better understand PHP and use cookies by sharing how to use cookies to control access authorization.
<?php if(isset($_POST['name'])||isset($_POST['pass'])){ //如果有表单有提交 //检测表单中需要的值 if(empty($_POST['name'])){ die("请输入用户名!"); } if(empty($_POST['pass'])){ die("请输入密码!"); } //设置数据库变量 $host = "localhost"; $user = "root"; $pass = "zq19890319"; $db = "cookie"; //打开连接 $connection = mysql_connect($host, $user, $pass) or die("Unable to connect!"); //选择一个数据库 mysql_select_db($db) or die("Unable to select database!"); //建立一个查询 $query = "SELECT * FROM users WHERE name = '".$_POST['name']."' AND pass = SHA1('".$_POST['pass']."')"; //执行一个查询 $result = mysql_query($query) or die("Error in query:$query." . mysql_error()); //是否有记录集返回 if(mysql_num_rows($result) == 1){ //如果有一行记录返回 //表示验证已经通过 //建立一个session,设置一个登陆标记为1,并将当前用户名保存在cookie中 session_start(); $_SESSION['auth'] = 1; setcookie("username", $_POST['name'], time()+(84600*30)); echo "用户访问已经授权!"; }else{ echo "错误的用户名或密码!"; } //释放记录集 mysql_free_result($result); //关闭数据库 mysql_close($connection); } else{ //如果没有表单提交,则显示一个HTML表单 ?> <html> <head></head> <body> <center> <form method="post" action=""> 用户名<input type="text" name="name" value="<?php echo $_COOKIE['username'];?>" /> <p /> 密码<input type="password" name="password" /> <p /> <input type="submit" name="submit" value="登陆" /> </form> </center> </body> <?php } ?>
Related recommendations:
ThinkPhp RBAC experience_PHP tutorial
PHP learning to write the perpetual calendar
PHP learning CURL crawler example
The above is the detailed content of Cookie control access authorization for beginners learning PHP. For more information, please follow other related articles on the PHP Chinese website!