PHP学习练手(十三)

来源:互联网 发布:lua 5.1 windows 编辑:程序博客网 时间:2024/06/05 09:21



特性: cookie将数据存储在用户的浏览器中。

流程:
这里写图片描述

这里写图片描述

代码:

1.login_page.inc.php

<?php #Script 12.1 - login.inc.php    $page_tile = 'Login';    include('../include/header.html');    if(isset($errors) && !empty($errors))    {        echo '<h1>Error!</h1>                    <p class="error">The following error(s) occurred:<br />';                    foreach ($errors as $msg) {                        echo "- $msg<br />\n";                    }                    echo '</p><p>Please try again.</p>';    }?><h1>Login</h1><form action="login1.php" method="post">    <p>Email Address: <input type="text" name="email" size="20" maxlength="60" /></p>    <p>Password: <input type="password" name="pass" size="20" maxlength="20" /></p>    <p><input type="submit" name="submit" value="Login" /></p></form><?php include('../include/footer.html'); ?>

注:
1、该页面使用.inc.php扩展名,指示它是一个可包含的文件并且它包含PHP代码

运行:
这里写图片描述

2.login_function.inc.php

<?php # Script 12.2 - login_functions.inc.php    //绝对url路径    //函数实现页面跳转到index1.php功能    function redirect_user($page = 'index1.php')    {        $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);        $url = trim($url, '/\\');        $url .= '/'.$page;        header("Location: $url");  //页面跳转        exit();    }    function check_login($mysqli, $email='', $pass='')    {        //检查email Address        if (empty($email))         {            $errors[] = 'You forgot to enter your email';        }else{            $e = mysqli_real_escape_string($mysqli, trim($email));        }        //检查pass        if (empty($pass))         {            $errors[] = 'You forgot to enter your email';        }else{            $p = mysqli_real_escape_string($mysqli, trim($pass));        }        if(empty($errors))        {            $sql = "SELECT user_id, first_name FROM users WHERE email = '$e' AND pass = SHA1('$p')";            $res = @mysqli_query($mysqli, $sql);            if(mysqli_num_rows($res) == 1)            {                $rows = mysqli_fetch_array($res, MYSQLI_ASSOC);                return array(true, $rows);            }else{                $errors[] = 'The email address and password entered do not match those on file';            }        }        return array(false, $errors);    }?>

注:
1、$_SERVER[‘HTTP_HOST’]:Contents of the Host: header from the current request, if there is one.根据客户端的HTTP请求输出信息
这里写图片描述

2、$_SERVER[‘PHP_SELF’] :表示当前 php 文件相对于网站根目录的位置地址
这里写图片描述

3、dirname() :函数返回路径中的目录部分
这里写图片描述

4、rtrim() :函数移除字符串右侧的空白字符或其他预定义字符

3.login.php

<?php # Script 12.3 - login.php    if($_SERVER['REQUEST_METHOD'] == 'POST')    {        require('../include/login_function.inc.php');        require_once ('../mysqli_connect.php');        list($check, $data) = check_login($mysqli, $_POST['email'], $_POST['pass']);        if($check)        {            setcookie('user_id', $data['user_id']);            setcookie('first_name', $data['first_name']);            redirect_user('loggedin.php');        }else{            $errors = $data;        }        mysqli_close($mysqli);    }    include('../include/login_page.inc.php');?>

注:
1、cookie必须在其他任何信息之前把它们从服务器发送给客户。万一服务器试图在web浏览器已经接收到HTML(甚至是无关紧要的空白)之后发送cookie,就会导致一条错误消息,并且不会发送cookie。

2、通过setcookie()函数发送cookie

3、cookie被限制为总共包含大约4KB的数据,每个Web浏览器可以记住来自任何一个站点的有限数量的cookie。对目前的大多数浏览器,这个限制是50个

运行:
这里写图片描述

4.loggedin.php

<?php # Script 12.4 - loggedin.php    if(!isset($_COOKIE['user_id']))    {        require('../include/login_function.inc.php');        redirect_user();    //登录不成功返回到首页index1.php    }    //print_r($_COOKIE);    $page_title = 'Logged In';    include('../include/header.html');    echo "<h1>Logged In</h1>                    <p>You are now logged in, {$_COOKIE['first_name']}</p>                    <p><a href=\"logout.php\">Logout</a></p>";    include('../include/footer.html');?>

注:
1、访问cookie:$_COOKIE

运行:
这里写图片描述

5.login1.php

<?php # Script 12.3 - login.php    if($_SERVER['REQUEST_METHOD'] == 'POST')    {        require('../include/login_function.inc.php');        require_once ('../mysqli_connect.php');        list($check, $data) = check_login($mysqli, $_POST['email'], $_POST['pass']);        if($check)        {            setcookie('user_id', $data['user_id'], time()+30, '/', '', 0, 0);            setcookie('first_name', $data['first_name'],time()+30, '/', '', 0, 0);            print_r($_COOKIE);            redirect_user('loggedin.php');        }else{            $errors = $data;        }        mysqli_close($mysqli);    }    include('../include/login_page.inc.php');?>

注:
1、setcookie('user_id', $data['user_id'], time()+30, '/', '', 0, 0); 设置cookie的到期时间

6.logout.php

<?php # Script 12.6 - logout.php    if(!isset($_COOKIE['user_id']))    {        require('../include/login_function.inc.php');        redirect_user();    }else{        setcookie('user_id', '', time()-3600, '/', '', 0, 0);        setcookie('first_name', '', time()-3600, '/', '', 0, 0);    }    $page_title = 'Loggout Out!';    include('../include/header.html');    echo "<h1>Logged Out!</h1>                <p>You are now logged out, {$_COOKIE['first_name']}!</p>";    include('../include/footer.html');?>

注:
1、删除cookie:
假设cookie设置为 setcookie(‘user’, ‘Lee’);
删除cookie方式一:setcookie(‘user’);
删除cookie方式二:setcookie(‘user’,”, time()-3600);//把到期日期设置成过去的某个日期

2、刚开始搞不懂:

test.php

<?php     setcookie('test','TEST');  //创建cookie    print_r($_COOKIE);?>

第一次在浏览器中刷新时,为什么输出的是空矩阵没有TEST值。然后运行:
test1.php

<?php    setcookie('test','',time()-3600);    //清除建立的cookie    print_r($_COOKIE);?>

已经把cookie注销了,为什么print_r还能输出值。
后来一番百度,终于找到详细的解释了:
php第一次无法获取cookie问题处理

现自己总结一下,加深印象O(∩_∩)O哈!
1)当在浏览器端第一次访问test.php脚本时,可以看到浏览器与服务端两者发送的消息头如下:
这里写图片描述

此时服务器响应setcookie命令,但是因为cookie是设置在客户端的,setcookie函数自己并不能设置cookie,它只能通过头信息的方式告诉浏览器说:兄弟,我要设置一个cookie,键为a,值为value,你在你那里帮我设置一下。

2)执行print_r($_COOKIE); 因为客户端访问服务器的时候,这个cookie压根就不存在,而前面第一步设置cookie的头信息,也还没有返回给客户端(php要从上到下把语句执行完才会返回给客户端),所以此时显示为空矩阵

3)再次刷新test.php。信息头如下:
这里写图片描述
此时返回COOKIEcookie访cookie_COOKIE中存储了值。发现此时浏览器确实保存了test的cookie记录:
这里写图片描述

4)第一次运行test1.php。发现test的cookie记录表不在了,说明成功删除了cookie
这里写图片描述
但是$_COOKIE中仍有值:
这里写图片描述
同理,这是因为print_r(COOKIE)cookie_COOKIE中还有值,再次刷新,则发现矩阵为空了:
这里写图片描述

运行:
这里写图片描述

7.修改后的header.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title><?php echo $page_title; ?></title>    <link rel="stylesheet" href="../include/style.css" type="text/css" media = "screen"></head><body>    <div id="header">        <h1>Your Website</h1>        <h2>catchy slogan...</h2>    </div>    <div id="navigation">        <ul>            <li><a href="index1.php">Home Page</a></li>            <li><a href="register.php">Register</a></li>            <li><a href="view_users5.php">View Users</a></li>            <li><a href="password.php">Change Password</a></li>            <li><?php                     if((isset($_COOKIE['user_id'])) && (basename($_SERVER['PHP_SELF']) != 'logout.php'))                    {                        echo '<a href = "logout.php">Logout</a>';                    }else{                        echo '<a href="login1.php">Login</a>';                    }            ?></li>        </ul>    </div>    <div id="content"><!-- Start of the page-specific content-->    <!-- Script 9.1 - header.html -->

注:
1、basename() 函数返回路径中的文件名部分。

0 0
原创粉丝点击