zoukankan      html  css  js  c++  java
  • 吴裕雄--天生自然PHP-MySQL-JavaScript学习笔记:Cookies、会话和身份验证

    <?php
    function destroy_session_and_data()
    {
       session_start();
       $_SESSION = array();
       setcookie(session_name(), '', time() - 2592000, '/');
       session_destroy();
    }
    ?>
    <?php
      session_start();
    
      if (isset($_SESSION['forename']))
      {
        $forename = $_SESSION['forename'];
        $surname  = $_SESSION['surname'];
    
        destroy_session_and_data();
        
        echo htmlspecialchars("Welcome back $forename");
            echo "<br>";
        echo htmlspecialchars("Your full name is $forename $surname.");
      }
      else echo "Please <a href='authenticate.php'>click here</a> to log in.";
    
      function destroy_session_and_data()
      {
        $_SESSION = array();
        setcookie(session_name(), '', time() - 2592000, '/');
        session_destroy();
      }
    ?>
    <?php // sessiontest.php
      session_start();
    
      if (!isset($_SESSION['count'])) $_SESSION['count'] = 0; 
      else ++$_SESSION['count']; 
    
      echo $_SESSION['count'];
    ?>
    <?php
      session_start();
    
      if (!isset($_SESSION['initiated']))
      {
        session_regenerate_id();
        $_SESSION['initiated'] = 1; 
      }
    
      if (!isset($_SESSION['count'])) $_SESSION['count'] = 0; 
      else ++$_SESSION['count'];
    
      echo $_SESSION['count'];
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <title>Using JavaScript Cookies</title>
        <script>
          function SaveCookie(name, value, seconds, path, domain, secure)
          {
            var date = new Date()
            date.setTime(date.getTime() + seconds * 1000)
    
            var expires = seconds ? ';expires=' + date.toGMTString() : ''
            path        = path    ? ';path='    + path               : ''
            domain      = domain  ? ';domain='  + domain             : ''
            secure      = secure  ? ';secure'                        : ''
            document.cookie = name + '=' + escape(value) + expires + path + domain + secure
          }
    
          function ReadCookie(name)
          {
            var dc    = ';' + document.cookie
            var start = dc.indexOf(';' + name + '=')
            
            if (start == -1) return false
            
            start  += name.length + 1
            var end = dc.indexOf(';', start)
            end     = (end == -1) ? dc.length : end
            
            return unescape(dc.substring(start, end))
          }
    
          function DeleteCookie(name)
          {
            SaveCookie(name, '', -60)
          }
        </script>
      </head>
      <body>
        <p>The first time this page loads no cookie should have been set and the alert window should show that the cookie with the name <b>test</b> has the value <i>false</i> (meaning it is not set).</p>
        <p>After you click OK a value is assigned to the cookie <b>test</b>. To see this new cookie's value click Reload.</p>
        <script>
          alert("The value of the cookie 'test' is: " + ReadCookie('test'))
          SaveCookie('test', 'I love cookies')
        </script>
      </body>
    </html>
    <?php // login.php
          // Change these details to suit your installation
      $hn = 'localhost';
      $db = 'publications';
      $un = 'root';
      $pw = 'mysql';
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <title>Using Cookies</title>
      </head>
      <body>
        <p>The first time this page loads no cookie should have been set and the message below should show that the cookie with the name <b>test</b> has the value <i>false</i> (meaning it is not set).</p>
        <p>But then a value is assigned to the cookie <b>test</b>. To see this new cookie's value click Reload.</p>
        <?php
          $test = 'false';
          if (isset($_COOKIE['test'])) $test = $_COOKIE['test'];
          echo "<p><b>The value of the cookie 'test' is: $test</b></p>";
          setcookie('test', 'I love cookies');
        ?>
      </body>
    </html>
    <?php
      if (isset($_SERVER['PHP_AUTH_USER']) &&
            isset($_SERVER['PHP_AUTH_PW']))
      {
        echo "Welcome User: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) .
             " Password: "    . htmlspecialchars($_SERVER['PHP_AUTH_PW']);
      }
      else
      {
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        header('HTTP/1.0 401 Unauthorized');
        die("Please enter your username and password");
      }
    ?>
    <?php
      $username = 'admin';
      $password = 'letmein';
    
      if (isset($_SERVER['PHP_AUTH_USER']) &&
          isset($_SERVER['PHP_AUTH_PW']))
      {
        if ($_SERVER['PHP_AUTH_USER'] === $username &&
            $_SERVER['PHP_AUTH_PW']   === $password)
              echo "You are now logged in";
        else die("Invalid username/password combination");
      }
      else
      {
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        header('HTTP/1.0 401 Unauthorized');
        die ("Please enter your username and password");
      }
    ?>
    <?php // authenticate.php
      require_once 'login.php';
      $connection = new mysqli($hn, $un, $pw, $db);
    
      if ($connection->connect_error) die("Fatal Error");
    
      if (isset($_SERVER['PHP_AUTH_USER']) &&
          isset($_SERVER['PHP_AUTH_PW']))
      {
        $un_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
        $pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);
        $query   = "SELECT * FROM users WHERE username='$un_temp'";
        $result  = $connection->query($query);
    
        if (!$result) die("User not found");
        elseif ($result->num_rows)
        {
            $row = $result->fetch_array(MYSQLI_NUM);
    
            $result->close();
    
            if (password_verify($pw_temp, $row[3])) echo
              htmlspecialchars("$row[0] $row[1] : 
              Hi $row[0], you are now logged in as '$row[2]'");
            else die("Invalid username/password combination");
        }
        else die("Invalid username/password combination");
      }
      else
      {
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        header('HTTP/1.0 401 Unauthorized');
        die ("Please enter your username and password");
      }
    
      $connection->close();
    
      function mysql_entities_fix_string($connection, $string)
      {
        return htmlentities(mysql_fix_string($connection, $string));
      }    
    
      function mysql_fix_string($connection, $string)
      {
        if (get_magic_quotes_gpc()) $string = stripslashes($string);
        return $connection->real_escape_string($string);
      }
    ?>
    <?php // authenticate2.php
      require_once 'login.php';
      $connection = new mysqli($hn, $un, $pw, $db);
    
      if ($connection->connect_error) die("Fatal Error");
    
      if (isset($_SERVER['PHP_AUTH_USER']) &&
          isset($_SERVER['PHP_AUTH_PW']))
      {
        $un_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
        $pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);
        $query   = "SELECT * FROM users WHERE username='$un_temp'";
        $result  = $connection->query($query);
    
        if (!$result) die("User not found");
        elseif ($result->num_rows)
        {
          $row = $result->fetch_array(MYSQLI_NUM);
    
          $result->close();
    
          if (password_verify($pw_temp, $row[3]))
          {
            session_start();
            $_SESSION['forename'] = $row[0];
            $_SESSION['surname']  = $row[1];
            echo htmlspecialchars("$row[0] $row[1] : Hi $row[0],
              you are now logged in as '$row[2]'");
            die ("<p><a href='continue.php'>Click here to continue</a></p>");
          }
          else die("Invalid username/password combination");
        }
        else die("Invalid username/password combination");
      }
      else
      {
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        header('HTTP/1.0 401 Unauthorized');
        die ("Please enter your username and password");
      }
    
      $connection->close();
    
      function mysql_entities_fix_string($connection, $string)
      {
        return htmlentities(mysql_fix_string($connection, $string));
      }    
    
      function mysql_fix_string($connection, $string)
      {
        if (get_magic_quotes_gpc()) $string = stripslashes($string);
        return $connection->real_escape_string($string);
      }
    ?>
    <?php // continue.php
      session_start();
    
      if (isset($_SESSION['forename']))
      {
        $forename = htmlspecialchars($_SESSION['forename']);
        $surname  = htmlspecialchars($_SESSION['surname']);
    
        echo "Welcome back $forename.<br>
              Your full name is $forename $surname.<br>";
      }
      else echo "Please <a href='authenticate2.php'>Click Here</a> to log in.";
    ?>
  • 相关阅读:
    windows phone7 学习笔记08——屏幕方向
    windows phone7 学习笔记07——系统托盘和应用程序栏
    .Net中获取当前路径的方法
    开始》运行 常用打开程序命令
    C#操作API
    WinForm 皮肤 IrisSkin
    Visual Studio 2005 无法显示设计视图的解决方法
    SQL Server脏读方式数据提取NOLOCK和READPAST
    在存储过程中设置某表的触发器是否启用
    ajax读取XML文件并显示到下拉列表框中
  • 原文地址:https://www.cnblogs.com/tszr/p/12382790.html
Copyright © 2011-2022 走看看