标签归档:PHP

mac os中多版本php切换

方法一

1. 添加tab

brew tap josegonzalez/php

2. 安装多版本的PHP

brew install php53
brew install php54

3. 制作切换的脚本

mkdir -p ~/.bin/php-switch
cd ~/.bin/php-switch
curl -L http://d.pr/8yN8 > php-switch
chmod +x php-switch

需要把php-switch添加到PATH中,可以在.bash_profile中添加,这样开机就能够自动加载

4. 最后就可以通过如下命令切换php版本

php-switch

方法二

直接通过homebrew可以安装切换工具

brew tap homebrew/dupes
brew tap josegonzalez/homebrew-php
brew install php-version
# Homebrew (recommended)
source $(brew --prefix php-version)/php-version.sh && php-version 5

以上安装完成后也可以通过php-version来切换

方法三

安装切换工具

npm install -g brew-php-select
LoadModule php5_module /usr/local/php/libexec/apache2/libphp5.so

可以通过如下命令切换

brew-php-select

使用PHPSTORM和XDEBUG优化PHP程序

Xdebug将程序的中每个函数和方法的运行时间和内存情况,都记录到profiler中,但是需要专门的工具去分析,PhpStorm就提供了这种工具,下面给介绍下使用Phpstorm和Xdebug分析和优化程序。

MAC OS中安装xdebug方法:

brew install php53-xdebug

首先去php.ini配置Xdebug让其记录日志,配置如下

MAC OS的配置文件在/usr/local/etc/php/5.3/conf.d目录中

[xdebug]
zend_extension="/usr/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_autostart=1
xdebug.remote_port=9000
;下面就是配置Xdebug分析器的,大家可根据自己的要求,去定制dir和output_name
xdebug.profiler_enable=on
xdebug.trace_output_dir="/tmp"
xdebug.profiler_output_dir="/tmp"
xdebug.profiler_output_name="xdebug"

然后重启apache,然后运行php程序就会在tmp目录下看到xdebug开头的文件。

下一步,用PhpStorm自带工具区分析,选在tools下Analyze Xdebug Profiler Snapshot工具

可以点击Time选项,看看哪个函数消耗的时间长。

PHP截取英文保证单词完整性

/**
     * 完整词的截取
     *
     * @param $str
     * @param $start
     * @param $length
     *
     * @return string
     */
    public static function usubstr($str, $start, $length = null)
    {

        // 先正常截取一遍.
        $res = substr($str, $start, $length);
        $strlen = strlen($str);

        /* 接着判断头尾各6字节是否完整(不残缺) */
        // 如果参数start是正数
        if ($start >= 0) {
            // 往前再截取大约6字节
            $next_start = $start + $length; // 初始位置
            $next_len = $next_start + 6 <= $strlen ? 6 : $strlen - $next_start;
            $next_segm = substr($str, $next_start, $next_len);
            // 如果第1字节就不是 完整字符的首字节, 再往后截取大约6字节
            $prev_start = $start - 6 > 0 ? $start - 6 : 0;
            $prev_segm = substr($str, $prev_start, $start - $prev_start);
        } // start是负数
        else {
            // 往前再截取大约6字节
            $next_start = $strlen + $start + $length; // 初始位置
            $next_len = $next_start + 6 <= $strlen ? 6 : $strlen - $next_start;
            $next_segm = substr($str, $next_start, $next_len);

            // 如果第1字节就不是 完整字符的首字节, 再往后截取大约6字节.
            $start = $strlen + $start;
            $prev_start = $start - 6 > 0 ? $start - 6 : 0;
            $prev_segm = substr($str, $prev_start, $start - $prev_start);
        }
        // 判断前6字节是否符合utf8规则
        if (preg_match('@^([x80-xBF]{0,5})[xC0-xFD]?@', $next_segm, $bytes)) {
            if (!empty($bytes[1])) {
                $bytes = $bytes[1];
                $res .= $bytes;
            }
        }
        // 判断后6字节是否符合utf8规则
        $ord0 = ord($res[0]);
        if (128 <= $ord0 && 191 >= $ord0) {
            // 往后截取 , 并加在res的前面.
            if (preg_match('@[xC0-xFD][x80-xBF]{0,5}$@', $prev_segm, $bytes)) {
                if (!empty($bytes[0])) {
                    $bytes = $bytes[0];
                    $res = $bytes . $res;
                }
            }
        }
        if (strlen($res) < $strlen) {
            $res = $res . '...';
        }
        return $res;
    }

MEMCACHE_COMPRESSED常量报错问题处理

首先介绍下MEMCACHE_COMPRESSED:

常用的Memcache::set方法:

bool Memcache::set  ( string $key  , mixed $var  [, int $flag  [, int $expire  ]] )

在这个方法中,将$flag设置为MEMCACHE_COMPRESSED即可启用memcache压缩存储。

今天在调试系统的过程中报“ Use of undefined constant MEMCACHE_COMPRESSED”的错误,于是下意识的去查看phpinfo的信息是支持memcached的,找了半天没发现有人遇到过;

想了半天突然想到php-memcached和php-memcache是有区别的,我是安装的php-memcached,于是安装了php-memcache,果断没了报错。

手动编辑安装PHP扩展

开发和部署的过程中可能会经常出现需要额外安装PHP扩展的情况,下边以PDO_MYSQL为例,介绍下手动编译安装PHP扩展:

先到http://pecl.php.net/找需要的版本,我用的是稳定的版本。要先看看说明,特别是要注意mysql的php的版本。

wget http://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz
tar xzvf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2
/usr/local/php/bin/phpize
Configuring for:
PHP Api Version: 20041225
Zend Module Api No: 20060613
Zend Extension Api No: 220060519
./configure --with-php-config=/usr/local/php/bin/php-config

经过configure就可以make了

make
make install

注意pdo_mysql的全路径,我的是:

/usr/local/php/lib/php/extensions/debug-non-zts-20060613/pdo_mysql.so

然后在/usr/local/lib/php.ini

加上一句:

extension=/usr/local/php/lib/php/extensions/debug-non-zts-20060613/pdo_mysql.so

重新启动apache即可看到已经加载pdo_mysql成功。

PHP判断是否为手机移动设备实例

//判断是否属手机
function is_mobile() {
	$user_agent = $_SERVER['HTTP_USER_AGENT'];
	$mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
	$is_mobile = false;
	foreach ($mobile_agents as $device) {
		if (stristr($user_agent, $device)) {
			$is_mobile = true;
			break;
		}
	}
	return $is_mobile;
}
//使用很简单
if( is_mobile() ){
//Your Code
}

 

转自:http://levi.cg.am/?p=2214

mac os x编辑安装vld及错误处理

1. 下载

http://pecl.php.net/package/vld

2. 解压后进入源码目录

3. sudo /Applications/XAMPP/xamppfiles/bin/phpize

4. sudo MACOSX_DEPLOYMENT_TARGET=10.8 CFLAGS="-arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch i386 -arch x86_64 -g -Os -pipe" CXXFLAGS="-arch i386 -arch x86_64 -g -Os -pipe" LDFLAGS="-arch i386 -arch x86_64 -bind_at_load" ./configure --with-php-config=/Applications/XAMPP/xamppfiles/bin/php-config

5. sudo make

6. sudo make install

注意:

在第四步中如果不添加一些编译参数,则会出现下面的错误:

PHP Warning: PHP Startup: Unable to load dynamic library '/Applications/XAMPP/xamppfiles/lib/php/php-5.3.1/ extensions/no-debug-non-zts-20090626/vld.so' - dlopen(/Applications/XAMPP/xamppfiles/lib/php/php-5.3.1/extensions/ no-debug-non-zts-20090626/vld.so, 9): no suitable image found. Did find:\n\t/Applications/XAMPP/xamppfiles/lib/ php/php-5.3.1/extensions/no-debug-non-zts-20090626/vld.so: mach-o, but wrong architecture in Unknown on line 0
2109 [Wed Jan 23 11:32:53 2013] [notice] Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2. 0.4 Perl/v5.10.1 configured -- resuming normal operations

Kohana 3.1 cache config bug解决办法

今天用到了kohana 3.1自带的cache并且使用memcache引擎,但是一直发现写不进缓存,开始以为自己的缓存配置有问题查了半天,没有找到解决办法,后来把缓存服务器换成本地实际可用的服务器,还是不能写入,这样就开始怀疑是程序的问题,自己手动写了一个缓存写入的代码

$mem = new Memcache;
$mem->connect("127.0.0.1", 10000);
//Memcache::set方法有四个参数,第一个参数是key,第二个参数是value,第三个参数可选,表示是否压缩保存,第四个参数可选,用来设置一个过期自动销毁的时间。
$mem->set('test1', '123', 0, 60);
//Memcache::add方法的作用和Memcache::set方法类似,区别是如果 Memcache::add方法的返回值为false,表示这个key已经存在,而Memcache::set方法则会直接覆写。
$mem->add('test2', '123', 0, 60);
//Memcache::get方法的作用是获取一个key值,Memcache::get方法有一个参数,表示key。
$mem->get('test'); //输出为'123'
//Memcache::replace 方法的作用是对一个已有的key进行覆写操作,Memcache::replace方法有四个参数,作用和Memcache::set方法的相同。
$mem->replace('test', '456', 0, 60);

发现是可用,就开始查kohana自带的驱动文件,一步一步跟踪后发现,是配置文件的问题,系统没有把app里的config合并到system,google了下,发现也有朋友遇到过这样的问题,把cache.php文件用如下写法即可:

<?php defined('SYSPATH') or die('No direct script access.');
return array
(
    'memcache' => array
    (
        'driver' => 'memcache',
        'default_expire' => 3600,
        'compression' => FALSE, // Use Zlib compression (can cause issues with integers)
        'servers' => array
        (
            'local' => array (
                'host' => 'localhost', // Memcache Server
                'port' => 11211, // Memcache port number
                'persistent' => FALSE, // Persistent connection
                'weight' => 1,
                'timeout' => 1,
                'retry_interval' => 15,
                'status' => TRUE,
            ),
        ),
        'instant_death' => TRUE, // Take server offline immediately on first fail (no retry)
    ),
    'memcachetag' => array
    (
        'driver' => 'memcachetag',
        'default_expire' => 3600,
        'compression' => FALSE, // Use Zlib compression (can cause issues with integers)
        'servers' => array (
            'local' => array(
                'host' => 'localhost', // Memcache Server
                'port' => 11211, // Memcache port number
                'persistent' => FALSE, // Persistent connection
                'weight' => 1,
                'timeout' => 1,
                'retry_interval' => 15,
                'status' => TRUE,
            ),
        ),
        'instant_death' => TRUE,
    ),
    'apc' => array
    (
        'driver' => 'apc',
        'default_expire' => 3600,
    ),
    'wincache' => array
    (
        'driver' => 'wincache',
        'default_expire' => 3600,
    ),
    'sqlite' => array
    (
        'driver' => 'sqlite',
        'default_expire' => 3600,
        'database' => APPPATH . 'cache/kohana-cache.sql3',
        'schema' => 'CREATE TABLE caches(id VARCHAR(127) PRIMARY KEY, tags VARCHAR(255), expiration INTEGER, cache TEXT)',
    ),
    'eaccelerator' => array
    (
        'driver' => 'eaccelerator',
    ),
    'xcache' => array
    (
        'driver' => 'xcache',
        'default_expire' => 3600,
    ),
    'file' => array
    (
        'driver' => 'file',
        'cache_dir' => APPPATH . 'cache',
        'default_expire' => 3600,
    )
);