PHP 碎片
1. $_SERVER['REMOTE_ADDR']
cannot be modified by the user or via HTTP so you CAN trust it. -- 用这个可以有效防止别人跨站提交。
2. 自己写的验证时间格式是否正式的函数:
function checktime($time){ $time = trim($time); if( empty($time) ){ return false; } $regStr = "/^20\d{2}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}$/i"; if( !preg_match($regStr,$time) ){ return false; } $arr = explode(' ',$time); $dateStr = $arr[0]; $timeStr = $arr[1]; $dateArr = explode('-',$dateStr); if( !checkdate($dateArr[1],$dateArr[2],$dateArr[0]) ){ return false; } $timeArr = explode(':',$timeStr); $hour = intval($timeArr[0]); $minute = intval($timeArr[1]); $second = intval($timeArr[2]); if( $hour>24 || $minute>60 || $second>60 ){ return false; } return true; }
3.非常好用的调试方法:debug_print_backtrace,可以打印出一个页面的调用过程 , 从哪儿来到哪儿去一目了然。但这个方法是直接输出到页面的,虽然输出页面的东西可以用缓存得到,但也不方便。debug_backtrace,把结果保存到数组,方便很多。使用 debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); 简化输出。
4.
$_POST = array( 'test' => 1 ); $_REQUEST = $_POST; $_REQUEST['test'] = 2; print_r($_REQUEST); print_r($_POST); /* 分别输出 array( 'test' => 2 ); array( 'test' => 1 ); */
$_POST = array( 'test' => 1 ); $_REQUEST = &$_POST; $_REQUEST['test'] = 2; print_r($_REQUEST); print_r($_POST); /* 分别输出 array( 'test' => 2 ); array( 'test' => 2 ); */
5. 当循环(for)里面有 switch 而我又想用 continue 跳到下一个循环,谁知却是跳出 switch 。
while(){ switch(){ case 1: xxxx; continue; //没有跳出循环,而是跳出了switch } }
6.curl 的函数
function curl_get($url, $data=array()){ $ch = curl_init(); $query = http_build_query($data); if(''!=$query) $url .= '?' . $query; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $result = curl_exec($ch); curl_close($ch); return $result; } function curl_post($url, $post_data=array()){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); $result = curl_exec($ch); curl_close($ch); return $result; }