必须收藏的23个php实用代码片段
在编写代码的时候有个神奇的工具总是好的!下面这里收集了40+PHP代码片段,可以帮助你开发PHP项目。
这些PHP片段对于PHP初学者也非常有帮助,非常容易学习,让我们开始学习吧~
1.发送SMS
在开发Web或者移动应用的时候,经常会遇到需要发送SMS给用户,或者因为登录原因,或者是为了发送信息。下面的PHP代码就实现了发送SMS的功能。
为了使用任何的语言发送SMS,需要一个SMSgateway。大部分的SMS会提供一个API,这里是使用MSG91作为SMSgateway。
functionsend_sms($mobile,$msg)
{
$authKey="XXXXXXXXXXX";
date_default_timezone_set("Asia/Kolkata");
$date=strftime("%Y-%m-%d%H:%M:%S");
//Multiplemobilesnumbersseparatedbycomma
$mobileNumber=$mobile;
//SenderID,Whileusingroute4senderidshouldbe6characterslong.
$senderId="IKOONK";
//Yourmessagetosend,AddURLencodinghere.
$message=urlencode($msg);
//Defineroute
$route="template";
//Prepareyoupostparameters
$postData=array(
'authkey'=>$authKey,
'mobiles'=>$mobileNumber,
'message'=>$message,
'sender'=>$senderId,
'route'=>$route
);
//APIURL
$url="https://control.msg91.com/sendhttp.php";
//inittheresource
$ch=curl_init();
curl_setopt_array($ch,array(
CURLOPT_URL=>$url,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>$postData
//,CURLOPT_FOLLOWLOCATION=>true
));
//IgnoreSSLcertificateverification
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
//getresponse
$output=curl_exec($ch);
//Printerrorifany
if(curl_errno($ch))
{
echo'error:'.curl_error($ch);
}
curl_close($ch);
}
其中“$authKey="XXXXXXXXXXX";”需要你输入你的密码,“$senderId="IKOONK";”需要你输入你的SenderID。当输入移动号码的时候需要指定国家代码(比如,美国是1,印度是91)。
语法:
<?php $message="HelloWorld"; $mobile="918112998787"; send_sms($mobile,$message); ?>
2.使用mandrill发送邮件
Mandrill是一款强大的SMTP提供器。开发者倾向于使用一个第三方SMTPprovider来获取更好的收件交付。
下面的函数中,你需要把“Mandrill.php”放在同一个文件夹,作为PHP文件,这样就可以使用TA来发送邮件。
functionsend_email($to_email,$subject,$message1)
{
require_once'Mandrill.php';
$apikey='XXXXXXXXXX';//specifyyourapikeyhere
$mandrill=newMandrill($apikey);
$message=newstdClass();
$message->html=$message1;
$message->text=$message1;
$message->subject=$subject;
$message->from_email="blog@koonk.com";//SenderEmail
$message->from_name="KOONK";//SenderName
$message->to=array(array("email"=>$to_email));
$message->track_opens=true;
$response=$mandrill->messages->send($message);
}
$apikey='XXXXXXXXXX';//specifyyourapikeyhere”这里需要你指定你的API密钥(从Mandrill账户中获得)。
语法:
<?php $to="abc@example.com"; $subject="Thisisatestemail"; $message="HelloWorld!"; send_email($to,$subject,$message); ?>
为了达到最好的效果,最好按照Mandrill的教程去配置DNS。
3.PHP函数:阻止SQL注入
SQL注入或者SQLi常见的攻击网站的手段,使用下面的代码可以帮助你防止这些工具。
functionclean($input)
{
if(is_array($input))
{
foreach($inputas$key=>$val)
{
$output[$key]=clean($val);
//$output[$key]=$this->clean($val);
}
}
else
{
$output=(string)$input;
//ifmagicquotesisonthenusestripslashes
if(get_magic_quotes_gpc())
{
$output=stripslashes($output);
}
//$output=strip_tags($output);
$output=htmlentities($output,ENT_QUOTES,'UTF-8');
}
//returnthecleantext
return$output;
}
语法:
<?php $text="<script>alert(1)</script>"; $text=clean($text); echo$text; ?>
4.检测用户位置
使用下面的函数,可以检测用户是在哪个城市访问你的网站
functiondetect_city($ip){
$default='UNKNOWN';
$curlopt_useragent='Mozilla/5.0(Windows;U;WindowsNT5.1;en-US;rv:1.9.2)Gecko/20100115Firefox/3.6(.NETCLR3.5.30729)';
$url='http://ipinfodb.com/ip_locator.php?ip='.urlencode($ip);
$ch=curl_init();
$curl_opt=array(
CURLOPT_FOLLOWLOCATION=>1,
CURLOPT_HEADER=>0,
CURLOPT_RETURNTRANSFER=>1,
CURLOPT_USERAGENT=>$curlopt_useragent,
CURLOPT_URL=>$url,
CURLOPT_TIMEOUT=>1,
CURLOPT_REFERER=>'http://'.$_SERVER['HTTP_HOST'],
);
curl_setopt_array($ch,$curl_opt);
$content=curl_exec($ch);
if(!is_null($curl_info)){
$curl_info=curl_getinfo($ch);
}
curl_close($ch);
if(preg_match('{<li>City:([^<]*)</li>}i',$content,$regs)){
$city=$regs[1];
}
if(preg_match('{<li>State/Province:([^<]*)</li>}i',$content,$regs)){
$state=$regs[1];
}
if($city!=''&&$state!=''){
$location=$city.','.$state;
return$location;
}else{
return$default;
}
}
语法:
<?php $ip=$_SERVER['REMOTE_ADDR']; $city=detect_city($ip); echo$city; ?>
5.获取Web页面的源代码
使用下面的函数,可以获取任意Web页面的HTML代码
functiondisplay_sourcecode($url)
{
$lines=file($url);
$output="";
foreach($linesas$line_num=>$line){
//loopthrueachlineandprependlinenumbers
$output.="Line#<b>{$line_num}</b>:".htmlspecialchars($line)."\n";
}
}
语法:
<?php $url="http://blog.koonk.com"; $source=display_sourcecode($url); echo$source; ?>
6.计算喜欢你的Facebook页面的用户
functionfb_fan_count($facebook_name)
{
$data=json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
$likes=$data->likes;
return$likes;
}
语法:
<?php $page="koonktechnologies"; $count=fb_fan_count($page); echo$count; ?>
7.确定任意图片的主导颜色
functiondominant_color($image)
{
$i=imagecreatefromjpeg($image);
for($x=0;$x<imagesx($i);$x++){
for($y=0;$y<imagesy($i);$y++){
$rgb=imagecolorat($i,$x,$y);
$r=($rgb>>16)&0xFF;
$g=($rgb>>&0xFF;
$b=$rgb&0xFF;
$rTotal+=$r;
$gTotal+=$g;
$bTotal+=$b;
$total++;
}
}
$rAverage=round($rTotal/$total);
$gAverage=round($gTotal/$total);
$bAverage=round($bTotal/$total);
}
8.whois查询
使用下面的函数可以获取任何域名用户的完整细节
functionwhois_query($domain){
//fixthedomainname:
$domain=strtolower(trim($domain));
$domain=preg_replace('/^http:\/\//i','',$domain);
$domain=preg_replace('/^www\./i','',$domain);
$domain=explode('/',$domain);
$domain=trim($domain[0]);
//splittheTLDfromdomainname
$_domain=explode('.',$domain);
$lst=count($_domain)-1;
$ext=$_domain[$lst];
//Youfindresourcesandlists
//liketheseonwikipedia:
//
//http://de.wikipedia.org/wiki/Whois
//
$servers=array(
"biz"=>"whois.neulevel.biz",
"com"=>"whois.internic.net",
"us"=>"whois.nic.us",
"coop"=>"whois.nic.coop",
"info"=>"whois.nic.info",
"name"=>"whois.nic.name",
"net"=>"whois.internic.net",
"gov"=>"whois.nic.gov",
"edu"=>"whois.internic.net",
"mil"=>"rs.internic.net",
"int"=>"whois.iana.org",
"ac"=>"whois.nic.ac",
"ae"=>"whois.uaenic.ae",
"at"=>"whois.ripe.net",
"au"=>"whois.aunic.net",
"be"=>"whois.dns.be",
"bg"=>"whois.ripe.net",
"br"=>"whois.registro.br",
"bz"=>"whois.belizenic.bz",
"ca"=>"whois.cira.ca",
"cc"=>"whois.nic.cc",
"ch"=>"whois.nic.ch",
"cl"=>"whois.nic.cl",
"cn"=>"whois.cnnic.net.cn",
"cz"=>"whois.nic.cz",
"de"=>"whois.nic.de",
"fr"=>"whois.nic.fr",
"hu"=>"whois.nic.hu",
"ie"=>"whois.domainregistry.ie",
"il"=>"whois.isoc.org.il",
"in"=>"whois.ncst.ernet.in",
"ir"=>"whois.nic.ir",
"mc"=>"whois.ripe.net",
"to"=>"whois.tonic.to",
"tv"=>"whois.tv",
"ru"=>"whois.ripn.net",
"org"=>"whois.pir.org",
"aero"=>"whois.information.aero",
"nl"=>"whois.domain-registry.nl"
);
if(!isset($servers[$ext])){
die('Error:Nomatchingnicserverfound!');
}
$nic_server=$servers[$ext];
$output='';
//connecttowhoisserver:
if($conn=fsockopen($nic_server,43)){
fputs($conn,$domain."\r\n");
while(!feof($conn)){
$output.=fgets($conn,128);
}
fclose($conn);
}
else{die('Error:Couldnotconnectto'.$nic_server.'!');}
return$output;
}
语法:
<?php $domain="http://www.blog.koonk.com"; $result=whois_query($domain); print_r($result); ?>
9.验证邮箱地址
有时候,当在网站填写表单,用户可能会输入错误的邮箱地址,这个函数可以验证邮箱地址是否有效。
functionis_validemail($email)
{
$check=0;
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
$check=1;
}
return$check;
}
语法:
<?php $email="blog@koonk.com"; $check=is_validemail($email); echo$check; //Iftheoutputis1,thenemailisvalid. ?>
10.获取用户的真实 IP
functiongetRealIpAddr()
{
if(!emptyempty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
//tocheckipispassfromproxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return$ip;
}
语法:
<?php $ip=getRealIpAddr(); echo$ip; ?>
11.转换URL:从字符串变成超链接
如果你正在开发论坛,博客或者是一个常规的表单提交,很多时候都要用户访问一个网站。使用这个函数,URL字符串就可以自动的转换为超链接。
functionmakeClickableLinks($text)
{
$text=eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
'<ahref="\1">\1</a>',$text);
$text=eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
'\1<ahref="http://\2">\2</a>',$text);
$text=eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
'<ahref="mailto:\1">\1</a>',$text);
return$text;
}
语法:
<?php $text="Thisismyfirstpostonhttp://blog.koonk.com"; $text=makeClickableLinks($text); echo$text; ?>
12.阻止多个IP访问你的网站
这个代码片段可以方便你禁止某些特定的IP地址访问你的网站
if(!file_exists('blocked_ips.txt')){
$deny_ips=array(
'127.0.0.1',
'192.168.1.1',
'83.76.27.9',
'192.168.1.163'
);
}else{
$deny_ips=file('blocked_ips.txt');
}
//readuseripadress:
$ip=isset($_SERVER['REMOTE_ADDR'])?trim($_SERVER['REMOTE_ADDR']):'';
//searchcurrentIPin$deny_ipsarray
if((array_search($ip,$deny_ips))!==FALSE){
//addressisblocked:
echo'YourIPadress('.$ip.')wasblocked!';
exit;
}
13.强制性文件下载
如果你需要下载特定的文件而不用另开新窗口,下面的代码片段可以帮助你。
functionforce_download($file)
{
$dir="../log/exports/";
if((isset($file))&&(file_exists($dir.$file))){
header("Content-type:application/force-download");
header('Content-Disposition:inline;filename="'.$dir.$file.'"');
header("Content-Transfer-Encoding:Binary");
header("Content-length:".filesize($dir.$file));
header('Content-Type:application/octet-stream');
header('Content-Disposition:attachment;filename="'.$file.'"');
readfile("$dir$file");
}else{
echo"Nofileselected";
}
}
语法:
<php
force_download("image.jpg");
?>
14.创建JSON数据
使用下面的PHP片段可以创建JSON数据,可以方便你创建移动应用的Web服务
$json_data=array('id'=>1,'name'=>"Mohit");
echojson_encode($json_data);
15.压缩zip文件
使用下面的PHP片段可以即时压缩zip文件
functioncreate_zip($files=array(),$destination='',$overwrite=false){
//ifthezipfilealreadyexistsandoverwriteisfalse,returnfalse
if(file_exists($destination)&&!$overwrite){returnfalse;}
//vars
$valid_files=array();
//iffileswerepassedin...
if(is_array($files)){
//cyclethrougheachfile
foreach($filesas$file){
//makesurethefileexists
if(file_exists($file)){
$valid_files[]=$file;
}
}
}
//ifwehavegoodfiles...
if(count($valid_files)){
//createthearchive
$zip=newZipArchive();
if($zip->open($destination,$overwrite?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)!==true){
returnfalse;
}
//addthefiles
foreach($valid_filesas$file){
$zip->addFile($file,$file);
}
//debug
//echo'Theziparchivecontains',$zip->numFiles,'fileswithastatusof',$zip->status;
//closethezip--done!
$zip->close();
//checktomakesurethefileexists
returnfile_exists($destination);
}
else
{
returnfalse;
}
}
语法:
<?php
$files=array('file1.jpg','file2.jpg','file3.gif');
create_zip($files,'myzipfile.zip',true);
?>
16.解压文件
functionunzip($location,$newLocation)
{
if(exec("unzip$location",$arr)){
mkdir($newLocation);
for($i=1;$i<count($arr);$i++){
$file=trim(preg_replace("~inflating:~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
returnTRUE;
}else{
returnFALSE;
}
}
语法:
<?php
unzip('test.zip','unziped/test');//Filewouldbeunzippedinunziped/testfolder
?>
17.缩放图片
functionresize_image($filename,$tmpname,$xmax,$ymax)
{
$ext=explode(".",$filename);
$ext=$ext[count($ext)-1];
if($ext=="jpg"||$ext=="jpeg")
$im=imagecreatefromjpeg($tmpname);
elseif($ext=="png")
$im=imagecreatefrompng($tmpname);
elseif($ext=="gif")
$im=imagecreatefromgif($tmpname);
$x=imagesx($im);
$y=imagesy($im);
if($x<=$xmax&&$y<=$ymax)
return$im;
if($x>=$y){
$newx=$xmax;
$newy=$newx*$y/$x;
}
else{
$newy=$ymax;
$newx=$x/$y*$newy;
}
$im2=imagecreatetruecolor($newx,$newy);
imagecopyresized($im2,$im,0,0,0,0,floor($newx),floor($newy),$x,$y);
return$im2;
}
18.使用mail()发送邮件
之前我们提供了如何使用Mandrill发送邮件的PHP代码片段,但是如果你不想使用第三方服务,那么可以使用下面的PHP代码片段。
functionsend_mail($to,$subject,$body)
{
$headers="From:KOONK\r\n";
$headers.="Reply-To:blog@koonk.com\r\n";
$headers.="Return-Path:blog@koonk.com\r\n";
$headers.="X-Mailer:PHP5\n";
$headers.='MIME-Version:1.0'."\n";
$headers.='Content-type:text/html;charset=iso-8859-1'."\r\n";
mail($to,$subject,$body,$headers);
}
语法:
<?php $to="admin@koonk.com"; $subject="Thisisatestmail"; $body="HelloWorld!"; send_mail($to,$subject,$body); ?>
19.把秒转换成天数,小时数和分钟
functionsecsToStr($secs){
if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.'day';if($days<>1){$r.='s';}if($secs>0){$r.=',';}}
if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.'hour';if($hours<>1){$r.='s';}if($secs>0){$r.=',';}}
if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.'minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=',';}}
$r.=$secs.'second';if($secs<>1){$r.='s';}
return$r;
}
语法:
<?php $seconds="56789"; $output=secsToStr($seconds); echo$output; ?>
20.数据库连接
连接MySQL数据库
<?php
$DBNAME='koonk';
$HOST='localhost';
$DBUSER='root';
$DBPASS='koonk';
$CONNECT=mysql_connect($HOST,$DBUSER,$DBPASS);
if(!$CONNECT)
{
echo'MySQLError:'.mysql_error();
}
$SELECT=mysql_select_db($DBNAME);
if(!$SELECT)
{
echo'MySQLError:'.mysql_error();
}
?>
21.目录清单
使用下面的PHP代码片段可以在一个目录中列出所有文件和文件夹
functionlist_files($dir)
{
if(is_dir($dir))
{
if($handle=opendir($dir))
{
while(($file=readdir($handle))!==false)
{
if($file!="."&&$file!=".."&&$file!="Thumbs.db"/*peskywindows,images..*/)
{
echo'<atarget="_blank"href="'.$dir.$file.'">'.$file.'</a>'."\n";
}
}
closedir($handle);
}
}
}
语法:
<?php
list_files("images/");//Thiswilllistallfilesofimagesfolder
?>
22.检测用户语言
使用下面的PHP代码片段可以检测用户浏览器所使用的语言
functionget_client_language($availableLanguages,$default='en'){
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach($langsas$value){
$choice=substr($value,0,2);
if(in_array($choice,$availableLanguages)){
return$choice;
}
}
}
return$default;
}
23.查看CSV文件
functionreadCSV($csvFile){
$file_handle=fopen($csvFile,'r');
while(!feof($file_handle)){
$line_of_text[]=fgetcsv($file_handle,1024);
}
fclose($file_handle);
return$line_of_text;
}
语法:
<?php $csvFile="test.csv"; $csv=readCSV($csvFile); $a=csv[0][0];//ThiswillgetvalueofColumn1&Row1 ?>
以上就是本文的全部内容,希望对大家的学习有所帮助。