下面这个例子是利用了php中的session_set_save_handler函数保存到数据库中,这个有点像小编写的购物车原理了,下面来看看这个例子,希望对各位有帮助。
PHP保存session默认的是采用的文件的方式来保存的,这仅仅在文件的空间开销很小的windows上是可以采用的,但是如果我们采用uinx或者是liux上的文件系统的时候,这样的文件系统的文件空间开销是很大的,然而session是要时时刻刻的使用的,大量的用户就要创建很多的session文件,这样对整个的服务器带来性能问题。
另一方面,如果服务器起采用群集的方式的话就不能保持session的一致性,所以我们就绪要采用数据库的方式来保存session,这样,不管有几台服务器同时使用,只要把他们的session保存在一台数据库服务器上就可以保证session的完整了,具体如何来实现请继续看下去。
PHP保存session默认的情况下是采用的文件方式来保存的,我们在PHP的配制文件PHP.ini中可以看到这样的一行:
session.save_handler="files"
这样的意思就是采用文件来保存session 的,要采用数据库来保存的话,我们需要修改成用户模式,改成
session.save_handler="use"
就可以了,但是,这仅仅是说明我门没有采用文件的方式存储session,我们还要选择数据库和建立数据库的表。
建立数据库和数据库的表结构,我们可以采用PHP可以使用的任何的数据库,因为PHP和mysql的结合最好,我就使用mysql来做示例,当然根据你的需要可以改称别的数据库。
创建数据库
create database 'session';
创建表结构
create table 'session'( id char(32) not null , 'user 'char(30), data char(3000) ,primary key ('id') );
PHP保存session编写PHP文件
代码如下 |
复制代码 |
<?php
$con = mysql_connect("127.0.0.1", "user" , "pass");
mysql_select_db("session");
function open($save_path, $session_name) {
return(true);
}
function close() {
return(true);
}
function read($id) {
if ($result = mysql_query("select * from session where id='$id'")) {
if ($row = mysql_felth_row($result)) {
return $row["data"];
}
} else {
return "";
}
}
function write($id, $sess_data) {
if ($result = mysql_query("update session set data='$sess_data' where id='$id'")) {
return true;
} else {
return false;
}
}
function destroy($id) {
if ($result = mysql_query("delete * from session where id='$id'")) {
return true;
} else {
return false;
}
}
function gc($maxlifetime) {
return true;
}
session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
session_start();
// proceed to use sessions normally
|
保存成为session_user_start.php。
现在我们的PHP保存session的工作就已经完成了,只要你在需要在使用session的时候,把session_user_start.php包含进来.注意,这个文件一定要在文件的第一行包含,然后就像使用文件的session一样的方法使用就可以了。
以上仅仅是个简单教程,在实际的应用中,可以对它封装得更专业些,参考代码如下:
SessionMysql.class.php
代码如下 |
复制代码 |
<?php
/**
* SessionMysql 数据库存储类
*/
defined('IN_QIAN') or exit('Access Denied');
class SessionMysql {
public $lifetime = 1800; // 有效期,单位:秒(s),默认30分钟
public $db;
public $table;
/**
* 构造函数
*/
public function __construct() {
$this->db = Base::loadModel('SessionModel');
$this->lifetime = Base::loadConfig('system', 'session_lifetime');
session_set_save_handler(
array(&$this, 'open'), // 在运行session_start()时执行
array(&$this, 'close'), // 在脚本执行完成 或 调用session_write_close() 或 session_destroy()时被执行,即在所有session操作完后被执行
array(&$this, 'read'), // 在运行session_start()时执行,因为在session_start时,会去read当前session数据
array(&$this, 'write'), // 此方法在脚本结束和使用session_write_close()强制提交SESSION数据时执行
array(&$this, 'destroy'), // 在运行session_destroy()时执行
array(&$this, 'gc') // 执行概率由session.gc_probability 和 session.gc_divisor的值决定,时机是在open,read之后,session_start会相继执行open,read和gc
);
session_start(); // 这也是必须的,打开session,必须在session_set_save_handler后面执行
}
/**
* session_set_save_handler open方法
*
* @param $savePath
* @param $sessionName
* @return true
*/
public function open($savePath, $sessionName) {
return true;
}
/**
* session_set_save_handler close方法
*
* @return bool
*/
public function close() {
return $this->gc($this->lifetime);
}
/**
* 读取session_id
*
* session_set_save_handler read方法
* @return string 读取session_id
*/
public function read($sessionId) {
$condition = array(
'where' => array(
'session_id' => $sessionId
),
'fields' => 'data'
);
$row = $this->db->fetchFirst($condition);
return $row ? $row['data'] : '';
}
/**
* 写入session_id 的值
*
* @param $sessionId 会话ID
* @param $data 值
* @return mixed query 执行结果
*/
public function write($sessionId, $data) {
$userId = isset($_SESSION['userId']) ? $_SESSION['userId'] : 0;
$roleId = isset($_SESSION['roleId']) ? $_SESSION['roleId'] : 0;
$grouId = isset($_SESSION['grouId']) ? $_SESSION['grouId'] : 0;
$m = defined('ROUTE_M') ? ROUTE_M : '';
$c = defined('ROUTE_C') ? ROUTE_C : '';
$a = defined('ROUTE_A') ? ROUTE_A : '';
if (strlen($data) > 255) {
$data = '';
}
$ip = get_ip();
$sessionData = array(
'session_id' => $sessionId,
'user_id' => $userId,
'ip' => $ip,
'last_visit' => SYS_TIME,
'role_id' => $roleId,
'group_id' => $grouId,
'm' => $m,
'c' => $c,
'a' => $a,
'data' => $data,
);
return $this->db->insert($sessionData, 1, 1);
}
/**
* 删除指定的session_id
*
* @param string $sessionId 会话ID
* @return bool
*/
public function destroy($sessionId) {
return $this->db->delete(array('session_id' => $sessionId));
}
/**
* 删除过期的 session
*
* @param $lifetime session有效期(单位:秒)
* @return bool
*/
public function gc($lifetime) {
$expireTime = SYS_TIME - $lifetime;
return $this->db->delete("`last_visit`<$expireTime");
}
}
|
在系统文件的某个地方,实例化这个类即可!
new SessionMysql();
如果你知道迅雷地址的生成规则你就不觉得迅雷的url资源下载地址有多么复杂了,其实雷的地址就是原url前面带AA后面带BB之后再base64_encode编码即可
如下例子
代码如下 |
复制代码 |
<?php
function Thunder($url, $type='en') {
$url ='http://www.111cn.net';
if($type =='en'){
return "thunder://".base64_encode("AA".$url."ZZ");
}else{
return substr(base64_decode(substr(trim($url),10)),2,-2);
}
}
$url ='http://www.111cn.net';
echo Thunder($url);
输出结果
thunder://QUFodHRwOi8vd3d3LjExMWNuLm5ldFpa
?>
|
标题有点说不清楚了就是否PHP获取指定日期所在月的第一天和最后一天几个段程序了了,下文给各位总结一下吧。
示例代码
代码如下 |
复制代码 |
//获取指定日期所在月的第一天和最后一天
function GetTheMonth($date){
$firstday = date("Y-m-01",strtotime($date));
$lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
return array($firstday,$lastday);
}
|
示例代码
//PHP获得指定日期所在星期的第一天和最后一天
代码如下 |
复制代码 |
function getdays($day){
$lastday=date('Y-m-d',strtotime("$day Sunday"));
$firstday=date('Y-m-d',strtotime("$lastday -6 days"));
return array($firstday,$lastday);
}
print_r(getdays('2012-06-2'));
|
示例代码
代码如下 |
复制代码 |
$date= 要处理的日期
* $step 0= 本月 ,正负表示得到本月前后的月份日期
* $date= 要处理的月份
* Enter description here ...
*/
function AssignTabMonth($date,$step){
$date= date("Y-m-d",strtotime($step." months",strtotime($date)));//得到处理后的日期(得到前后月份的日期)
$u_date = strtotime($date);
$days=date("t",$u_date);// 得到结果月份的天数
//月份第一天的日期
$first_date=date("Y-m",$u_date).'-01';
for($i=0;$i<$days;$i++){
$for_day=date("Y-m-d",strtotime($first_date)+($i*3600*24));
}
return $first_date.'至'.$for_day;
|
下面来看一个关于顺丰BSP订单号查询接口SOAP的请求示例,这个例子能帮助到各位同学哦。
在一些接口的设计中有时用到了SOAP方式的请求,比如顺丰BSP的接口。
我尝试不同方式的POST方式请求,要么完全请求不到东西,要么接收到乱码,均以失败告终。
针对顺丰接口的SOAP请求的核心代码分享如下:
代码如下 | 复制代码 |
/** * 发送soap请求 */ private function _soap() { $client = new SoapClient($this->serviceUrl); $info = new stdClass(); $info->arg0 = $this->xml; $param = array($info); $response = $client->__call(“sfexpressService”,$param); return $response->return ; } /** * 拼接出请求的xml */ public function createXml() { $xml = ‘ ’.$this->user.’,’.$this->passWord.’
invoice_no.’” />
’; $this->xml = $xml; } |
提示:
1.$this->serviceUrl 顺丰分配的BSP请求地址,注意是?wsdl的地址
2.$this->user,$this->passWord 即是顺丰分配的ID和校验码
3.返回的return是一个XML的String,你可能需要simplexml_load_string来解析。
原文来自:http://www.jxm.cc/blogs/498.html
下文整理了一段php管理nginx虚拟主机shell脚本,希望这段脚本能帮助到各位同学哦。
使用php作为shell脚本是一件很方便的事情。理所当然,我们可以使用php脚本来管理 nginx虚拟主机,下面是笔者的 脚本 文件供各位参考
代码如下 |
复制代码 |
#!/usr/bin/php -q
<?php
start: fwrite(STDOUT,"===========Vhost Script===========\n");
fwrite(STDOUT,"= Choose an operation \n");
fwrite(STDOUT,"= 1.Create 2.Delete 3.Exit\n");
fwrite(STDOUT,"==================================\n");
$operate = trim(fgets(STDIN));
if ( $operate == 1 ){
fwrite(STDOUT,"Please Enter a Domain Name:");
$domain = trim(fgets(STDIN));
$path = "/home/sites/{$domain}";
$nginx_conf = "/etc/nginx/sites/{$domain}";
$nginx_template = "/etc/nginx/template/site_conf";
$apache_conf = "/etc/httpd/conf/httpd.conf";
$conf_str = "";
//变量初始化
if( file_exists($path ) ) exit ("Domain Existed!\n");
else mkdir($path,0700);
if(file_exists($nginx_conf)) exit ("Nginx Config file existed!\n");
else {
$conf_str = file_get_contents( $nginx_template );
}
//目录检测及配置文件拷贝
eval ( "\$conf_str = \"$conf_str\";" );
$succes = file_put_contents($nginx_conf,$conf_str);
if( !$succes ) exit ("Write Config File Fauile!");
else echo "Create Vhost success!\n";
goto start;
//写入配置文件
}
else if ($operate == 2){
$confs_dir = dir("/etc/nginx/sites");
$confs_list = array();
$count = 0;
while ( false !== ( $conf_file = $confs_dir->read() ) ){
if( $conf_file == "." ) continue;
if( $conf_file == ".." ) continue;
if ( is_file( $confs_dir->path ."/". $conf_file) ) {
$confs_list[$count++] = $conf_file;
}
}
echo "Select a site by number which to delete:\n";
if( count( $confs_list ) >0 )
foreach ( $confs_list as $k=>$v ){
echo "{$k}. $v\n";
}
$index = trim(fgets(STDIN));
if( in_array ( $index,array_keys( $confs_list ) ) ){
copy( $confs_dir->path ."/". $confs_list[$index],"/etc/nginx/backup/{$confs_list[$index]}" );
unlink ( $confs_dir->path ."/". $confs_list[$index] );
exec("tar -zcf /home/sites/{$confs_list[$index]}.tar.gz /home/sites/".$confs_list[$index] );
exec("rm -Rf /home/sites/".$confs_list[$index]);
}
//删除指定配置,并保存备份
}
else if( $operate == 3 ) {
exit;
}
else {
exit ("No Operation Selected!");
}?>
|
下面是nginx的配置模版
代码如下 |
复制代码 |
server {
listen 80;
server_name {$domain};
access_log /var/log/nginx/{$domain}_access_log;
error_log /var/log/nginx/{$domain}_error_log;
root {$path};
#不记录对站点图标访问
location = /favicon.ico {
log_not_found off;
access_log off;
}
#不记录对robots.txt的访问
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location = / {
try_files @proxy;
}
location / {
index index.htm index.html index.php;
try_files \$uri @proxy;
}
#匹配html
location ~* \.(html|htm)$ {
expires 30s;
gzip off;
add_header Content-Encoding gzip;
try_files \$uri \$uri/ /wp-content/cache/supercache/\$http_host/\$request_uri/index.html.gz @proxy;
}
#匹配图片、脚本文件等
location ~* \.(jpe?g|gif|png|ico|css|js|flv|swf|avi|zip|rar|svg|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mp3)$ {
expires 30d;
}
#传递给apache
location @proxy {
index index.htm index.html index.php;
proxy_pass http://127.0.0.1:81;
include /etc/nginx/proxy.conf;
}
}
|
标签:[!--infotagslink--]