php随笔小技巧
//更改自動加載時調用的函數
spl_autoload_register(array('Core_Fun','_class_autoload'));//腳本執行完畢時調用
register_shutdown_function()//獲取指定下標的參數
func_get_arg($offset)//把獲取的全部參數放到一個數組里
func_get_args()
file_put_contents設置超時時間
?
$opt = array('http'=>array('method'=>"GET",'header'=>"Content-Type: text/html; charset=utf-8",'timeout'=>2) ); $context = stream_context_create($opt); file_get_contents("http://www.baidu.com", false, $context);curl中的超時設置:curl_setopt($ch, CURLOPT_TIMEOUT, 3)
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.baidu.com"); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec($ch); curl_close($ch);?fscoketopen 超時
function request($host, $uri, $timeout = 3, $port = 80) {$fp = fsockopen ( $host, 80, $errno, $errstr, $timeout );if (! $fp) {echo "$errstr ($errno)<br />\n";exit;} else {$data = '';stream_set_timeout ( $fp, $timeout ); //#$out = "GET {$uri} HTTP/1.1\r\n";$out .= "Host: {$host}\r\n";$out .= "Connection: Close\r\n\r\n";fwrite ( $fp, $out );while ( ! feof ( $fp ) ) {$data .= fgets ( $fp, 128 );}fclose ( $fp );return $data;}}echo request('www.cnblogs.com', '/siqi');?
?
?
抽象類的妙用:可以用來做單例模式用
?
class man{public $a = 1;public function __construct(){echo 'new';}public function say(){echo 'saying';} }//抽象類不可以直接被實例化(巧妙的運用) abstract class people{public $a = 123;public static function get_obj(){//這個的變量改成成員變量也是可以的static $obj = null;if(is_null($obj)){$obj = new man();}return $obj;} }// 只輸出的一個new說明只實例化了一次 $p1 = people::get_obj(); $p2 = people::get_obj();?
用數組中的每個值一次去替換字符串中的自定字符
//$sql = "?,?,?,?" //$data = array('a', 'b', 'c', 'd'); //一次替換一個問號 for($i=0;$i<$count;$i++){ $sql=preg_replace('/\?/',"'".mysql_escape_string($data[$i])."'",$sql,1);// 一次只替換一個 }?
?
/*** 當發生致命性錯誤或者exit時都會調用此函數* */ error_reporting(0); register_shutdown_function ( 'handleShutdown' );function handleShutdown (){$error = error_get_last ();// 根據錯誤信息,判斷是否是超時了if ( $error && strpos ( $error [ 'message' ], 'Maximum exec' )!== false ) {echo 'handle time out';} }set_time_limit(2);sleep(3);?
?
/*** 獲取最后一次出錯信息,無論如何也能獲取到* * error_get_last set_error_handler 都不會受環境配置的影響* */ error_reporting(0); ini_set("display_errors", "off");set_error_handler(function(){print_r(func_get_args());});echo $a ; print_r(error_get_last());?
//$php_errormsg 獲取php前一個錯誤信息 ,必須在 php.ini 中 track_errors = On ini_set('track_errors', true); echo $a; echo $php_errormsg; //Undefined variable: a?
//調試// 輸出所有的函數 get_defined_functions();//獲取所定義的常量 get_defined_constants();//獲取所定義的變量 get_defined_vars();?
?
#對于請求外部地址curl比file_get_contents效率更高 #禁用后者php.ini中修改 allow_url_fopen = Off #重啟php-fpm?
?
#正則中對\的理解$str = '<a href=\"db.house.qq\"></a>';#雙引號中可以轉義的符合會被執行,輸出后不在顯示轉義符 echo "/\\\\\"db.house.qq\\\\\"/" . "\n"; // /\\"db.house.qq\\"/ 總結:在雙引號的正則中一個\需要寫成 \\#正則本身的轉義符號也需要轉義 var_dump(preg_match("/\\\\\"db.house.qq\\\\\"/", $str, $m));#單引號寫法,單引號中的內容不會執行 var_dump(preg_match('/\\\"db.house.qq\\\"/', $str, $m));print_r($m);?
?
// ?: 匹配但不捕獲 加在前面 //? 去貪婪 加在后面 // \1 反向引用 // $1 捕獲 $str = 'a a'; preg_match("/(a)(?:\s+)\\1/", $str, $m); #1 echo preg_replace("/(a)(\s+)\\1/", "$1", $str); #a print_r($m);?
#php通過mysql取出的數據庫的數據都是字符串類型?
#關閉gpc magic_quotes_gpc=Off get_magic_quotes_gpc()?
#請不要在程序里面嵌套任何PHP標簽(以免多次調用PHP解析器)?
#strtolower會在沒有安裝中文語言的系統中把中文轉成亂碼,用下面的這個函數 strtr($string, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');?
#如果print/echo輸出HTML會被Apache加上緩存頭,如果不希望被緩存,則需要加上上面的輸出無緩存頭代碼來避免 @header('Cache-Control: no-cache, must-revalidate, max-age=0'); @header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); @header('Pragma: no-cache');?
file_get_contents() 讀取文件要比 fopen/fread 快30倍,但請求外部地址很慢,請用curl替代?
null ++ 為1, -- 仍為null 字符串只可以++,相當于最后一個字節加1, --則沒效果?
?
/*** sql轉義,并把輸入轉換成可插入的sql* @author root**/ class escape{/*** 內部函數,做insert操作時候的字符串過濾** @param unknown_type $data* @return int or errorno*/public function compile_insert_string($data){$field_names = '';$field_values = '';foreach ($data as $k => $v){$field_names .= "$k,";if ( is_numeric( $v ) and intval($v) == $v ){$field_values .= intval($v).",";}elseif ($v === null){//兼容字段值為null的$field_values .= "null,";}else {$field_values .= "'".$this->format_string($v)."',";}}//去掉最后一個,$field_names = preg_replace( "/,$/" , "" , $field_names );$field_values = preg_replace( "/,$/" , "" , $field_values );return array( 'FIELD_NAMES' => $field_names,'FIELD_VALUES' => $field_values,);}/*** 格式化參數,php連接mysql的時候,可能導致SQL注入攻擊,使用這個來做過濾** @param string $str* @return string*/public function format_string($str){if (get_magic_quotes_gpc()){$str = stripslashes($str);}if (!is_numeric($str)){//$str = mysqli_real_escape_string($this->connection, $str); }return $str;} }$insert_arr = array("id"=>1, "name"=>"sjk");$e = new escape(); $formated_array = $e->compile_insert_string($arr); $table = "card"; $insert_sql = 'INSERT INTO '.$table.' ('.$formated_array['FIELD_NAMES'].') VALUES('.$formated_array['FIELD_VALUES'].')';?
#注意需要帶上引號 (include 'mth.php') == "a";?
#外部參數的驗證原則:對外部參數進程合法性驗證,對于不符合的應該拒絕而不是使其合法?
spl_autoload_*類函數運用//獲取加載文件的擴展名 spl_autoload_extensions()//獲取所有注冊的函數列表 spl_autoload_functions//反注冊一個自動加載函數 spl_autoload_unregister();//注冊一個函數,注意此操作會覆蓋原來的 __autoload 函數 spl_autoload_register(func_name); //某個類的某個方法 spl_autoload_register(array('AutoloadClass', 'autoload')); //autoload 為靜態方法 spl_autoload_register(array($this, 'autoload')); //$this 代表一個對象?
//spl_autoload_register 可重復調用,如果找到則停止搜索 function a ($c) {echo "a\n";class Bla {} // Usually "include 'path/to/file.php';" } function b ($c) {echo "b\n";class Bla {} // Usually "include 'path/to/file.php';" } spl_autoload_register('a'); spl_autoload_register('b');$c = new Bla();?
//php 1~100 單個輸出 記得php.ini中設置 output_buffering = Off echo str_repeat(' ',1024); for($i=1;$i<100;$i++) {echo $i;sleep(1); // ob_flush();flush();}?
set_time_limit() 僅計算腳本自己執行的時間,調用system(),io操作,數據庫查詢、連接、sleep()、外部的請求(curl)等都不算在之內,并且windows下并不是這樣的
//通用的測試腳本 set_time_limit(1); $time = time(); while(time()-$time <5) {echo 'timeout'; }?
限制程序使用內存的大小
ini_set("memory_limit", "128M"); ini_set("memory_limit", "100K");?
根據輸出的內容設置相應的頭信息,可以減少攻擊
header('Content-Type:text/plain'); header('Content-Type:application/json');
?php中模擬不可中斷睡眠
class SleepWorkaroundForSIGALRM {private $time;function __construct($seconds) {$this->time = microtime(1) + $seconds;while ($this->time >= microtime(1)) {usleep(10);}} }??
數組模擬循環鏈表
$a = array(0,1,2,3,4);$i=0; $len = count($a);// 1 while(1) {if($i==$len){$i = 0;}ee($a[$i]);$i++;}// 2 while(1) {$i = $i%$len;ee($a[$i]);$i++; }// 3 while(1) {if(!next($a)){reset($a);}ee(current($a)); }// 4 for($i=0;$i<$len;) {ee($i);$i++;if($i == $len){$i = 0;} }?
curl 當post超過1024byte時的問題
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3* it adds a header, "Expect: 100-continue". * it then sends the request head, waits for a 100 response code, then sends the content Not all web servers support this though. Various errors are returned depending on the server. If this happens to you, suppress the "Expect" header with this command:<?phpcurl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); ?>See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/?
?檢測url的連通性(只獲取頭信息,不獲取返回的內容,但也必須等服務端執行完成)
function check_url($url) { $c = curl_init(); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_HEADER, 1); // get the header curl_setopt($c, CURLOPT_NOBODY, 1); // and *only* get the header curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // get the response as a string from curl_exec(), rather than echoing it curl_setopt($c, CURLOPT_FRESH_CONNECT, 1); // don't use a cached version of the url if (!curl_exec($c)) { return false; } $httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE); return ($httpcode < 400); }?
判斷一個數組是否是關聯數組
function is_assoc($arr) {return array_keys($arr) !== range(0, count($arr) - 1); }?
不同的 content-type
設置頭信息(Post請求) 1、curl_setopt ( $ch, CURLOPT_HTTPHEADER, array('Content-type:text/plain') ); file_get_contents('php://input', 'r') 獲取到 $_POST 獲取不到2、curl_setopt ( $ch, CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded') );#默認 file_get_contents('php://input', 'r') 獲取到 $_POST 獲取到3、curl_setopt ( $ch, CURLOPT_HTTPHEADER, array('Content-type:multipart/form-data; boundary=----WebKitFormBoundarygAvW9MJkUNVmzDjY') ); file_get_contents('php://input', 'r') 獲取不到 $_POST 獲取到?
?curl上傳文件
/*** * 傳遞一個數組到CURLOPT_POSTFIELDS,cURL會把數據編碼成 multipart/form-data,* 而然傳遞一個URL-encoded字符串時,數據會被編碼成 application/x-www-form-urlencoded。* */ $ch = curl_init();$data = array('name' => 'Foo', 'file' => '@/home/user/test.png;type=xx;filename=xx');curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);curl_exec($ch);?
curl獲取頭信息?(注意包括\r\n)
$response = curl_exec($ch);$curl_info = curl_getinfo($ch);curl_close($ch);$header_size = $curl_info['header_size'];$header = substr($response, 0, $header_size);$body = substr($response, $header_size);?
curl邊下載邊輸出內容
$ch = curl_init(); $fh = fopen('/path/to/stored/file/example_file.dat', 'w'); curl_setopt($ch, CURLOPT_FILE, $fh); curl_setopt($ch, CURLOPT_URL, 'http://example.com/example_file.dat'); curl_exec($ch); fflush($fh); fclose($fh);//must reset cURL file handle. Not doing so will cause a warning to be //thrown and for cURL to default to output regardless //for our example, we'll set return transfer. curl_setopt($ch, CURLOPT_FILE, fopen('php://stdout', 'w')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, 'http://example.org/index.html'); $html = curl_exec($ch); //this will now work /*** 注意: curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $fp); 放在后面否則不起作用 ,開啟后 curl_exec 不再能獲取到值*/?
?
?
?
?
總結
- 上一篇: 计算机常用英语(2)
- 下一篇: Exchange企业实战技巧(15)启用