龚哥哥 爱生活、做自己!
PHP文件生成模块
发表于 2015-9-1 | 浏览(1729) | PHP
<?php
 /*
 *    描    述    :    把数据写入文件
 */
 namespace Model\Backend;
 class FilePutModel
 {
    /* 关闭自动连接数据库 */
    protected $autoCheckFields = false;
    private $m_DirName;  //目录地址
    private $m_FileName;  //文件名称
    private $m_Suffis;  //文件后缀名
    private $m_DataArray;  //需要写入文件的数据
    /*
     *    构造方法
     */
    public function __construct($DirName, $FileName, $DataArray, $Suffis = null)
    {
        $this->m_DirName = null;
        $this->m_FileName = null;
        $this->m_FileSuffix = null;
        $this->m_DataArray = array();
        /* 基础数据设置 */
        $this->m_DirName = $DirName;
        $this->m_FileName = $FileName;
        $this->m_FileSuffix = $Suffis;
        $this->m_DataArray = $DataArray;
        
        /* 基础数据处理 */
        $this->IsDirThere();
        $this->IsFileSuffix();
    }
    /*
     *    数据处理
     */
    public function SetFileData()
    {
        if(false == empty($this->m_FileName) && false == empty($this->m_DataArray)) {
            $Statu = file_put_contents(PATH_PHP_FILE.$this->m_FileName.'.'.$this->m_FileSuffix, "<?php\n\rreturn ".var_export($this->m_DataArray, true).";\n\r?>");
            if(false != $Statu) {
                return true;
            } else {
                return false;
            }
        } else {
            return '数据不能为空!';
        }
    }
    
    /*
     *    判断目录是否存在
     */
    private function IsDirThere()
    {
        if(false == is_dir($this->m_DirName)) {
            mkdir($this->m_DirName, 0777, true);
        }
    }
    
    /*
     *    判断后缀名是否存在
     */
    private function IsFileSuffix()
    {
        if(true == empty($this->m_FileSuffix)) {
            $this->m_FileSuffix = 'php';
        }
    }
}
 ?>
//使用说明
$FilePutObj = new \Model\Backend\FilePutModel('路径',文件名称,'数据','文件后缀名');
        if(true == $FilePutObj->SetFileData()) {
            //成功
        }

阅读全文

PHP中常见的字符编码设置,截取字符部分
发表于 2015-9-1 | 浏览(1683) | PHP
echo mb_substr('你aa好啊反反复复', 0, 6, 'utf-8').'<br />';   //mb_substr— 获取字符串的部分
  你aa好啊反

echo mb_strlen('ww刚好刚').'<br />';
  11

echo $str = '我好啊';  // 一个字符 3 字节
  我好啊

echo '<br />';
echo $ff = mb_detect_encoding($str).'<br />';   //mb_detect_encoding 检测字符的编码
  UTF-8

$ret = mb_convert_encoding($str, 'GBK', 'UTF-8');   //mb_convert_encoding— 转换字符的编码
  echo mb_strlen($str).'<br />';   //mb_strlen— 获取字符串的长度
    9
  echo mb_strlen($ret).'<br />';
    6

$a = "翻盖手机,MOTO,you like it?";
  echo mb_substr($a,0,6,"UTF-8");
    翻盖手机,M

阅读全文

2015最新微信支付APP 服务端处理
发表于 2015-9-1 | 浏览(2333) | PHP
<?php

/**
 * 微信支付驱动
 * @author  Devil
 * @version v_1.0.0
 */
class WeiXin
{
    private $config;

    /**
     * [__construct 从数据库读取微信申请的密钥]
     */
    public function __construct() 
    {
        $this->config = array(
                'partner_id'        =>  '',
                'partner_key'       =>  '',
                'appid'             =>  '',
                'secret'            =>  '',
                'pay_sign_key'      =>  '',
                'notify_url'        =>  '',
            );
    }

    /**
     * [Get_App_Code 生成支付信息]
     * @param  [array] $order   [订单数据]
     * @return [string]         [支付信息]
     */
    public function Get_App_Code($order)
    {
        /* 标题空格处理 */
        if(!empty($order['subject'])) $order['subject'] = str_replace(array(' ', "\n", "\r"), '', $order['subject']);

        $access_token = $this->Get_Access_Token();
        $param = array(
            'appid'         =>  $this->config['appid'],
            'traceid'       =>  $order['out_trade_no'],
            'noncestr'      =>  md5(time().rand()),
            'package'       =>  $this->GetParamData($order),
            'timestamp'     =>  time(),
            'sign_method'   =>  'sha1',
        );

        /* 获取支付签名 */
        $param['app_signature'] = $this->GetAppSign($param);

        /* 生成预支付 */
        $data = $this->GenprePayInsert($param, $access_token);

        /* 生成支付信息 */
        if(!empty($data['prepayid']) && !empty($data['errmsg']) && $data['errmsg'] == 'Success')
        {
            $pay = array(
                    'appid'         =>  $this->config['appid'],
                    'noncestr'      =>  $param['noncestr'],
                    'package'       =>  'Sign=WXPay',
                    'partnerid'     =>  $this->config['partner_id'],
                    'prepayid'      =>  $data['prepayid'],
                    'timestamp'     =>  $param['timestamp']
                );
            $pay['sign'] = $this->GetAppSign($pay);
            return $pay;
        }
        return '';
    }

    /**
     * [GenprePayInsert 生成预支付]
     * @param [array] $param        [请求参数]
     * @param [token] $access_token [token]
     */
    private function GenprePayInsert($param, $access_token)
    {
        return json_decode($this->Curl_Post('https://api.weixin.qq.com/pay/genprepay?access_token='.$access_token, json_encode($param)), true);
    }

    /**
     * [GetAppSign signature签名生成]
     * @param [array] $param    [参数数据]
     */
    private function GetAppSign($param)
    {
        unset($param['sign_method']);
        $param['appkey'] = $this->config['pay_sign_key'];
        ksort($param);
        return sha1($this->SetParam($param));
    }

    /**
     * [GetParamData 获取参数数据]
     * @param  [array] $data    [订单数据]
     * @return [array]          [参数和sign]
     */
    private function GetParamData($data)
    {
        $order = array(
            'bank_type'         =>  'WX',
            'body'              =>  $data['subject'],
            'total_fee'         =>  $data['total_fee']*100, /* 微信要求需要乘以100 */
            'spbill_create_ip'  =>  $GLOBALS['pz_log']->Getip(),
            'out_trade_no'      =>  $data['out_trade_no'],
            'notify_url'        =>  $this->config['notify_url'],
            'partner'           =>  $this->config['partner_id'],
            'fee_type'          =>  1,
            'input_charset'     =>  'UTF-8',
            'attach'            =>  'weixin',
        );
        ksort($order);

        $sgin = strtoupper(md5($this->SetParam($order).'&key='.$this->config['partner_key']));
        return $this->SetParam($order, true).'&sign='.$sgin;
    }

    /**
     * [Curl_Post curl模拟post]
     * @param  [string] $url  [请求地址]
     * @param  [array] $post  [发送的post数据]
     */
    private function Curl_Post($url, $post) {
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => false,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $post,
        );

        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * [SetParam url模式字符串拼接]
     * @param [array]  $param         [需要拼接的参数]
     * @param [boolean] $is_urlencode [是否urlencode转义value]
     */
    private function SetParam($param, $is_urlencode = false)
    {
        $str = '';
        foreach($param as $k=>$v) 
        {
            if($is_urlencode)
            {
                $str .= $k.'='.urlencode($v).'&';
            } else {
                $str .= $k.'='.$v.'&';
            }
        }
        return substr($str, 0, -1);
    }

    /**
     * [Get_Access_Token 获取微信支付token]
     * @return [string]         [token]
     */
    private function Get_Access_Token()
    {   
        if(file_exists('/tmp/weixin_pay_token.json'))
        {
            $temp = json_decode(file_get_contents('/tmp/weixin_pay_token.json'), true);
            if($temp['time'] > time()) $token = $temp['token'];
        }
        if(empty($token)) $token = $this->Set_Access_Token();
        return $token;
    }

    /**
     * [Set_Access_Token token设置]
     * @return [string]     [token]
     */
    private function Set_Access_Token()
    {
        $temp = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->config["appid"].'&secret='.$this->config['secret']), true);
        if(!empty($temp['access_token']))
        {
            $data = array(
                    'token' =>  $temp['access_token'],
                    'time'  =>  time()+7000
                );
            if(!is_dir('/tmp')) mkdir('/tmp');
            file_put_contents('/tmp/weixin_pay_token.json', json_encode($data));
            return $temp['access_token'];
        }
        return '';
    }

    /**
     * [Respond 响应操作]
     * @return [string] [响应处理结果]
     */
    public function Respond()
    {
        $param = $_GET;
        if(empty($param)) return;
        $param_sign = $param['sign']; unset($param['sign']);

        ksort($param);
        $sign = strtoupper(md5($this->SetParam($param).'&key='.$this->config['partner_key']));
        if($param_sign != $sign) return;

        /* check_money方法 价格校验是否一致 */
        if(isset($param['trade_state']) && $param['trade_state'] == 0 && check_money($param['out_trade_no'], $param['total_fee']/100))
        {
            //如果成功这里就可以处理自己的订单了,标识符是 $param['out_trade_no']
        }
    }
}

?>

阅读全文

PHP单例模式 设计模式 面向对象
发表于 2015-9-1 | 浏览(1824) | PHP
<?php

/**
 * 单例模式
 * @author  Devil
 * @version v_0.0.1
 */
class Singleton
{
	private $parem;

	/**
	 * [__construct 构造方法]
	 * @param [mixed] $param [参数]
	 */
	private function __construct($param)
	{
		$this->param = $param;
	}

	/**
	 * [Instantiate 静态方法, 用于实例化类]
	 * @param  [mixed] $param [参数]
	 * @return [object]   [类对象]
	 */
	public static function Instantiate($param)
	{
		static $object = null;
		if(!is_object($object)) $object = new self($param);
		return $object;
	}

	/**
	 * [Show 测试方法]
	 */
	public function Show()
	{
		print_r($this->param);
	}
}



/**
 * 使用列子
 */
$param = array('test', 'demo', 'devil');
$obj = Singleton::Instantiate($param);
$obj->Show();

/**
 * $obj = Singleton::Instantiate($param);
 * 不管在项目中多少次这么对类进行实例化,都不会重复创建类对象。
 * $object 被定义成静态变量,不能被第二次赋值。
 * 只要$object是一个对象就直接返回当前对象,则进行实例化并返回。
 *
 * 单例模式可以防止重复创建对象,减轻内存开销。
 */

?>

阅读全文

PHP支付宝接口类 WEB版 即时到帐接口
发表于 2015-9-1 | 浏览(1967) | PHP
<?php

/**
 * 支付宝支付驱动
 * @author  Devil
 * @version v_1.0.0
 */
class Alipay
{
    private $config;

    /**
     * [__construct 构造方法, 初始化配置信息]
     */
    public function __construct()
    {
        $this->config = array(
            'alipay_key'        =>  '', //key
            'alipay_partner'    =>  '', //partner
            'alipay_account'    =>  '', //支付宝账户名称
            'notify_url'        =>  '', //异步通知地址
            'call_back_url'     =>  '', //同步返回地址
        );
    }

    /**
     * [Payment 生成即时到帐支付信息]
     * @param  [array] $order [订单数据]
     */
    public function Payment($order)
    {
        $param = array(
            'service'           => 'create_direct_pay_by_user',
            'partner'           => $this->config['alipay_partner'],
            '_input_charset'    => 'utf-8',
            'notify_url'        => $this->config['notify_url'],
            'return_url'        => $this->config['call_back_url'],

            /* 业务参数 */
            'subject'           => $order['name'],
            'out_trade_no'      => $order['number_id'],
            'price'             => $order['total_fee'],
            'quantity'          => 1,
            'payment_type'      => 1,

            /* 物流参数 */
            'logistics_type'    => 'EXPRESS',
            'logistics_fee'     => 0,
            'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE',

            /* 买卖双方信息 */
            'seller_email'      => $this->config['alipay_account']
        );
        ksort($param);
        $string = '';
        $sign  = '';

        foreach($param AS $key=>$val)
        {
            $string .= "$key=" .urlencode($val). "&";
            $sign  .= "$key=$val&";
        }

        $string = substr($string, 0, -1);
        $sign  = md5(substr($sign, 0, -1).$this->config['alipay_key']);
        header('location:https://mapi.alipay.com/gateway.do?'.$string. '&sign='.$sign.'&sign_type=MD5');
    }

    /**
     * [Respond 异步请求处理]
     * @return [string] [成功success, 失败其它]
     */
    public function Respond()
    {
        /* 参数处理 */
        if (!empty($_POST))
        {
            foreach($_POST as $key => $val)
            {
                $_GET[$key] = $val;
            }
        }
        $param = $_GET;
        ksort($param);

        /* 判断是否已经处理过 */
        $this->IsRespond($param);

        /* 签名校验 */
        $sign = '';
        foreach($param AS $key=>$val)
        {
            if($key != 'sign' && $key != 'sign_type' && $key != 'code')
            {
                $sign .= "$key=$val&";
            }
        }
        $sign = md5(substr($sign, 0, -1).$this->config['alipay_key']);
        if($Sign == $param['sign'] && $param['trade_status'] == 'TRADE_SUCCESS')
        {
            //$param['out_trade_no'] 参数是唯一标识符
            exit('success');
        }
    }

    /**
     * [IsRespond 是否处理过操作]
     * @param [array] $param [参数]
     */
    private function IsRespond($param)
    {
        //$param['out_trade_no'] 参数是唯一标识符
        //如果处理过了可以直接exit('success');
    }
}

?>

阅读全文

CentOS安装PHP错误:error: xml2-config not found
发表于 2015-9-1 | 浏览(1490) | 服务器

错误

configure: error: xml2-config not found. Please check your libxml2 installation.

解决方案

yum install libxml2
yum install libxml2-devel

阅读全文

安装PHP错误:configure: error: mcrypt.h not found. Plea
发表于 2015-9-1 | 浏览(1470) | 服务器

今天在编译php的时候,出现如下错误php安装出错:configure: error: mcrypt.h not found. Please reinstall libmcrypt.,意思是,没有查找到mcrytp.h,需要安装libcrytp,在下面的地址下载libmarypt:

解决办法一

1、安装第三方yum源
wget http://www.atomicorp.com/installers/atomic
chmod a+x chmod
sh ./atomic

2、使用yum命令安装
yum  install  php-mcrypt  libmcrypt  libmcrypt-devel 

解决办法二

使用php mcrypt 前必须先安装Libmcrypt

wget ftp://mcrypt.hellug.gr/pub/crypto/mcrypt/attic/libmcrypt/libmcrypt-2.5.7.tar.gz

安装

tar -zxvf libmcrypt-2.5.7.tar.gz
cd libmcrypt-2.5.7
mkdir -p /usr/local/libmcrypt
./configure prefix=/usr/local/libmcrypt/
make
make install

然后再安装PHP

========================================================================

如果以上方法仍然不能安装,请参考:

rpm -ivh "http://www.lishiming.net/data/attachment/forum/month_1211/epel-release-6-7.noarch.rpm

yum install -y libmcrypt-devel 

因为centos6.x 默认的yum源没有libmcrypt-devel 这个包,只能借助第三方yum源。

文章原创地址:http://blog.163.com/yxba_02/blog/static/1875576201272583532588/

阅读全文

PHP支付宝支付接口pc+wap MD5加密方式
发表于 2015-8-31 | 浏览(4217) | PHP
<?php

/**
 * 支付宝支付驱动
 * @author  Devil
 * @version V_1.0.0
 */
class AlipayLibrary
{
	/**
	 * [__construct 构造方法]
	 */
	public function __construct(){}

	/**
	 * [SoonPay 立即支付]
	 * @param [array] $data [支付信息]
	 */
	public function SoonPay($data, $config)
	{
		if(empty($data) || empty($config)) return false;

                //这里判断是否是手机访问,自己写一个方法接口。根据访问终端类型进行区分pc或wap
		if(IsMobile())
		{
			$this->SoonPayMobile($data, $config);
		} else {
			$this->SoonPayWeb($data, $config);
		}
	}

	/**
	 * [SoonPayMobile wap支付]
	 * @param  [array] $data   [参数列表]
	 * @param  [array] $config [配置信息]	
	 */
	private function SoonPayMobile($data, $config)
	{
		$request_token = $this->GetRequestToken($data, $config);

		$req_data = '<auth_and_execute_req><request_token>'.$request_token.'</request_token></auth_and_execute_req>';
		$parameter = array(
			'service'				=>	'alipay.wap.auth.authAndExecute',
			'format'				=>	'xml',
			'v'						=>	'2.0',
			'partner'				=>	$config['id'],
			'sec_id'				=>	'MD5',
			'req_data'				=>	$req_data,
			'request_token'			=>	$request_token
		);

		$param = $this->GetParamSign($parameter, $config);
		header('location:http://wappaygw.alipay.com/service/rest.htm?'.$param['param']. '&sign='.md5($param['sign']));

	}

	/**
	 * [GetRequestToken 获取临时token]
	 * @param  [array] $data   [参数列表]
	 * @param  [array] $config [配置信息]
	 * @return [string]        [返回临时token]
	 */
	private function GetRequestToken($data, $config)
	{
		$parameter = array(
			'service'				=>	'alipay.wap.trade.create.direct',
			'format'				=>	'xml',
			'v'						=>	'2.0',
			'partner'				=>	$config['id'],
			'req_id'				=>	$data['order_sn'],
			'sec_id'				=>	'MD5',
			'req_data'				=>	$this->GetReqData($data, $config),
			'subject'				=>	$data['name'],
			'out_trade_no'			=>	$data['order_sn'],
			'total_fee'				=>	$data['total_price'],
			'seller_account_name'	=>	$config['name'],
			'call_back_url'			=>	$data['call_back_url'],
			'notify_url'			=>	$data['notify_url'],
			'out_user'				=>	$data['out_user'],
			'merchant_url'			=>	$data['merchant_url'],
		);
		
		$param = $this->GetParamSign($parameter, $config);
        $ret = urldecode(file_get_contents('http://wappaygw.alipay.com/service/rest.htm?'.$param['param'].'&sign='.md5($param['sign'])));

        $para_split = explode('&',$ret);
        //把切割后的字符串数组变成变量与数值组合的数组
        foreach ($para_split as $item) {
            //获得第一个=字符的位置
            $nPos = strpos($item,'=');
            //获得字符串长度
            $nLen = strlen($item);
            //获得变量名
            $key = substr($item,0,$nPos);
            //获得数值
            $value = substr($item,$nPos+1,$nLen-$nPos-1);
            //放入数组中
            $para_text[$key] = $value;
        }

        $req = Xml_Array($para_text['res_data']);
        if(empty($req['request_token']))
        {
        	exit(header('location:'.__ROOT__.'index.php?g=Info&c=Prompt&f=PromptInfo&state=error&content=支付宝异常错误&url='.__ROOT__));
        }

        return $req['request_token'];
	}

	private function GetReqData($data, $config)
	{
		return '<direct_trade_create_req>
					<subject>'.$data['name'].'</subject>
					<out_trade_no>'.$data['order_sn'].'</out_trade_no>
					<total_fee>'.$data['total_price'].'</total_fee>
					<seller_account_name>'.$config['name'].'</seller_account_name>
					<call_back_url>'.$data['call_back_url'].'</call_back_url>
					<notify_url>'.$data['notify_url'].'</notify_url>
					<out_user>'.$data['out_user'].'</out_user>
					<merchant_url>'.$data['merchant_url'].'</merchant_url>
					<pay_expire>3600</pay_expire>
					<agent_id>0</agent_id>
				</direct_trade_create_req>';
	}

	/**
	 * [SoonPayWeb web支付]
	 * @param [array] $data   [订单信息]
	 * @param [array] $config [配置信息]
	 */
	private function SoonPayWeb($data, $config)
	{
        $parameter = array(
            'service'           => 'create_direct_pay_by_user',
            'partner'           => $config['id'],
            '_input_charset'    => ML_CHARSET,
            'notify_url'        => $data['notify_url'],
            'return_url'        => $data['call_back_url'],

            /* 业务参数 */
            'subject'           => $data['name'],
            'out_trade_no'      => $data['order_sn'],
            'price'             => $data['total_price'],

            'quantity'          => 1,
            'payment_type'      => 1,

            /* 物流参数 */
            'logistics_type'    => 'EXPRESS',
            'logistics_fee'     => 0,
            'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE',

            /* 买卖双方信息 */
            'seller_email'      => $config['name']
        );

        $param = $this->GetParamSign($parameter, $config);
		header('location:https://mapi.alipay.com/gateway.do?'.$param['param']. '&sign='.md5($param['sign']).'&sign_type=MD5');
	}

	/**
	 * [GetParamSign 生成参数和签名]
	 * @param  [array] $data   [待生成的参数]
	 * @param  [array] $config [配置信息]
	 * @return [array]         [生成好的参数和签名]
	 */
	private function GetParamSign($data, $config)
	{
        $param = '';
        $sign  = '';
        ksort($data);

		foreach($data AS $key => $val)
        {
            $param .= "$key=" .urlencode($val). "&";
            $sign  .= "$key=$val&";
        }

        return array(
        	'param'	=>	substr($param, 0, -1),
        	'sign'	=>	substr($sign, 0, -1).$config['key']
        );
	}

	/**
	 * [Respond 异步处理]
	 * @param  [array] $config [配置信息]
	 * @return [array|string] [成功返回数据列表,失败返回no]
	 */
	public function Respond($config)
	{
		if(empty($config)) return 'no';

        $data = empty($_POST) ? $_GET :  array_merge($_GET, $_POST);
		ksort($data);

		$sign = '';
		$sec = isset($data['sec_id']) ? $data['sec_id'] : '';
		if($sec == 'MD5')
		{
            $data_xml = json_decode(json_encode((array) simplexml_load_string($data['notify_data'])), true);
            $data = array_merge($data, $data_xml);
            $sign = 'service='.$data['service'].'&v='.$data['v'].'&sec_id='.$data['sec_id'].'&notify_data='.$data['notify_data'];
		} else {
	        foreach($data AS $key=>$val)
	        {
	            if ($key != 'sign' && $key != 'sign_type' && $key != 'code')
	            {
	                $sign .= "$key=$val&";
	            }
	        }
	        $sign = substr($sign, 0, -1);
	    }
        if(!isset($data['sign']) || md5($sign.$config['key']) != $data['sign']) return 'no';

        /* 支付状态 */
        $state = isset($data['trade_status']) ? $data['trade_status'] : $data['result'];
        switch($state)
        {
            case 'TRADE_SUCCESS':
                return $data;
                break;

            case 'TRADE_FINISHED':
                return $data;
                break;

               case 'success':
                return $data;
                break;
        }
        return 'no';
	}

}
?>

阅读全文

PHP图片上传
发表于 2015-8-31 | 浏览(1560) | PHP
<?php

/**
 * 图片上传驱动
 * @author 	Devil
 * @version 1.0.0
 */
class ImageLibrary
{
	private $i_path;
	private $i_type;
	private $i_is_new_name;
	private $i_quality;
	private $i_data;

	/**
	 * [__construct 构造方法]
	 * @param [array] $parameters [参数列表]
	 */
	private function __construct($parameters)
	{
		/* 检测是否支持gd */
		$this->IsGD();

		/* 图片类型 */
		$this->i_type = empty($parameters['type']) ? $this->GetImageType() : $parameters['type'];

		/* 图片名称是否使用新名称, 则使用原图片名称 */
		$this->i_is_new_name = (isset($parameters['is_new_name']) && is_bool($parameters['is_new_name'])) ? $parameters['is_new_name'] : true;

		/* jpg图片的质量值, 值越大质量越好 */
		$this->i_quality = max(75, isset($parameters['quality']) ? intval($parameters['quality']) : 75);
	}

	/**
	 * [Instance 静态方法实例化本类]
	 * @return [object] [实例对象]
	 */
	public static function Instance($parameters = array())
	{
		static $object = null;
		if(!is_object($object)) $object = new self($parameters);
		return $object;
	}

	/**
	 * [SetParameters 参数设置]
	 * @param [array] $parameters [参数列表]
	 */
	public function SetParameters($parameters = array())
	{
		if(empty($parameters)) return;
		$this->__construct($parameters);
	}

	/**
	 * [Is_GD 检查是否支持gd库]
	 */
	private function IsGD()
	{
		if(!isset(gd_info()['GD Version']) || empty(gd_info()['GD Version'])) Api_Return(L('code_412'), 412);
	}

	/**
	 * [GetImageType 获取图片后缀类型]
	 * @return [array] [图片后缀类型]
	 */
	private function GetImageType()
	{
		return array(
			'gif'	=> 'image/gif',
			'png'	=> 'image/png',
			'jpg'	=> 'image/jpeg',
			'bmp'	=> 'image/bmp'
		);
	}

	/**
	 * [Initialization 基本信息初始化]
	 * @param  [array]   $data [临时图片数据]
	 * @param  [string]  $path [图片保存路径]
	 * @return [boolean]	   [true或false]
	 */
	private function Initialization($data, $path)
	{
		if(empty($data)) return false;

		/* 图片保存地址 */
		$path .= (substr($path, -1) == '/') ? '' : '/';
		$this->i_path = empty($path) ? '/tmp/image' : $path;

		/* 设置存储路径是否存在 */
		if(!is_dir($this->i_path)) @mkdir($this->i_path, 0777, true);
		if(!@opendir($this->i_path)) exit('dir not access');

		/* 初始化返回数据 */
		$this->i_data = array();

		return true;
	}

	/**
	 * [GetNewFileName 获取随机名称]
	 * @return [string] [新的名称]
	 */
	private function GetNewFileName()
	{
		return date('YmdHis').str_shuffle(rand());
	}

	/**
	 * [SaveBaseImages base64图片存储]
	 * @param  [array] $data  [需要存储的base数据, 一维数组]
	 * @param  [string] $path [存储路径]
	 * @return [array] 		  [返回图片地址, 一维数组]
	 */
	public function SaveBaseImages($data, $path)
	{
		if(!$this->Initialization($data, $path)) return null;

		for($i=0; $i<count($data); $i++)
		{
			if(empty($data[$i])) continue;

			$temp_img = str_replace(array("\n", '\n', ' '), '', $data[$i]);
			$img_info = @getimagesize('data://application/octet-stream;base64,'.$temp_img);
			if(empty($img_info['mime'])) continue;

			$type = $this->Is_ImageType($img_info['mime']);
			if($type == 'no') continue;

			$file_name = $this->GetNewFileName().'.'.$type;
			if(file_put_contents($this->i_path.$file_name, base64_decode($temp_img)) !== false) $this->i_data[] = $file_name;
		}
		return $this->i_data;
	}

	/**
	 * [SaveBinaryImages 二进制图片保存]
	 * @param  [array]  $data [二进制图片数据, 一维数组]
	 * @param  [string] $path [存储路径]
	 * @return [array] 		  [返回图片地址, 一维数组]
	 */
	public function SaveBinaryImages($data, $path)
	{
		if(!$this->Initialization($data, $path)) return null;

		for($i=0; $i<count($data); $i++)
		{
			if(empty($data[$i])) continue;

			$img_info = getimagesizefromstring($data[$i]);
			if(empty($img_info['mime'])) continue;

			$type = $this->Is_ImageType($img_info['mime']);
			if($type == 'no') continue;

			$file_name = $this->GetNewFileName().'.'.$type;
			if(file_put_contents($this->i_path.$file_name, $data) !== false) $this->i_data[] = $file_name;
		}
		return $this->i_data;
	}

	/**
	 * [GetOriginal 获取临时图片文件的原图]
	 * @param  [array]  $data [临时图片数据]
	 * @param  [string] $path [存储路径]
	 * @return [string] 	  [返回图片地址]
	 */
	public function GetOriginal($data, $path)
	{
		if(!$this->Initialization($data, $path)) return '';

		if(empty($data['tmp_name'])) return '';

		$type = $this->Is_ImageType($data['type']);
		if($type == 'no') return '';

		$file_name = $this->GetNewFileName().'.'.$type;

		if(move_uploaded_file($data['tmp_name'], $this->i_path.$file_name)) return $file_name;
		return '';
	}

	/**
	 * [GetBinaryCompress 获取指定图片路径的压缩图]
	 * @param  [string] $file  [图片地址]
	 * @param  [string] $path  [存储路径]
	 * @param  [int] 	$width [设定图片宽度]
	 * @param  [int] 	$height[指定图片高度, 不指定则高度按照比例自动计算]
	 * @return [string] 	   [返回图片地址]
	 */
	public function GetBinaryCompress($file, $path, $width = 0, $height = 0)
	{
		if(!$this->Initialization($file, $path) || is_array($file) || !file_exists($file)) return '';

		$img_info = pathinfo($file);
		if(empty($img_info['basename'])) return '';

		$type = $this->Is_ImageType($img_info['extension']);
		if($type == 'no') return '';

		$file_name = ($this->i_is_new_name) ? $this->GetNewFileName().'.'.$type : $img_info['basename'];

		if($this->ImageCompress($width, $height, $file, $type, $this->i_path.$file_name)) return $file_name;
		
		return '';
	}

	/**
	 * [GetCompress 获取临时图片文件的压缩图]
	 * @param  [array]  $data  [临时图片数据]
	 * @param  [string] $path  [存储路径]
	 * @param  [int] 	$width [设定图片宽度]
	 * @param  [int] 	$height[指定图片高度, 不指定则高度按照比例自动计算]
	 * @return [atring|空字符串] [返回图片存储的名称]
	 */
	public function GetCompress($data, $path, $width = 0, $height = 0)
	{
		if(!$this->Initialization($data, $path)) return '';

		if(empty($data['tmp_name'])) return '';
		
		$type = $this->Is_ImageType($data['type']);
		if($type == 'no') return '';

		$file_name = $this->GetNewFileName().'.'.$type;

		if($this->ImageCompress($width, $height, $data['tmp_name'], $type, $this->i_path.$file_name)) return $file_name;
		return '';
	}

	/**
	 * [GetCompressCut 临时图像裁剪]
	 * @param [array]  	$data       [图像临时数据]
	 * @param [string] 	$path       [图像存储地址]
	 * @param [int] 	$width      [指定存储宽度]
	 * @param [ing] 	$height     [指定存储高度]
	 * @param [ing] 	$src_x      [裁剪x坐标]
	 * @param [ing] 	$src_y      [裁剪y坐标]
	 * @param [ing] 	$src_width  [裁剪区域宽度]
	 * @param [ing] 	$src_height [裁剪区域高度]
	 * @return [atring|空字符串] [返回图片存储的名称]
	 */
	function GetCompressCut($data, $path, $width = 0, $height = 0, $src_x = 0, $src_y = 0, $src_width = 0, $src_height = 0)
	{
		if(!$this->Initialization($data, $path)) return '';

		if(empty($data['tmp_name'])) return '';
		
		$type = $this->Is_ImageType($data['type']);
		if($type == 'no') return '';

		$file_name = $this->GetNewFileName().'.'.$type;

		if($this->ImageCompress($width, $height, $data['tmp_name'], $type, $this->i_path.$file_name, $src_x, $src_y, $src_width, $src_height)) return $file_name;
		return '';
	}

	/**
	 * [ImageCompress 图片压缩]
	 * @param  [int] 	$width [指定图片宽度]
	 * @param  [int] 	$height[指定图片高度]
	 * @param  [string] $file  [原图片地址]
	 * @param  [string] $type  [类型]
	 * @param  [string] $path  [新图片地址]
	 * @return [boolean] 	   [成功true, 失败false]
	 */
	private function ImageCompress($width, $height, $file, $type, $path, $src_x = 0, $src_y = 0, $src_width = 0, $src_height = 0)
	{
		/* 获取图片原本尺寸 */
		list($w, $h) = getimagesize($file);
		
		/* 尺寸计算 */
		$new_width = ($width > 0 && $w > $width) ? $width : $w;
		$new_height = ($width > 0 && $w > $width) ? (round($h/($w/$width))) : $h;
		if($width > 0 && $height > 0) $new_width = $width;
		if($height > 0) $new_height = $height;

		/* url创建一个新图象 */
		switch($type)
	    {
	        case 'gif':
	            $src_im = @imagecreatefromgif($file);
	            break;
	        case 'png':
	            $src_im = @imagecreatefrompng($file);
	            break;
	        default:
	            $src_im = @imagecreatefromjpeg($file);
	    }
	    if(!$src_im) return;

	    /* 新建一个真彩色图像 */
	    $dst_im = imagecreatetruecolor($new_width, $new_height);

	    /* 是否裁剪图片 */
	    if($src_width > 0 && $src_height > 0)
	    {
	    	/* 新建拷贝大小的真彩图像 */
	    	$cpd_im = imagecreatetruecolor($src_width, $src_height);

	    	/* 拷贝图片 */
		    imagecopy($cpd_im, $src_im, 0, 0, $src_x, $src_y, $src_width, $src_height);

		    /* 图片缩放 */
		    $s = imagecopyresampled($dst_im, $cpd_im, 0, 0, 0, 0, $new_width, $new_height, $src_width, $src_height);
		} else {
			/* 图片缩放 */
	    	$s = imagecopyresampled($dst_im, $src_im, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
		}
	    
	    if($s)
	    {
		    switch($type)
		    {
		        case 'png':
		            imagepng($dst_im, $path);
		            break;
		        case 'gif':
		            imagegif($dst_im, $path);
		            break;
		        default:
		            imagejpeg($dst_im, $path, $this->i_quality);
		    }
		}
		imagedestroy($dst_im);
		imagedestroy($src_im);

		return $s;
	}

	/**
	 * [Is_ImageType 验证后缀名是否合法]
	 * @param  [string] $image_type [图片后缀类型]
	 * @return [string] 			[后缀名或no]
	 */
	private function Is_ImageType($image_type)
	{
		if(empty($image_type)) return 'no';
		if(array_key_exists($image_type, $this->i_type)) return $image_type;

		foreach($this->i_type as $key=>$val)
		{
			if($val == $image_type) return $key;
		}
		return 'no';
	}
}
?>

阅读全文

PHP Memcached操作类
发表于 2015-8-31 | 浏览(1763) | PHP
<?php

/**
 * 缓存驱动
 * @author 	Devil
 * @version 1.0.0
 */
class CacheLibrary
{
	private $c_obj;
	private $c_time;
	/**
	 * [__construct 构造方法]
	 */
	public function __construct($host, $port = 11211)
	{
		/* 实例化memcached */
		$this->c_obj = new Memcached();
		if(!$this->c_obj->addServer($host, $port)) Api_Return(L('code_413'), 413);

		/* 基础参数设置 */
		$this->c_time = empty(C('cache')['time']) ? 0 : C('cache')['time'];
	}

	/**
	 * [GetTime 获取缓存时间]
	 * @return [int] [缓存时间]
	 */
	private function GetTime($time = 0)
	{
		return (intval($time) > 0) ? intval($time) : $this->c_time;
	}

	/**
	 * [Add 缓存添加]
	 * @param  [string]  	$key  [索引]
	 * @param  [mixed]  	$val  [值]
	 * @param  [integer] 	$time [过期时间(单位秒), 0永久, 或时间戳]
	 * @return [boolean] 	[成功true, 失败false]
	 */
	public function Add($key, $val, $time = 0)
	{
		return $this->c_obj->add($key, $val, $this->GetTime($time));
	}

	/**
	 * [Set 缓存替换]
	 * @param  [string]  	$key  [索引]
	 * @param  [mixed]  	$val  [值]
	 * @param  [integer] 	$time [过期时间(单位秒), 0永久, 或时间戳]
	 * @return [boolean] 	[成功true, 失败false]
	 */
	public function Set($key, $val, $time = 0)
	{
		return $this->c_obj->set($key, $val, $this->GetTime($time));
	}

	/**
	 * [SetMulti 设置多个索引的缓存数据]
	 * @param [type] $key_all [索引数组]
	 * @param  [integer] 	  $time [过期时间(单位秒), 0永久, 或时间戳]
	 * @return [boolean] 	  [成功true, 失败false]
	 */
	public function SetMulti($key_all, $time = 0)
	{
		return $this->c_obj->setMulti($key_all, $time);
	}

	/**
	 * [Append 向已存在索引后面追加数据]
	 * @param [string] $key [索引]
	 * @param [string] $val [追加的数据(字符串)]
	 */
	public function Append($key, $val)
	{
		$this->setOption();
		return $this->c_obj->append($key, $val);
	}

	/**
	 * [Prepend 向已存在索引前面追加数据]
	 * @param [string] $key [索引]
	 * @param [string] $val [追加的数据(字符串)]
	 */
	public function Prepend($key, $val)
	{
		$this->setOption();
		return $this->c_obj->prepend($key, $val);
	}

	/**
	 * [Replace 替换已存在索引下的元素]
	 * @param  [string]  	$key  [索引]
	 * @param  [mixed]  	$val  [值]
	 * @param  [integer] 	$time [过期时间(单位秒), 0永久, 或时间戳]
	 * @return [boolean] 	[成功true, 失败false]
	 */
	public function Replace($key, $val, $time = 0)
	{
		$this->c_obj->replace($key, $val, $time);
	}

	/**
	 * [setOption 设置选项]
	 */
	private function setOption()
	{
		$this->c_obj->setOption(Memcached::OPT_COMPRESSION, false);
	}

	/**
	 * [Fetch 抓取下一个结果]
	 * @param [string]  $key_all [索引名]
	 * @param [boolean] $cas     [是否返回长度, 是true, 否false默认]
	 */
	public function Fetch($key_all, $cas = false)
	{
		$this->GetDelayed($key_all, $cas);
		return $this->c_obj->fetch();
	}

	/**
	 * [FetchAll 抓取所有剩余的结果]
	 * @param [string]  $key_all [索引名]
	 * @param [boolean] $cas     [是否返回长度, 是true, 否false默认]
	 */
	public function FetchAll($key_all, $cas = false)
	{
		$this->GetDelayed($key_all, $cas);
		return $this->c_obj->fetchAll();
	}

	/**
	 * [GetDelayed 请求多个索引]
	 * @param [string]  $key_all [索引名]
	 * @param [boolean] $cas     [是否返回长度, 是true, 否false默认]
	 */
	private function GetDelayed($key_all, $cas)
	{
		$this->c_obj->getDelayed($key_all, $cas);
	}

	/**
	 * [Get 缓存获取]
	 * @param  [string]  $key  [索引]
	 * @return [mixed]   [当前索引对应的数据]
	 */
	public function Get($key)
	{
		return $this->c_obj->get($key);
	}

	/**
	 * [GetMulti 获取多个索引的缓存数据]
	 * @param [type] $key_all [索引数组]
	 */
	public function GetMulti($key_all)
	{
		return $this->c_obj->getMulti($key_all);
	}

	/**
	 * [Delete 删除一个索引]
	 * @param  [string]  $key [索引]
	 * @param  [integer] $time [等待时间(单位秒), 0立即, 或时间戳]
	 * @return [boolean] [成功true, 失败false]
	 */
	public function Delete($key, $time = 0)
	{
		return $this->c_obj->delete($key, $time);
	}

	/**
	 * [DeleteMulti 删除多个索引]
	 * @param  [array]            $key_all     [索引数组]
	 * @param  [integer] 	      $time [过期时间(单位秒), 0立即, 或时间戳]
	 * @return [boolean或array] 	  [成功true, 失败false]
	 */
	public function DeleteMulti($key_all, $time = 0)
	{
		$s = $this->c_obj->deleteMulti($key_all, $time);
		if(empty($s)) return false;
		foreach($s as $key=>$val)
		{
			if($val !== true) if($this->Get($key) == false) $s[$key] = true;
		}
		return $s;
	}

	/**
	 * [Flush 作废所有元素]
	 * @param  [integer] $time [等待时间(单位秒), 0立即]
	 * @return [boolean] [成功true, 失败false]
	 */
	public function Flush($time = 0)
	{
		return $this->c_obj->flush($time);
	}
}
?>

阅读全文

TOP