分享10段PHP常用代码
本文汇集PHP开发中经常用到的十段代码,包括Email、64位编码和解码、解压缩、64位编码、解析JSON等,希望对您有所帮助。
1、使用PHPMail函数发送Email
$to="viralpatel.net@gmail.com"; $subject="VIRALPATEL.net"; $body="BodyofyourmessagehereyoucanuseHTMLtoo.e.g.﹤br﹥﹤b﹥Bold﹤/b﹥"; $headers="From:Peter\r\n"; $headers.="Reply-To:info@yoursite.com\r\n"; $headers.="Return-Path:info@yoursite.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); ?﹥
2、PHP中的64位编码和解码
functionbase64url_encode($plainText){
$base64=base64_encode($plainText);
$base64url=strtr($base64,'+/=','-_,');
return$base64url;
}
functionbase64url_decode($plainText){
$base64url=strtr($plainText,'-_,','+/=');
$base64=base64_decode($base64url);
return$base64;
}
3、获取远程IP地址
functiongetRealIPAddr()
{
if(!empty($_SERVER['HTTP_CLIENT_IP']))//checkipfromshareinternet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))//tocheckipispassfromproxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return$ip;
}
4、日期格式化
functioncheckDateFormat($date)
{
//matchtheformatofthedate
if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/",$date,$parts))
{
//checkweatherthedateisvalidofnot
if(checkdate($parts[2],$parts[3],$parts[1]))
returntrue;
else
returnfalse;
}
else
returnfalse;
}
5、验证Email
$email=$_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).
([a-zA-Z0-9]{2,4})~",$email)){
echo'Thisisavalidemail.';
}else{
echo'Thisisaninvalidemail.';
}
6、在PHP中轻松解析XML
//thisisasamplexmlstring
$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,'﹤br/﹥';
}
7、数据库连接
﹤?php
if(basename(__FILE__)==basename($_SERVER['PHP_SELF']))send_404();
$dbHost="localhost";//LocationOfDatabaseusuallyitslocalhost
$dbUser="xxxx";//DatabaseUserName
$dbPass="xxxx";//DatabasePassword
$dbDatabase="xxxx";//DatabaseName
$db=mysql_connect("$dbHost","$dbUser","$dbPass")or
die("Errorconnectingtodatabase.");
mysql_select_db("$dbDatabase",$db)ordie("Couldn'tselectthedatabase.");
#Thisfunctionwillsendanimitation404pageiftheuser
#typesinthisfilesfilenameintotheaddressbar.
#onlyfilesconnectingwithinthesamedirectoryasthis
#filewillbeabletouseitaswell.
functionsend_404()
{
header('HTTP/1.x404NotFound');
print'﹤!DOCTYPEHTMLPUBLIC"-//IETF//DTDHTML2.0//EN"﹥'."n".
'﹤html﹥﹤head﹥'."n".
'﹤title﹥404NotFound﹤/title﹥'."n".
'﹤/head﹥﹤body﹥'."n".
'﹤h1﹥NotFound﹤/h1﹥'."n".
'﹤p﹥TherequestedURL'.
str_replace(strstr($_SERVER['REQUEST_URI'],'?'),'',$_SERVER['REQUEST_URI']).
'wasnotfoundonthisserver.﹤/p﹥'."n".
'﹤/body﹥﹤/html﹥'."n";
exit;
}
#Inanyfileyouwanttoconnecttothedatabase,
#andinthiscasewewillnamethisfiledb.php
#justaddthislineofphpcode(withoutthepoundsign):
#include"db.php";
?﹥
8、创建和解析JSON数据
$json_data=array('id'=﹥1,'name'=﹥"rolf",'country'=﹥'russia',
"office"=﹥array("google","oracle"));
echojson_encode($json_data);
9、处理MySQL时间戳
$query="selectUNIX_TIMESTAMP(date_field)asmydate
frommytablewhere1=1";
$records=mysql_query($query)ordie(mysql_error());
while($row=mysql_fetch_array($records))
{
echo$row;
}
10、解压缩Zip文件
﹤?php
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;
}
}
?﹥
//Usethecodeasfollowing:
﹤?php
include'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
echo'Success!';
else
echo'Error';
?﹥
PHP常用功能如下
1.PHP字符串
字符串声明变量=''或者""(一般情况会使用单引号,因为写起来会比较方便)
$str='HelloPHP';
echo$str;
strpos计算字符在字符串中的位置(从0开始)
$str='HelloPHP';
echostrpos($str,'o'); //计算字符在字符串中的位置
echo'<br/>';
echostrpos($str,'PH');
substr截取字符串
$str='HelloPHP'; //截取字符串 $str1=substr($str,2,3);//从2位置开始截取,截取长度为3的字符串 echo$str1;
不传入长度参数的话,会从指定位置一直截取到字符串的末尾
str_split分割字符串 固定长度的分割(默认长度为1)
$str='HelloPHP'; //分割字符串 $result=str_split($str);//将结果保存到一个数组中 print_r($result);//使用print_r输入一个数组 echo'<br/>'; $result1=str_split($str,2); print_r($result1);
explode(分割字符,待分割的字符串)按照空格进行分割
$str='HelloPHPJavaC#C++';
$result=explode('',$str);
print_r($result);
字符串的连接
$str='HelloPHPJavaC#C++'; //字符串的连接 $num=100; $str1=$str.'<br/>Objective-C'.$num; echo$str1; echo'<br/>'; $str2="$str<br/>Objective-C$num";//另一中简便的写法 echo$str2;