php的做為web編程語應用是非常廣的,做為一個php程序員要知道并總結一些應用寫法方式以方便日常的開發。
1、自動判斷當前http協議類型,這個應用還是我在支付寶SDK中發現的,是一個不錯的寫法。
$protocol=(!empty($_SERVER['HTTPS'])$_SERVER['HTTPS']!=='off'||$_SERVER['SERVER_PORT']==443)?https://:www.300.cnserbanghita/Mobile-Detect/
require_once'Mobile_Detect.php';
$detect=newMobile_Detect;
$deviceType=($detect-isMobile()?($detect-isTablet()?'tablet':'phone'):'computer');
3、php通過curl上傳文件,特別注意的是下面的file路徑,如果在windows環境下,在realpath后的路徑前面加上@字符是可以正常發送的。如果在linux中是不能正常發送的。正確的寫法是curl_file_create($fileurl)
$fileurl=realpath($fileObj-getRealFile());//獲取文件的實際物理路徑
$post_data=array(
'token'='88e780d49ff812c644c89ff31e5de196',
file=curl_file_create($fileurl),
);
4、php生成二維碼,使用的是PHPQRcode。
5、PHP浮點數精度丟失問題解決方案。原則:在進行浮點數計算的時候一定要對浮點數進行格式化!再代入進行計算處理。
var_dump(intval(sprintf(%.2f,$f*100)));//string'5
8.00'//int58
var_dump(intval(round($f*100,1)));//float58//int58
var_dump(intval(number_format($f*100,2)));//string'5
8.00'//int58
6、根據IP定位用戶所在城市信息
使用第三方ip庫來獲取內容:http://www.ipip.net/download.html
7、隨機排列數組。shuffle()函數把數組中的元素按隨機順序重新排列。常在數據庫中查出數據后,用這個函數處理一下就可以生成隨機排列的新數組
8、php獲取上傳文件大小函數
/**
*文件大小格式化
*@paramtype$filename文件路徑
*/
functiongetFilesize($filename){
$filename=$_SERVER['DOCUMENT_ROOT']..$filename;
$size=filesize($filename);
$mod=1024;
$units=explode('','BKBMBGBPB');
for($i=0;$size$mod;$i++){
$size/=$mod;
}
returnround($size,2).''.$units[$i];
}