Home > Backend Development > PHP Tutorial > php使用Cookie控制访问授权的方法_PHP

php使用Cookie控制访问授权的方法_PHP

WBOY
Release: 2016-05-31 13:17:15
Original
911 people have browsed it

本文实例讲述了php使用Cookie控制访问授权的方法。分享给大家供大家参考。具体如下:

代码如下:

    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表单 
    ?> 
     
   

 
     
       
 
           
 
            用户名 
           

 
            密码 
           

 
             
           
 
       
 
     
    } 
?>

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template