WP程序之session功能应用介绍
session可以让你的程序更安全、更高效。可惜的是,Wordpress核心并不支持session。下面这个示意图是不支持session的wordpress的在被已登录用户访问时的情况:
no-session-diagram
很容易理解,是吧?
基本上,每次加载页面
- 或在每次用户定位到新页面 -
程序都要从数据库中查询必要的信息,然后将其呈现给用户。
这可能也是Wordpress相对于支持session的CMS核心来说比较浪费不锈钢气动隔膜泵服务器资源的原因之一。
那么,如果程序是支持session的呢?
假如程序支持session,我们设置为:
不为没登录的访客设置session;
为登录的用户设置session;
用户退出时销毁session。
那会是怎么样呢?看下面的示意图:
Wordpress:session
简而言之:一旦用户登录,session会将某些信息存储进一个全局数组,以减轻不锈钢气动隔膜泵数据库的负担。
2.Wordpress是否支持session?
WordPress核心不支持session,它支持cookie。
3.如何让Wordpress支持session?
上面简要介绍了session是什么以及其用途,并且说明了Wordpress核心不支持session,现在的问题就是:如何让Wordpress支持session了:
不多废话了,直接将Wordpress.org社区成员Peter
Wooster的插件Simple Session Support 的源码发上来吧:
<?php
/*
Plugin
Name: Simple Session Support
Plugin URI:
http://devondev.com/simple-session-support/
Description: Adds PHP session support for developers, destroys session at log
off
Version: 1.1
Author: Peter Wooster
Author URI: http://www.scol.com.cn/
*/
/* Copyright (C) 2011 Devondev Inc.
(http://devondev.com)
This program is free
software; you can redistribute it and/or modify
it under the terms of the
GNU General Public License as published by
the Free Software
Foundation; either version 2 of the License, or
(at your option) any later
version.
This program is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY;
without even the implied warranty of
MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the
GNU General Public License
for more details.
You should have received a
copy of the GNU General Public License
along with this program; if
not, write to the Free Software
Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* add actions at
initialization to start the session
* and at
logout and login to end the session
*/
add_action(‘init‘, ‘simpleSessionStart‘, 1);
add_action(‘wp_logout‘,
‘simpleSessionDestroy‘);
add_action(‘wp_login‘, ‘simpleSessionDestroy‘);
/**
* start the session, after this call the PHP
$_SESSION super global is available
*/
function simpleSessionStart() {
if(!session_id())session_start();
}
/**
* destroy the session, this removes any data
saved in the session over logout-login
*/
function simpleSessionDestroy() {
session_destroy ();
}
/**
* get a value from
the session array
* @param type $key the key
in the array
* @param type $default the value
to use if the key is not present. empty string if not present
* @return type the value found or the default
if not found
*/
function simpleSessionGet($key, $default=‘‘) {
if(isset($_SESSION[$key]))
{
return $_SESSION[$key];
} else {
return $default;
}
}
/**
* set a value in
the session array
* @param type $key the key
in the array
* @param type $value the value
to set
*/
function simpleSessionSet($key, $value) {
$_SESSION[$key] =
$value;
}
/*
=========================================================================
* end of program, php close tag intentionally omitted
WP程序之session功能应用介绍,布布扣,bubuko.com
原文:http://www.cnblogs.com/shhxpump/p/3598165.html