46 个非常有用的 PHP 代码片段
这些PHP片段对于PHP初学者也非常有帮助,非常容易学习,让我们开始学习吧~
在开发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); ?>
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。
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; ?>
使用下面的函数,可以检测用户是在哪个城市访问你的网站
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; ?>
使用下面的函数,可以获取任意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; ?>
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); ?>
有时候,当在网站填写表单,用户可能会输入错误的邮箱地址,这个函数可以验证邮箱地址是否有效。
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. ?>
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; ?>
如果你正在开发论坛,博客或者是一个常规的表单提交,很多时候都要用户访问一个网站。使用这个函数,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; ?>
这个代码片段可以方便你禁止某些特定的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; }
如果你需要下载特定的文件而不用另开新窗口,下面的代码片段可以帮助你。
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"); ?>
使用下面的PHP片段可以创建JSON数据,可以方便你创建移动应用的Web服务
$json_data=array('id'=>1,'name'=>"Mohit"); echojson_encode($json_data);
使用下面的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); ?>
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 ?>
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; }
之前我们提供了如何使用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); ?>
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; ?>
连接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(); } ?>
使用下面的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 ?>
使用下面的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; }
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 ?>
functiongenerateCsv($data,$delimiter=',',$enclosure='"'){ $handle=fopen('php://temp','r+'); foreach($dataas$line){ fputcsv($handle,$line,$delimiter,$enclosure); } rewind($handle); while(!feof($handle)){ $contents.=fread($handle,8192); } fclose($handle); return$contents; } 语法: <?php $data[0]="apple"; $data[1]="oranges"; generateCsv($data,$delimiter=',',$enclosure='"'); ?>
$xml_string="<?xmlversion='1.0'?> <moleculedb> <moleculename='Benzine'> <symbol>ben</symbol> <code>A</code> </molecule> <moleculename='Water'> <symbol>h2o</symbol> <code>K</code> </molecule> </moleculedb>"; //loadthexmlstringusingsimplexmlfunction $xml=simplexml_load_string($xml_string); //loopthroughtheeachnodeofmolecule foreach($xml->moleculeas$record) { //attributeareaccesstedby echo$record['name'],''; //nodeareaccesstedby->operator echo$record->symbol,''; echo$record->code,''; }
$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]}'; $obj=json_decode($json_string); //printtheparseddata echo$obj->name;//displaysrolf echo$obj->office[0];//displaysgoogle
这个PHP片段可以帮助你让用户登录后直接跳转到之前浏览的页面
functioncurrent_url() { $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; $validURL=str_replace("&","&",$url); returnvalidURL; }
语法:
<?php echo"Currentlyyouareon:".current_url(); ?>
functionmy_twitter($username) { $no_of_tweets=1; $feed="http://search.twitter.com/search.atom?q=from:".$username."&rpp=".$no_of_tweets; $xml=simplexml_load_file($feed); foreach($xml->children()as$child){ foreach($childas$value){ if($value->getName()=="link")$link=$value['href']; if($value->getName()=="content"){ $content=$value.""; echo'<pclass="twit">'.$content.'<aclass="twt"href="'.$link.'"title=""></a></p>'; } } } } 语法: <?php $handle="koonktech"; my_twitter($handle); ?>
使用这个PHP片段可以检测你的页面URL有多少转发数量
functiontweetCount($url){ $content=file_get_contents("http://api.tweetmeme.com/url_info?url=".$url); $element=newSimpleXmlElement($content); $retweets=$element->story->url_count; if($retweets){ return$retweets; }else{ return0; } } 语法: <?php $url="http://blog.koonk.com"; $count=tweetCount($url); return$count; ?>
<?php $date1=date('Y-m-d'); $date2="2015-12-04"; $diff=abs(strtotime($date2)-strtotime($date1)); $years=floor($diff/(365*60*60*24)); $months=floor(($diff-$years*365*60*60*24)/(30*60*60*24)); $days=floor(($diff-$years*365*60*60*24-$months*30*60*60*24)/(60*60*24)); printf("%dyears,%dmonths,%ddays\n",$years,$months,$days); --------------------------------------------------------OR $date1=newDateTime("2007-03-24"); $date2=newDateTime("2009-06-26"); $interval=$date1->diff($date2); echo"difference".$interval->y."years,".$interval->m."months,".$interval->d."days"; //showsthetotalamountofdays(notdividedintoyears,monthsanddayslikeabove) echo"difference".$interval->days."days"; --------------------------------------------------------OR /** *Calculatedifferencesbetweentwodateswithprecisesemantics.BasedonPHPsDateTime::diff() *implementationbyDerickRethans.PortedtoPHPbyEmilH,2011-05-02.Norightsreserved. * *Seeherefororiginalcode: *http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup *http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup */ function_date_range_limit($start,$end,$adj,$a,$b,$result) { if($result[$a]<$start){ $result[$b]-=intval(($start-$result[$a]-1)/$adj)+1; $result[$a]+=$adj*intval(($start-$result[$a]-1)/$adj+1); } if($result[$a]>=$end){ $result[$b]+=intval($result[$a]/$adj); $result[$a]-=$adj*intval($result[$a]/$adj); } return$result; } function_date_range_limit_days($base,$result) { $days_in_month_leap=array(31,31,29,31,30,31,30,31,31,30,31,30,31); $days_in_month=array(31,31,28,31,30,31,30,31,31,30,31,30,31); _date_range_limit(1,13,12,"m","y",&$base); $year=$base["y"]; $month=$base["m"]; if(!$result["invert"]){ while($result["d"]<0){ $month--; if($month<1){ $month+=12; $year--; } $leapyear=$year%400==0||($year%100!=0&&$year%4==0); $days=$leapyear?$days_in_month_leap[$month]:$days_in_month[$month]; $result["d"]+=$days; $result["m"]--; } }else{ while($result["d"]<0){ $leapyear=$year%400==0||($year%100!=0&&$year%4==0); $days=$leapyear?$days_in_month_leap[$month]:$days_in_month[$month]; $result["d"]+=$days; $result["m"]--; $month++; if($month>12){ $month-=12; $year++; } } } return$result; } function_date_normalize($base,$result) { $result=_date_range_limit(0,60,60,"s","i",$result); $result=_date_range_limit(0,60,60,"i","h",$result); $result=_date_range_limit(0,24,24,"h","d",$result); $result=_date_range_limit(0,12,12,"m","y",$result); $result=_date_range_limit_days(&$base,&$result); $result=_date_range_limit(0,12,12,"m","y",$result); return$result; } /** *Acceptstwounixtimestamps. */ function_date_diff($one,$two) { $invert=false; if($one>$two){ list($one,$two)=array($two,$one); $invert=true; } $key=array("y","m","d","h","i","s"); $a=array_combine($key,array_map("intval",explode("",date("YmdHis",$one)))); $b=array_combine($key,array_map("intval",explode("",date("YmdHis",$two)))); $result=array(); $result["y"]=$b["y"]-$a["y"]; $result["m"]=$b["m"]-$a["m"]; $result["d"]=$b["d"]-$a["d"]; $result["h"]=$b["h"]-$a["h"]; $result["i"]=$b["i"]-$a["i"]; $result["s"]=$b["s"]-$a["s"]; $result["invert"]=$invert?1:0; $result["days"]=intval(abs(($one-$two)/86400)); if($invert){ _date_normalize(&$a,&$result); }else{ _date_normalize(&$b,&$result); } return$result; } $date="2014-12-0419:37:22"; echo'<pre>'; print_r(_date_diff(strtotime($date),time())); echo'</pre>'; ?>
functionDelete($path) { if(is_dir($path)===true) { $files=array_diff(scandir($path),array('.','..')); foreach($filesas$file) { Delete(realpath($path).'/'.$file); } returnrmdir($path); } elseif(is_file($path)===true) { returnunlink($path); } returnfalse; }
语法:
<?php $path="images/"; Delete($path);//Thiswilldeleteimagesfolderalongwithitscontents. ?>
functionhighlighter_text($text,$words) { $split_words=explode("",$words); foreach($split_wordsas$word) { $color="#4285F4"; $text=preg_replace("|($word)|Ui", "<spanstyle=\"color:".$color.";\"><b>$1</b></span>",$text); } return$text; }
语法:
<?php $string="IlikechocolatesandIlikeapples"; $words="apple"; echohighlighter_text($string,$words); ?>
33.写入文件
<? $filename='blog.csv'; $fp=fopen($filename,'w'); $output="Hello"; $output.="World!"; $output.="\r\n"; fputs($fp,$output); fclose($fp); ?>
functionimagefromURL($image,$rename) { $ch=curl_init($image); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec($ch); curl_close($ch); $fp=fopen("$rename",'w'); fwrite($fp,$rawdata); fclose($fp); }
语法:
<?php $url="http://koonk.com/images/logo.png"; $rename="koonk.png"; imagefromURL($url,$rename); ?>
functionisvalidURL($url) { $check=0; if(filter_var($url,FILTER_VALIDATE_URL)!==false){ $check=1; } return$check; } 语法: <?php $url="http://koonk.com"; $check=checkvalidURL($url); echo$check;//ifreturns1thenURLisvalid. ?>
functionqr_code($data,$type="TXT",$size='150',$ec='L',$margin='0') { $types=array("URL"=-->"http://","TEL"=>"TEL:","TXT"=>"","EMAIL"=>"MAILTO:"); if(!in_array($type,array("URL","TEL","TXT","EMAIL"))) { $type="TXT"; } if(!preg_match('/^'.$types[$type].'/',$data)) { $data=str_replace("\\","",$types[$type]).$data; } $ch=curl_init(); $data=urlencode($data); curl_setopt($ch,CURLOPT_URL,'http://chart.apis.google.com/chart'); curl_setopt($ch,CURLOPT_POST,true); curl_setopt($ch,CURLOPT_POSTFIELDS,'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_HEADER,false); curl_setopt($ch,CURLOPT_TIMEOUT,30); $response=curl_exec($ch); curl_close($ch); return$response; }
语法:
<?php header("Content-type:image/png"); echoqr_code("http://koonk.com","URL"); ?>
functiongetDistanceBetweenPointsNew($latitude1,$longitude1,$latitude2,$longitude2){ $theta=$longitude1-$longitude2; $miles=(sin(deg2rad($latitude1))*sin(deg2rad($latitude2)))+(cos(deg2rad($latitude1))*cos(deg2rad($latitude2))*cos(deg2rad($theta))); $miles=acos($miles); $miles=rad2deg($miles); $miles=$miles*60*1.1515; $feet=$miles*5280; $yards=$feet/3; $kilometers=$miles*1.609344; $meters=$kilometers*1000; returncompact('miles','feet','yards','kilometers','meters'); }
语法:
<?php $point1=array('lat'=>40.770623,'long'=>-73.964367); $point2=array('lat'=>40.758224,'long'=>-73.917404); $distance=getDistanceBetweenPointsNew($point1['lat'],$point1['long'],$point2['lat'],$point2['long']); foreach($distanceas$unit=>$value){ echo$unit.':'.number_format($value,4).''; } ?>
functiongetTweets($hash_tag){ $url='http://search.twitter.com/search.atom?q='.urlencode($hash_tag); echo"<p>Connectingto<strong>$url</strong>...</p>"; $ch=curl_init($url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE); $xml=curl_exec($ch); curl_close($ch); //IfyouwanttoseetheresponsefromTwitter,uncommentthisnextpartout: //echo"<p>Response:</p>"; //echo"<pre>".htmlspecialchars($xml)."</pre>"; $affected=0; $twelement=newSimpleXMLElement($xml); foreach($twelement->entryas$entry){ $text=trim($entry->title); $author=trim($entry->author->name); $time=strtotime($entry->published); $id=$entry->id; echo"<p>Tweetfrom".$author.":<strong>".$text."</strong><em>Posted".date('n/j/yg:ia',$time)."</em></p>"; } returntrue; }
Fridaythe13th functionordinal($cdnl){ $test_c=abs($cdnl)%10; $ext=((abs($cdnl)%100<21&&abs($cdnl)%100>4)?'th' :(($test_c<4)?($test_c<3)?($test_c<2)?($test_c<1) ?'th':'st':'nd':'rd':'th')); return$cdnl.$ext; }
语法:
<?php $number=10; echoordinal($number);//outputis10th ?>
<?php //localfilethatshouldbesendtotheclient $local_file='test-file.zip'; //filenamethattheusergetsasdefault $download_file='your-download-name.zip'; //setthedownloadratelimit(=>20,5kb/s) $download_rate=20.5; if(file_exists($local_file)&&is_file($local_file)){ //sendheaders header('Cache-control:private'); header('Content-Type:application/octet-stream'); header('Content-Length:'.filesize($local_file)); header('Content-Disposition:filename='.$download_file); //flushcontent flush(); //openfilestream $file=fopen($local_file,"r"); while(!feof($file)){ //sendthecurrentfileparttothebrowser printfread($file,round($download_rate*1024)); //flushthecontenttothebrowser flush(); //sleeponesecond sleep(1); } //closefilestream fclose($file);} else{ die('Error:Thefile'.$local_file.'doesnotexist!'); } ?>
<?php header("Content-type:image/png"); $string=$_GET['text']; $im=imagecreatefrompng("images/button.png"); $color=imagecolorallocate($im,255,255,255); $px=(imagesx($im)-7.5*strlen($string))/2; $py=9; $fontSize=1; imagestring($im,fontSize,$px,$py,$string,$color); imagepng($im); imagedestroy($im); ?>
functionremote_filesize($url,$user="",$pw="") { ob_start(); $ch=curl_init($url); curl_setopt($ch,CURLOPT_HEADER,1); curl_setopt($ch,CURLOPT_NOBODY,1); if(!empty($user)&&!empty($pw)) { $headers=array('Authorization:Basic'.base64_encode("$user:$pw")); curl_setopt($ch,CURLOPT_HTTPHEADER,$headers); } $ok=curl_exec($ch); curl_close($ch); $head=ob_get_contents(); ob_end_clean(); $regex='/Content-Length:\s([0-9].+?)\s/'; $count=preg_match($regex,$head,$matches); returnisset($matches[1])?$matches[1]:"unknown"; }
语法:
<?php $file="http://koonk.com/images/logo.png"; $size=remote_filesize($url); echo$size; ?>
<?php $pdf_file='./pdf/demo.pdf'; $save_to='./jpg/demo.jpg';//makesurethatapachehaspermissionstowriteinthisfolder!(commonproblem) //executeImageMagickcommand'convert'andconvertPDFtoJPGwithappliedsettings exec('convert"'.$pdf_file.'"-colorspaceRGB-resize800"'.$save_to.'"',$output,$return_var); if($return_var==0){//ifexecsuccessfulyconvertedpdftojpg print"ConversionOK"; } elseprint"Conversionfailed.".$output; ?>
functionget_tiny_url($url) { $ch=curl_init(); $timeout=5; curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data=curl_exec($ch); curl_close($ch); return$data; }
语法:
<?php $url="http://blog.koonk.com/2015/07/Hello-World"; $tinyurl=get_tiny_url($url); echo$tinyurl; ?>
使用下面的PHP片段可以让你的用户下载Youtube视频
functionstr_between($string,$start,$end) { $string="".$string;$ini=strpos($string,$start);if($ini==0)return"";$ini+=strlen($start);$len=strpos($string,$end,$ini)-$ini;returnsubstr($string,$ini,$len);} functionget_youtube_download_link(){ $youtube_link=$_GET['youtube']; $youtube_page=file_get_contents($youtube_link); $v_id=str_between($youtube_page,"&video_id=","&"); $t_id=str_between($youtube_page,"&t=","&"); $flv_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id"; $hq_flv_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=6"; $mp4_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=18"; $threegp_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=17"; echo"\t\tDownload(right-click>saveas):\n\t\t"; echo"<ahref=\"$flv_link\">FLV</a>\n\t\t"; echo"<ahref=\"$hq_flv_link\">HQFLV(ifavailable)</a>\n\t\t"; echo"<ahref=\"$mp4_link\">MP4</a>\n\t\t"; echo"<ahref=\"$threegp_link\">3GP</a>\n"; }
Facebook(xminsage,yhoursagoetc) functionnicetime($date) { if(empty($date)){ return"Nodateprovided"; } $periods=array("second","minute","hour","day","week","month","year","decade"); $lengths=array("60","60","24","7","4.35","12","10"); $now=time(); $unix_date=strtotime($date); //checkvalidityofdate if(empty($unix_date)){ return"Baddate"; } //isitfuturedateorpastdate if($now>$unix_date){ $difference=$now-$unix_date; $tense="ago"; }else{ $difference=$unix_date-$now; $tense="fromnow"; } for($j=0;$difference>=$lengths[$j]&&$j<count($lengths)-1;$j++){ $difference/=$lengths[$j]; } $difference=round($difference); if($difference!=1){ $periods[$j].="s"; } return"$difference$periods[$j]{$tense}"; }
语法:
<?php $date="2015-07-0503:45"; $result=nicetime($date);//2daysago ?>
文章转自:http://blog.koonk.com