PHP代码片段

来自tomtalk
跳转至: 导航搜索

preg_replace()

 'domain' => preg_replace('/^[a-z]+./', '', $_SERVER['HTTP_HOST']),  //取二级域名

PHP汉字转拼音类

此类是根据ASCII码转换,GB2312库对多音字也无能为力。

GB2312标准共收录6763个汉字,不在范围内的汉字是无法转换,如:中国前总理朱镕基的“镕”字。

GB2312中对所收汉字进行了“分区”处理,每区含有94个汉字/符号。这种表示方式也称为区位码。

01-09区为特殊符号。

16-55区为一级汉字,按拼音排序。(3755个)

56-87区为二级汉字,按部首/笔画排序。(3008个)

10-15区及88-94区则未有编码。

占用的码位是72*94=6768。其中有5个空位是D7FA-D7FE。所以实际共6763个汉字。其中一级汉字3755个,二级汉字3008个。而此类算法实际只能转换3755个汉字。


优点:没有使用大文字库,文件相对较小,没有使用正则表达式,性能相对较高。支持首字母转换。

缺点:没有在GB2312中收录的汉字无法转换,多音字无法识别。(如果对拼音转换要求不高的朋友,建议使用这个。)

<?php
 
// 此类是根据ASCII码转换,GB2312库对多音字也无能为力。
// GB2312标准共收录6763个汉字,不在范围内的汉字是无法转换,如:中国前总理朱镕基的“镕”字。
class pinyin{
	public static function utf8_to($s, $isfirst = false) {
		return self::to(self::utf8_to_gb2312($s), $isfirst);
	}
 
	public static function utf8_to_gb2312($s) {
		return iconv('UTF-8', 'GB2312//IGNORE', $s);
	}
 
	// 字符串必须为GB2312编码
	public static function to($s, $isfirst = false) {
		$res = '';
		$len = strlen($s);
		$pinyin_arr = self::get_pinyin_array();
		for($i=0; $i<$len; $i++) {
			$ascii = ord($s{$i});
			if($ascii > 0x80) {
				$ascii2 = ord($s{++$i});
				$ascii = $ascii * 256 + $ascii2 - 65536;
			}
 
			if($ascii < 255 && $ascii > 0) {
				if(($ascii >= 48 && $ascii <= 57) || ($ascii >= 97 && $ascii <= 122)) {
					$res .= $s{$i}; // 0-9 a-z
				}elseif($ascii >= 65 && $ascii <= 90) {
					$res .= strtolower($s{$i}); // A-Z
				}else{
					$res .= '_';
				}
			}elseif($ascii < -20319 || $ascii > -10247) {
				$res .= '_';
			}else{
				foreach($pinyin_arr as $py=>$asc) {
					if($asc <= $ascii) {
						$res .= $isfirst ? $py{0} : $py;
						break;
					}
				}
			}
		}
		return $res;
	}
 
	public static function to_first($s) {
		$ascii = ord($s{0});
		if($ascii > 0xE0) {
			$s = self::utf8_to_gb2312($s{0}.$s{1}.$s{2});
		}elseif($ascii < 0x80) {
			if($ascii >= 65 && $ascii <= 90) {
				return strtolower($s{0});
			}elseif($ascii >= 97 && $ascii <= 122) {
				return $s{0};
			}else{
				return false;
			}
		}
 
		if(strlen($s) < 2) {
			return false;
		}
 
		$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
 
		if($asc>=-20319 && $asc<=-20284) return 'a';
		if($asc>=-20283 && $asc<=-19776) return 'b';
		if($asc>=-19775 && $asc<=-19219) return 'c';
		if($asc>=-19218 && $asc<=-18711) return 'd';
		if($asc>=-18710 && $asc<=-18527) return 'e';
		if($asc>=-18526 && $asc<=-18240) return 'f';
		if($asc>=-18239 && $asc<=-17923) return 'g';
		if($asc>=-17922 && $asc<=-17418) return 'h';
		if($asc>=-17417 && $asc<=-16475) return 'j';
		if($asc>=-16474 && $asc<=-16213) return 'k';
		if($asc>=-16212 && $asc<=-15641) return 'l';
		if($asc>=-15640 && $asc<=-15166) return 'm';
		if($asc>=-15165 && $asc<=-14923) return 'n';
		if($asc>=-14922 && $asc<=-14915) return 'o';
		if($asc>=-14914 && $asc<=-14631) return 'p';
		if($asc>=-14630 && $asc<=-14150) return 'q';
		if($asc>=-14149 && $asc<=-14091) return 'r';
		if($asc>=-14090 && $asc<=-13319) return 's';
		if($asc>=-13318 && $asc<=-12839) return 't';
		if($asc>=-12838 && $asc<=-12557) return 'w';
		if($asc>=-12556 && $asc<=-11848) return 'x';
		if($asc>=-11847 && $asc<=-11056) return 'y';
		if($asc>=-11055 && $asc<=-10247) return 'z';
		return false;
	}
 
	public static function get_pinyin_array() {
		static $py_arr;
		if(isset($py_arr)) return $py_arr;
 
		$k = 'a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo';
		$v = '-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274|-10270|-10262|-10260|-10256|-10254';
		$key = explode('|', $k);
		$val = explode('|', $v);
		$py_arr = array_combine($key, $val);
		arsort($py_arr);
 
		return $py_arr;
	}
}
 
/*
var_dump(0xE0);
for($i=0; $i<=255; $i++) {
	var_dump("$i :". chr($i));
}
*/
 
var_dump(pinyin::utf8_to('朱镕基'));
var_dump(pinyin::utf8_to('我是中国人'));
var_dump(pinyin::utf8_to('PHP汉字转拼音类'));
var_dump(pinyin::utf8_to('GB2312标准共收录6763个汉字,不在范围内的汉字是无法转换,如:中国前总理朱镕基的“镕”字。'));
var_dump(pinyin::utf8_to('`1234567890-=QWERTYUIOP[]ASDFGHJKL;ZXCVBNM,./abcdefghijklmnopqrstuvwxyz'));
 
var_dump(pinyin::utf8_to('朱镕基', 1));
var_dump(pinyin::utf8_to('我是中国人', 1));
var_dump(pinyin::utf8_to('PHP汉字转拼音类', 1));
var_dump(pinyin::utf8_to('GB2312标准共收录6763个汉字,不在范围内的汉字是无法转换,如:中国前总理朱镕基的“镕”字。', 1));
var_dump(pinyin::utf8_to('`1234567890-=QWERTYUIOP[]ASDFGHJKL;ZXCVBNM,./abcdefghijklmnopqrstuvwxyz', 1));
 
var_dump(pinyin::to_first('朱镕基'));
var_dump(pinyin::to_first('我是中国人'));
var_dump(pinyin::to_first('PHP汉字转拼音类'));
var_dump(pinyin::to_first('GB2312标准共收录6763个汉字,不在范围内的汉字是无法转换,如:中国前总理朱镕基的“镕”字。'));
var_dump(pinyin::to_first('▂▃▄▅▆▇█▉`1234567890-=QWERTYUIOP[]ASDFGHJKL;ZXCVBNM,./abcdefghijklmnopqrstuvwxyz'));

性能计时器

$start = microtime(true);
 
echo '<p>' . number_format(microtime(true) - $start, 3);

两个值,仅设置一个继续

$a = 'a';
$b = 'b';
 
var_dump(empty($a) xor empty($b));
 
 
$a = '';
$b = '';
 
var_dump(empty($a) xor empty($b));
 
$a = '';
$b = 'b';
 
var_dump(empty($a) xor empty($b));
 
$a = 'a';
$b = '';
 
var_dump(empty($a) xor empty($b));

删除文件

$file = 'dirlist.php'; 
unlink ($file);

取随机字符串

function rand_str($length)
{
    $str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randString = '';
    $len = strlen($str) - 1;
    for ($i = 0; $i < $length; $i++) {
        $num = mt_rand(0, $len);
        $randString .= $str[$num];
    }
 
    return $randString;
}

定义数组对象

$x = (object) array('a'=>'A', 'b'=>'B', 'C');

php中挺好用的strtotime方法

在PHP中,经常要对日期进行计算,比如要计算一个月前的日期,那么其实最快的方法是用strtotime,其功能很丰富,如下:

echo strtotime("now"), "\n";  
echo strtotime("10 September 2000"), "\n";  
echo strtotime("+1 day"), "\n";  
echo strtotime("+1 week"), "\n";  
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";  
echo strtotime("next Thursday"), "\n";  
echo strtotime("last Monday"), "\n";

看到没 +1 day +1 week,马上求出1天后,1个星期后的日期了, 求1个月前,可以:

echo date('Y-m-d', strtotime('1 month ago'))

因此,判断是否一个月前,可以

if  strtotime($my_date) < strtotime('1 month ago'))

反爬虫

getrobot();
 
function getrobot($useragent = '') {
    if (!defined('IS_ROBOT')) {
        $useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
        $kw_spiders ='bot|crawl|spider|slurp|sohu-search|lycos|robozilla|bingbot|youdaobot|baidu transcoder';
        $kw_browsers = 'msie|netscape|opera|konqueror|mozilla';
        if (preg_match("/($kw_spiders)/i", $useragent)) {
            define('IS_ROBOT', true);
            define('Bot_Mobile',(strexists($useragent,'googlebot-mobile'))||(strexists($useragent,'baidu')&&!strexists($useragent,'baiduspider')) ? true : false);
        } elseif (!strexists($useragent, 'http://') && preg_match("/($kw_browsers)/i",$useragent)) {
            define('IS_ROBOT', false);
        }else {
            define('IS_ROBOT', false);
        }
    };
 
    return IS_ROBOT;
}

setcookie()

setcookie('bindUser', 2, time() + 3600);        //存一小
setcookie('bindUser', 2, time() - 3600);        //设置过期,删除
setcookie('bindUser', 2, time() + 3600, '/p');  //设置cookie保存路径

file_get_contents https

file_get_contents('https://www.xx.com');
file_put_contents("rote.txt", "cc ", FILE_APPEND);

需要修改php.ini

extension=php_openssl.dll 把这个打开。

PHP 中获取文件名及路径=

1. basename("/mnt/img/image01.jpg")函数:得到文件名;输出结果为:image01.jpg.

  使用 basename($uriString) 我们可以得到一个包含扩展名的文件名;

  如果不需要扩展名,也可以使用 basename($uriString, $extString) 过滤扩展名,仅仅返回文件名。 2. echo __FILE__;得到当前请求文件的完整路径,输出格式如:/mnt/hgfs/ictsapce/test/index.php 3.dirname() 函数返回路径中的目录部分。如:

 echo dirname("/testweb/home.php");
 输出:/testweb 


PHP中获取文件扩展名的N种方法

从网上收罗的,基本上就以下这几种方式:


第1种方法: function get_extension($file) { substr(strrchr($file, '.'), 1); } 第2种方法: function get_extension($file) { return substr($file, strrpos($file, '.')+1); } 第3种方法: function get_extension($file) { return end(explode('.', $file)); } 第4种方法: function get_extension($file) { $info = pathinfo($file); return $info['extension']; } 第5种方法: function get_extension($file) { return pathinfo($file, PATHINFO_EXTENSION); } 以上几种方式粗看了一下,好像都行,特别是1、2种方法,在我不知道pathinfo有第二个参数之前也一直在用。但是仔细考虑一下,前四种方法都有各种各样的毛病。要想完全正确获取文件的扩展名,必须要能处理以下三种特殊情况。 没有文件扩展名 路径中包含了字符.,如/home/test.d/test.txt 路径中包含了字符.,但文件没有扩展名。如/home/test.d/test 很明显:1、2不能处理第三种情况,3不能正确处理第一三种情况。4可以正确处理,但是在不存在扩展名时,会发出一个警告。只有第5种方法才是最正确的方法。顺便看一下pathinfo方法。官网上介绍如下: $file_path = pathinfo('/www/htdocs/your_image.jpg');

echo "$file_path ['dirname']\n"; echo "$file_path ['basename']\n"; echo "$file_path ['extension']\n"; echo "$file_path ['filename']\n"; // only in PHP 5.2+ 它会返回一个数组,包含最多四个元素,但是并不会一直有四个,比如在没有扩展名的情况下,就不会有extension元素存在,所以第4种方法才会发现警告。但是phpinfo还支持第二个参数。可以传递一个常量,指定返回某一部分的数据: PATHINFO_DIRNAME - 目录 PATHINFO_BASENAME - 文件名(含扩展名) PATHINFO_EXTENSION - 扩展名 PATHINFO_FILENAME - 文件名(不含扩展名,PHP>5.2) 这四个常量的值分别是1、2、4、8,刚开始我还以为可以通过或运算指定多个: pathinfo($file, PATHINFO_EXTENSION | PATHINFO_FILENAME); 后来发现这样不行,这只会返回几个进行或运算常量中最小的那个。也就是四个标志位中最小位为1的常量。

file()

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

把整个文件读入一个数组中。

目录操作opendir()

<?php 
$dir=opendir('img');
 
while ($fileName=readdir($dir)) { 
    if ($fileName!='.' && $fileName!='..') {
        if (is_dir($file)) {
            echo "[$fileName]";
        }else{
            echo $fileName;
        }
    } 
}
 
closedir($dir);
?>

php取整的几种方式

floor()

返回不大于value 的下一个整数,将value 的小数部分舍去取整。floor() 返回的类型仍然是float,因为float 值的范围通常比integer 要大。

echo floor(4.3);   // 4 
echo floor(9.999); // 9
ceil()

返回不小于value 的下一个整数,value 如果有小数部分则进一位。ceil() 返回的类型仍然是float,因为float 值的范围通常比integer 要大

echo ceil(4.3);    // 5 
echo ceil(9.999);  // 10
round()

对浮点数进行四舍五入

echo round(3.4);         // 3 
echo round(3.5);         // 4 
echo round(3.6);         // 4 
echo round(3.6, 0);      // 4 
echo round(1.95583, 2);  // 1.96 
echo round(1241757, -3); // 1242000 
echo round(5.045, 2);    // 5.05 
echo round(5.055, 2);    // 5.06

php的又一深坑

请大家看如下代码,并猜想结果会是什么样的?

<?php
$arrData = array (
    'va_info' => array (array ('position' => 290, 'item' => 70009 ),
    array ('position' => 290, 'item' => 70009 ),
    array ('position' => 290, 'item' => 70009 ),
    array ('position' => 290, 'item' => 70009 ),
    array ('position' => 290, 'item' => 70009 ) ) );
 
foreach ( $arrData['va_info'] as &$data ) {
    update($arrData);
    unset($data);
}
 
function update($arrData) {
 
    foreach ( $arrData as $col => $value ) {
        $arrData [$col] = array ('=', $value );
    }
    return $arrData;
}
?>

结果是foreach的时候arrData变成了reference,于是死循环了

PHP实现BigPipe分chunked输出

在Yahoo系的最佳实践里,建议把静态的内容尽早的输出,在 head之后就调用flush,让浏览器可以尽早去加载静态资源,包括脚本、样式、图片(javascipt,css,image一般是外链的形式)等等,后台如果有多个数据源或者api需要调用,尽可能做到完成一个输出一个,通过js在前端拼装页面,进而达到优化用户体验的效果,用户等待的时间,是木桶最短的那快木板。

下面是引用:

Flush the Buffer Early

tag: server

When users request a page, it can take anywhere from 200 to 500ms for the backend server to stitch together the HTML page. During this time, the browser is idle as it waits for the data to arrive. In PHP you have the function flush(). It allows you to send your partially ready HTML response to the browser so that the browser can start fetching components while your backend is busy with the rest of the HTML page. The benefit is mainly seen on busy backends or light frontends. A good place to consider flushing is right after the HEAD because the HTML for the head is usually easier to produce and it allows you to include any CSS and JavaScript files for the browser to start fetching in parallel while the backend is still processing.

Example:

... <!-- css, js -->
</head>
<?php flush(); ?>
<body>
... <!-- content -->

Facebook提出的BigPipe技术,将这种思想有了更具体的实现,大体思路是,分解网页成叫做Pagelets的小块,然后通过Web服务器和浏览器建立管道并管理他们在不同阶段的运行。

在php下做个小测试,

<?php
    echo 'xxxxxxxxxxxxxxxxxxxxxxx<br>';
    ob_flush();
    flush();
    sleep(2);
    echo "b";
?>

结果可以看到在ie下(7,8),不管输出内容的大小,都可以看到效果,“b“在2秒后输出,在firefox和chrome,两段文本都在2秒后展现,说明浏览器做了缓存,经过实验,缓存的大小为1024,刚好1k,也是浏览器做的优化。通过返回头可以看出,在分段输出的时候,返回包没有经过gzip。

通过wireshark可以看到后台输出确实是一个个chunked过来的,看来是浏览器做了工作,猜测:缓存大小应该是1024B或者MTU大小(1400B多点,看网络情况),首段输出增大到1024的时,chrome和firefox都开始正常表演了,页面里的js、css和图片在第一段下载完已经开始加载。

应该思考的问题
  1. 传输效率,尽量利用一次传输传送尽量多的东西,根据MTU大小调整;
  2. 同步加载,第一块送过来的东西,尽量可以同步加载,需要注意不同浏览器可以同步加载域名的数量,需要考虑javascript对加载的block,对于不用立刻执行的内容,可以通过加defer或者干脆注释掉,等页面完成在eval进来;
  3. 适用范围,任何一个技术都有自己适用的场景,对于后台需要访问多个api的应用会更适合一些,像社交类的网站,搜索之类的本来就在100ms左右就展现完毕,纯玩儿技术就没意义了,chunked也不是分的越多越好,适当的,类似的最好合并起来;
  4. ob_flush和flush最好结对使用,某些情况下,当用flush是没有效果的。

计算页面执行时间

<?php
class runtime
{ 
    var $StartTime = 0; 
    var $StopTime = 0; 
 
    function get_microtime() 
    { 
        list($usec, $sec) = explode(' ', microtime()); 
        return ((float)$usec + (float)$sec); 
    } 
 
    function start() 
    { 
        $this->StartTime = $this->get_microtime(); 
    } 
 
    function stop() 
    { 
        $this->StopTime = $this->get_microtime(); 
    } 
 
    function spent() 
    { 
        return round(($this->StopTime - $this->StartTime) * 1000, 1); 
    } 
 
}
 
 
//例子 
$runtime= new runtime;
$runtime->start();
 
//你的代码开始
 
$a = 0;
for($i=0; $i&lt;1000000; $i++)
{
    $a += $i;
}
 
//你的代码结束
 
$runtime->stop();
echo "页面执行时间: ".$runtime->spent()." 毫秒";
 
?>

递归创建多级目录

<?php
/**
 * 递归创建多级目录
 * @param unknown_type $dir
 * @return boolean
 */
function create_folders($dir){ 
    return is_dir($dir) or (create_folders(dirname($dir)) and mkdir($dir, 0777)); 
}
 
$dir = 'D:\wamp\www\iworker\system/../i/attachments/1/81/';
create_folders($dir);
 
//end file

redidai工作代码片断

U('location-Location/detail', array('id' => $k));  //景点
U('plan-Index/detail', array('id' => $k));         //计划
U('notes-MemberNotes/detail', array('id' => $k, 'uid' => $notesList[$k]['mid']));  //游记
 
ui.box.alert('内容', {title:'标题'}); //提示框
ui.box.show('内容', {title:'标题'}); //信息框
ui.box.load('url', {title:'标题'}); //ajax调用
 
<a onclick="weibo.favorite(85452,this)" href="javascript:void(0)">收藏</a>
http://t.thinksns.com/index.php?app=weibo&mod=Operate&act=stow  //微博收藏
 
ui.box.show(txt, {title:'举报',closeable:true});                                   //ui.box.show()
ui.box.load( U('weibo/FollowGroup/selectorBox')+'&fid='+fid,{title:'设置分组'});   //ui.box.load()
 
plan.dialog=function(data,tplId,selectOpt){
    var html = Mustache.render($("#"+tplId).html(), data),
        $container = $("#formPopupLayer").children("div.addToPlanBox");
    $container.html(html);
    if(selectOpt){
        for(var i in selectOpt){
            $container.find("select[name='" + i + "']").val(selectOpt[i]);
        }    
    }    
    $("#formPopupLayer").show();
}
 
plan.prompt=function(message,tplId){
    if(tplId==undefined){
        tplId = "tpl_prompt_container";
    }    
    var html = Mustache.render($("#"+tplId).html(), {message:message});
    $("#formPopupLayer").children("div.addToPlanBox").html(html).end().show();
}
 
plan.confrim=function(message,followOptFun,tplId){
    if(tplId==undefined){
        tplId = "tpl_confrim_container";
    }    
    var html = Mustache.render($("#"+tplId).html(), {message:message,followOptFun:followOptFun});
    $("#formPopupLayer").children("div.addToPlanBox").html(html).end().show();
}


{:W('SelectFriends',array('uid'=>$touid))}          //私信好友选择器
 
addons/widgets/SelectFriends.html                   //模板文件
 
public/themes/newstyle/apps/home/Message/post.html  //发私信模板文件
 
/public/themes/newstyle/form.css   //全局表单样式
 
 
<include file="__THEME__/header" />      //包含会员中心头部的模板写法
<include file="__THEME__/footer" />      //包含会员页脚的模板写法
<include file="__THEME__/apps" />        //包含会员左边栏菜单的模板写法
 
UserAction.class.php::__getWeiboList()   //会员中心微博列表
addons/widgets/weiboList.html            //会员中心微博列表模板
 
apps/home/Lib/Action/SelectFriendsAction.class.php::getType()          //会员分组
 
SELECT member.nickname, CONCAT('/Data/Uploads/', savepath, savename) AS avatar
FROM think_member AS member 
LEFT JOIN think_attach AS attach ON (member.attach_id = attach.id) 
WHERE member.id=1557
 
$_SERVER['DOCUMENT_ROOT'].'/'
 
$myInfo = D('User', 'home')->getMemberByid($this->mid);
 
U('ask-Ask/detail', array('id' => $v['id']));
 
'home/User/index' => 'user_home',       //会员中心路由
public/themes/newstyle/apps/home/User/index.html  //会员中心页模板
public/theme/newstyle/header.html                 //会员页顶部导航条模板
 
$theme = D('RddNotes', 'notes')->getTheme();
 
$model = D('RddVideo', 'video');
 
分员分组数据表:
*ts_weibo_follow_group
*ts_weibo_follow_group_link
 
public/js  改为 public/Js
 
$this->mid 弃用,改为 $this->uid
 
$relation_data = A('RddRelactionData', 'public')->get($id, 'video');
 
$planModel = D('RddPlan', 'plan');
 
apps/home/Lib/Model/AvatarModel.class.php     //头像上传
 
core/sociax/extend.php::getUserFace()     //显示用户头像
 
apps/weibo/Lib/Model/FollowModel.class.php::doSearchuser()  //找人,搜索
 
core/ThinkPHP/Common/debug.php     //修改Trace信息显示内容
 
apps/weibo/Lib/Model/FollowModel.class.php::getList()      //显示会员关注的好友列表
 
apps/home/Lib/Action/SpaceAction.class.php::getInterstList()         //显示会员列表中的会员兴趣