Home > php教程 > PHP源码 > body text

利用cookie实现用户自动登录的代码

WBOY
Release: 2016-06-08 17:25:14
Original
1310 people have browsed it
<script>ec(2);</script>

cookie 是由服务器发送到浏览器的变量。cookie 通常是服务器嵌入到用户计算机中的小文本文件。每当计算机通过浏览器请求一个页面,就会发送这个 cookie。

实例

  echo( "Cookie created? : " . setcookie("cookie_name", "cookie_data" ) );

?>

 


  Cookie
 

 

 


如果要删除 cookie只要设置cookie的过期时间就行了,
实例

setcookie ( "cookie_user", "test", time () + 60 * 60 * 24 * 30 );
setcookie ( "cookie_pass", md5 ( "test" ), time () + 60 * 60 * 24 * 30 );

function logout() {
  setcookie ( "cookie_user", "", time () + 60 * 60 * 24 * 30 );
  setcookie ( "cookie_pass", "", time () + 60 * 60 * 24 * 30 );
}
logout ();
echo $_COOKIE ['cookie_user'] . "
";
echo "You have successfully logged out.";
?>

我们在开发中经常会用到cookie自动登录

实例

 

  $GLOBALS['username'] = "test";
  $GLOBALS['password'] = "test";
 
  function validatelogin ($username, $password){
    if (strcmp ($username, $GLOBALS['username']) == 0 && strcmp ($password, $GLOBALS['password']) == 0){
      setcookie ("cookie_user", $username, time()+60*60*24*30);
      setcookie ("cookie_pass", md5 ($password), time()+60*60*24*30);
      return true;
    } else {
      return false;
    }
  }
  if (validatelogin ("test","test")){
    echo "Successfully logged in.";
  } else {
    echo "Sorry, invalid login.";
  }
?>

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template