php的做為web編程語應(yīng)用是非常廣的,做為一個(gè)php程序員要知道并總結(jié)一些應(yīng)用寫法方式以方便日常的開發(fā)。
1、自動(dòng)判斷當(dāng)前http協(xié)議類型,這個(gè)應(yīng)用還是我在支付寶SDK中發(fā)現(xiàn)的,是一個(gè)不錯(cuò)的寫法。
$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環(huán)境下,在realpath后的路徑前面加上@字符是可以正常發(fā)送的。如果在linux中是不能正常發(fā)送的。正確的寫法是curl_file_create($fileurl)
$fileurl=realpath($fileObj-getRealFile());//獲取文件的實(shí)際物理路徑
$post_data=array(
'token'='88e780d49ff812c644c89ff31e5de196',
file=curl_file_create($fileurl),
);
4、php生成二維碼,使用的是PHPQRcode。
5、PHP浮點(diǎn)數(shù)精度丟失問題解決方案。原則:在進(jìn)行浮點(diǎn)數(shù)計(jì)算的時(shí)候一定要對(duì)浮點(diǎn)數(shù)進(jìn)行格式化!再代入進(jìn)行計(jì)算處理。
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、根據(jù)IP定位用戶所在城市信息
使用第三方ip庫來獲取內(nèi)容:http://www.ipip.net/download.html
7、隨機(jī)排列數(shù)組。shuffle()函數(shù)把數(shù)組中的元素按隨機(jī)順序重新排列。常在數(shù)據(jù)庫中查出數(shù)據(jù)后,用這個(gè)函數(shù)處理一下就可以生成隨機(jī)排列的新數(shù)組
8、php獲取上傳文件大小函數(shù)
/**
*文件大小格式化
*@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];
}