前端小白之每天學習記錄----php(7)session與cookie

來源:互聯網
上載者:User

標籤:1.0   put   lang   添加   func   tco   web服務   location   zhang   

伺服器端的會話技術(通訊協議)

坐地鐵:
深圳通
拿手機刷

cookie( 儲存在 用戶端的瀏覽器裡面的資料 )
session( 儲存在 web伺服器裡面的資料 )

如何使用cookie?

1.設定/登出cookie(建立cookie.php)

<?php/*array( ‘user‘ => ‘ghostwu‘ )*/// function setCookie(c_name,value,expiredays)                      // 變數名,值,到期天數setcookie( "user", "zhangsan" );//設定成功if( isset( $_GET[‘act‘] ) && $_GET[‘act‘] == ‘logout‘){    //time(): 擷取到當前的時間戳記    setcookie( "user", "", time() - 1 );//清空user的值,並使它到期}?>  <a href="?act=logout">登出</a>

 2.取出cookie(建立cookie2.php)

<?php    /*        php裡面的所有cookie都是儲存在超級全域變數 $_COOKIE 裡面        $_COOKIE是儲存在瀏覽器的類數組    */    // print_r( $_COOKIE );    // echo $_COOKIE[‘user‘];    if( !empty( $_COOKIE[‘user‘] ) ){        echo $_COOKIE[‘user‘];    }?>

 

3.一個設定cookie的登入頁面(建立login.php)

登入成功時候用cookie儲存使用者名稱與密碼

setcookie( "name", $userName ); /

setcookie( "pwd", $userPwd );

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <title>Document</title>  <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">  <style>    .reg-form {      margin-top: 100px;    }  </style></head><body><!-- 連結資料庫 -->  <?phprequire( ‘./mysql.class.php‘ );//連結資料庫的類檔案,請參考本系列上一節?><!-- html文本 -->    <div class="container">      <div class="row">        <div class="tip"></div>        <form class="form-horizontal reg-form" role="form" method="post">          <div class="form-group">            <label for="firstname" class="col-md-2 control-label">使用者名稱:</label>            <div class="col-md-6">              <input type="text" class="form-control" id="user" name="user" placeholder="請輸入使用者名稱">            </div>          </div>          <div class="form-group">            <label for="lastname" class="col-md-2 control-label">密碼</label>            <div class="col-md-6">              <input type="password" name="pwd" class="form-control" id="pwd" placeholder="請輸入密碼">            </div>          </div>          <div class="form-group">            <div class="col-sm-offset-2 col-sm-10">              <button type="submit" class="btn btn-primary">登入</button>            </div>          </div>        </form>      </div>    </div><!-- PHP文本 -->    <?phpif( !empty( $_POST[‘user‘] ) && !empty( $_POST[‘pwd‘] ) ){ //判斷使用者名稱密碼非空    $userName = $_POST[‘user‘];    $userPwd = $_POST[‘pwd‘];    $sql = "SELECT * FROM user_info WHERE user_name = ‘$userName‘ AND user_pwd = ‘$userPwd‘";     $res = mysql_query( $sql );   //查詢使用者名稱密碼    if( $res && mysql_num_rows( $res ) ){ //如果查詢成功,並且帳號密碼正確        setcookie( "name", $userName ); //設定cookie        setcookie( "pwd", $userPwd );        header("Location:success.php"); //設定完跳轉到success.php頁面?>    <!-- <script>        window.location.href = ‘./success.html‘;    </script> --><?php    }else {   //登入不成功,重新載入頁面        header("Location:login.php");?>    <!-- <script>        window.location.href = ‘./error.html‘;    </script> --><?php    }}?></body></html>

  

 

4.使用儲存的cookie --->登入成功頁面(建立success.php)

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title></head><body>    <?php        if( empty( $_COOKIE[‘name‘] ) ){    //是否有使用者名稱            header("Location:login.php");   // 沒有使用者名稱則跳到登入頁面        }        //這裡要添加一條判斷 資料庫查詢使用者名稱與密碼是否正確        //判斷方法與登入頁面相同,如果使用者名稱密碼錯誤,跳去登入頁面        //點擊登出頁面:使cookie到期        if( isset( $_GET[‘act‘] ) && $_GET[‘act‘] == ‘logout‘ ){            setcookie( ‘name‘, ‘‘, time() - 1 ); //登出cookie            header("Location:login.php"); //登出後跳轉到登入頁面        }    ?>   <h3>歡迎您<!-- 把cookie儲存的使用者名稱取出來 --><?php echo !empty($_COOKIE[‘name‘]) ? $_COOKIE[‘name‘] : ‘‘; ?> !登入</h3> | <!-- 登出按鈕 --><a href="?act=logout">登出</a></body></html>

如何使用session?

1.設定/登出session(建立session.php)

   <?php    /*        要使用session, 必須先要用session_start() 開啟session               web伺服器上會建立一個類數組$_SESSION    */    session_start();    $_SESSION[‘name‘] = ‘zhangsan‘;    if( isset( $_GET[‘act‘] ) && $_GET[‘act‘] == ‘logout‘  ){        //刪除某個數組的一項,或者刪除一個變數        unset( $_SESSION[‘name‘] );    }?><a href="?act=logout">登出</a>

2.取出session(建立session2.php)

<?php    session_start();    if( !empty( $_SESSION[‘name‘] ) ){        echo $_SESSION[‘name‘];    }?>

3.一個設定session的登入頁面(建立login2.php)

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <title>Document</title>  <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">  <style>    .reg-form {      margin-top: 100px;    }  </style></head><body>  <?php  session_start();require( ‘./mysql.class.php‘ );?>    <div class="container">      <div class="row">        <div class="tip"></div>        <form class="form-horizontal reg-form" role="form" method="post">          <div class="form-group">            <label for="firstname" class="col-md-2 control-label">使用者名稱:</label>            <div class="col-md-6">              <input type="text" class="form-control" id="user" name="user" placeholder="請輸入使用者名稱">            </div>          </div>          <div class="form-group">            <label for="lastname" class="col-md-2 control-label">密碼</label>            <div class="col-md-6">              <input type="password" name="pwd" class="form-control" id="pwd" placeholder="請輸入密碼">            </div>          </div>          <div class="form-group">            <div class="col-sm-offset-2 col-sm-10">              <button type="submit" class="btn btn-primary">登入</button>            </div>          </div>        </form>      </div>    </div><?phpif( !empty( $_POST[‘user‘] ) && !empty( $_POST[‘pwd‘] ) ){    $userName = $_POST[‘user‘];    $userPwd = $_POST[‘pwd‘];    $sql = "SELECT * FROM user_info WHERE user_name = ‘$userName‘ AND user_pwd = ‘$userPwd‘";     $res = mysql_query( $sql );     if( $res && mysql_num_rows( $res ) ){        $_SESSION[‘name‘] = $userName;        $_SESSION[‘pwd‘] = $userPwd;        header("Location:success2.php");?>    <!-- <script>        window.location.href = ‘./success.html‘;    </script> --><?php    }else {        header("Location:login2.php");?>    <!-- <script>        window.location.href = ‘./error.html‘;    </script> --><?php    }}?></body></html>

4.使用儲存的session --->登入成功頁面(建立succeed2.php)

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title></head><body>    <?php        session_start();    //開啟session        require("./mysql.class.php");//連結資料庫的類檔案,請參考本系列上一節?><?php    if( empty( $_SESSION[‘name‘] ) ){//判斷使用者名稱是否為空白        header("Location:login2.php");    }    else if ( !empty( $_SESSION[‘name‘] ) ){//使用者名稱非空        $sql = "SELECT * FROM user_info WHERE user_name = ‘{$_SESSION[‘name‘]}‘ AND user_pwd = ‘{$_SESSION[‘pwd‘]}‘";        $res = $mysql->query( $sql );        if( !( $res && mysql_num_rows( $res ) ) ){//使用者名稱密碼正確            header("Location:login2.php");        }    }    if( isset( $_GET[‘act‘] ) && $_GET[‘act‘] == ‘logout‘ ){//是否登出        unset( $_SESSION[‘name‘] ); //移除使用者名稱        header("Location:login2.php");    }    ?>   <h3>歡迎您<?php echo !empty( $_SESSION[‘name‘] ) ? $_SESSION[‘name‘] : ‘‘; ?>! 登入測試人員中樞</h3>    <a href="?act=logout">登出</a> </body></html>

5.在註冊頁面註冊成功的時候儲存session --->註冊頁面(建立reg.php)

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <title>Document</title>  <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">  <style>    .reg-form {      margin-top: 100px;    }  </style></head><body>  <?php  session_start();require( ‘./mysql.class.php‘ );?>    <div class="container">      <div class="row">        <div class="tip"></div>        <form class="form-horizontal reg-form" role="form" method="post">          <div class="form-group">            <label for="firstname" class="col-md-2 control-label">使用者名稱:</label>            <div class="col-md-6">              <input type="text" class="form-control" id="user" name="user" placeholder="請輸入使用者名稱">            </div>          </div>          <div class="form-group">            <label for="lastname" class="col-md-2 control-label">密碼</label>            <div class="col-md-6">              <input type="password" name="pwd" class="form-control" id="pwd" placeholder="請輸入密碼">            </div>          </div>          <div class="form-group">            <div class="col-sm-offset-2 col-sm-10">              <button type="submit" class="btn btn-primary">註冊</button>            </div>          </div>        </form>      </div>    </div>    <?phpif( !empty( $_POST[‘user‘] ) && !empty( $_POST[‘pwd‘] ) ){    $userName = $_POST[‘user‘];    $userPwd = $_POST[‘pwd‘];    $sql = ‘SELECT * FROM user_info WHERE user_name = "‘ . $userName . ‘"‘;    $res = mysql_query( $sql );    if( $res && mysql_num_rows( $res ) ){ //使用者名稱存在       ?>        <script>            document.querySelector(".tip").innerHTML = ‘你輸入的使用者名稱已經存在‘;        </script>        <?php     }else { //使用者名稱, 開始註冊了        $sql = "INSERT INTO user_info ( user_name, user_pwd ) VALUES( ‘$userName‘, ‘$userPwd‘ )";        $res = mysql_query( $sql );        if( $res !== false ){            $_SESSION[‘name‘] = $userName;            $_SESSION[‘pwd‘] = $userPwd;            ?>        <script>            document.querySelector(".tip").innerHTML = ‘使用者名稱註冊成功‘;        </script>             <?php        }else {            ?>        <script>            document.querySelector(".tip").innerHTML = ‘使用者名稱註冊失敗‘;        </script>             <?php        }    }}?></body></html>

  

 

 

 

  

前端小白之每天學習記錄----php(7)session與cookie

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.