分享10段PHP常用代码


Posted in PHP onNovember 11, 2015

本文汇集PHP开发中经常用到的十段代码,包括Email、64位编码和解码、解压缩、64位编码、解析JSON等,希望对您有所帮助。

1、使用PHP Mail函数发送Email

$to = "viralpatel.net@gmail.com"; 
$subject = "VIRALPATEL.net"; 
$body = "Body of your message here you can use HTML too. 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位编码和解码

function base64url_encode($plainText) {
$base64 = base64_encode($plainText);
$base64url = strtr($base64, '+/=', '-_,');
return $base64url;
}
function base64url_decode($plainText) {
$base64url = strtr($plainText, '-_,', '+/=');
$base64 = base64_decode($base64url);
return $base64;
}

3、获取远程IP地址

function getRealIPAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}

4、 日期格式化

function checkDateFormat($date)
{
//match the format of the date
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
{
//check weather the date is valid of not
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
}
else
return false;
}

5、验证Email

$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).
   ([a-zA-Z0-9]{2,4})~",$email)) {
echo 'This is a valid email.';
} else{
echo 'This is an invalid email.';
}

6、在PHP中轻松解析XML

//this is a sample xml string
$xml_string="??xml version='1.0'??
?moleculedb?
 ?molecule name='Benzine'?
 ?symbol?ben?/symbol?
 ?code?A?/code?
 ?/molecule?
 ?molecule name='Water'?
 ?symbol?h2o?/symbol?
 ?code?K?/code?
 ?/molecule?
?/moleculedb?";
//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);
//loop through the each node of molecule
foreach ($xml-?molecule as $record)
{
 //attribute are accessted by
 echo $record['name'], ' ';
 //node are accessted by -? operator
 echo $record-?symbol, ' ';
 echo $record-?code, '?br /?';
}

7、数据库连接

??php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost"; //Location Of Database usually its localhost
$dbUser = "xxxx"; //Database User Name
$dbPass = "xxxx"; //Database Password
$dbDatabase = "xxxx"; //Database Name
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or 
   die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404()
{
 header('HTTP/1.x 404 Not Found');
 print '?!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"?'."n".
 '?html??head?'."n".
 '?title?404 Not Found?/title?'."n".
 '?/head??body?'."n".
 '?h1?Not Found?/h1?'."n".
 '?p?The requested URL '.
 str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
 ' was not found on this server.?/p?'."n".
 '?/body??/html?'."n";
 exit;
}
# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";
??

8、创建和解析JSON数据

$json_data = array ('id'=?1,'name'=?"rolf",'country'=?'russia',
"office"=?array("google","oracle"));
echo json_encode($json_data);

9、处理MySQL时间戳

$query = "select UNIX_TIMESTAMP(date_field) as mydate 
 from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
echo $row;
}

10、解压缩Zip文件

??php
 function unzip($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);
 }
 return TRUE;
 }else{
 return FALSE;
 }
 }
??
//Use the code as following:
??php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
 echo 'Success!';
else
 echo 'Error';
??

PHP常用功能如下

1.PHP字符串

字符串声明 变量=''或者""(一般情况会使用单引号,因为写起来会比较方便)

$str = 'Hello PHP';
echo $str;

strpos 计算字符在字符串中的位置(从0开始)

$str = 'Hello PHP';
echo strpos($str,'o');  //计算字符在字符串中的位置
echo '<br/>';
echo strpos($str,'PH');

substr 截取字符串

$str = 'Hello PHP';
//截取字符串
$str1 = substr($str,2,3); //从2位置开始截取,截取长度为3的字符串
echo $str1;

不传入长度参数的话,会从指定位置一直截取到字符串的末尾

str_split 分割字符串  固定长度的分割(默认长度为1)

$str = 'Hello PHP';
//分割字符串
$result = str_split($str); //将结果保存到一个数组中
print_r($result); //使用print_r输入一个数组
echo '<br/>';
$result1 = str_split($str,2);
print_r($result1);

explode(分割字符,待分割的字符串) 按照空格进行分割

$str = 'Hello PHP Java C# C++';
$result = explode(' ',$str);
print_r($result);

字符串的连接

$str = 'Hello PHP Java C# C++';
//字符串的连接
$num = 100;
$str1 = $str.'<br/>Objective-C '.$num;
echo $str1;
echo '<br/>';
$str2 = "$str<br/>Objective-C $num"; //另一中简便的写法
echo $str2;
PHP 相关文章推荐
apache rewrite_module模块使用教程
Jan 10 PHP
PHP网站基础优化方法小结
Sep 29 PHP
php调用nginx的mod_zip模块打包ZIP文件
Jun 11 PHP
php使用$_POST或$_SESSION[]向js函数传参
Sep 16 PHP
PHP实现随机生成水印图片功能
Mar 22 PHP
PHP基于堆栈实现的高级计算器功能示例
Sep 15 PHP
PHP中递归的实现实例详解
Nov 14 PHP
在云虚拟主机部署thinkphp5项目的步骤详解
Dec 21 PHP
简单实用的PHP文本缓存类实例
Mar 22 PHP
PHP实现通过二维数组键值获取一维键名操作示例
Oct 11 PHP
laravel config文件配置全局变量的例子
Oct 13 PHP
PhpStorm2020 + phpstudyV8 +XDebug的教程详解
Sep 17 PHP
php+mysql实现无限级分类
Nov 11 #PHP
2款PHP无限级分类实例代码
Nov 11 #PHP
PHP中set error handler函数用法小结
Nov 11 #PHP
php实现Session存储到Redis
Nov 11 #PHP
PHP防止刷新重复提交页面的示例代码
Nov 11 #PHP
PHP用mb_string函数库处理与windows相关中文字符及Win环境下开启PHP Mb_String方法
Nov 11 #PHP
深入php内核之php in array
Nov 10 #PHP
You might like
全国FM电台频率大全 - 23 四川省
2020/03/11 无线电
js中escape对应的C#解码函数 UrlDecode
2012/12/16 Javascript
Javascript 检测键盘按键信息及键码值对应介绍
2013/01/03 Javascript
HTML5之lang属性与dir属性的详解
2013/06/19 Javascript
查找iframe里元素的方法可传参
2013/09/11 Javascript
jquery跨域请求示例分享(jquery发送ajax请求)
2014/03/25 Javascript
我的Node.js学习之路(一)
2014/07/06 Javascript
浅析javascript的间隔调用和延时调用
2014/11/12 Javascript
在JavaScript中call()与apply()区别
2016/01/22 Javascript
javascript实现的猜数小游戏完整实例代码
2016/05/10 Javascript
AngularJS ng-style中使用filter
2016/09/21 Javascript
JavaScript定时器实现的原理分析
2016/12/06 Javascript
JS变量及其作用域
2017/03/29 Javascript
如何选择适合你的JavaScript框架
2017/11/20 Javascript
echarts学习笔记之箱线图的分析与绘制详解
2017/11/22 Javascript
python通过ElementTree操作XML获取结点读取属性美化XML
2013/12/02 Python
跟老齐学Python之字典,你还记得吗?
2014/09/20 Python
python中sets模块的用法实例
2014/09/30 Python
python检测远程服务器tcp端口的方法
2015/03/14 Python
python实现简单ftp客户端的方法
2015/06/28 Python
Python脚本获取操作系统版本信息
2016/12/17 Python
Python3非对称加密算法RSA实例详解
2018/12/06 Python
python3+selenium实现qq邮箱登陆并发送邮件功能
2019/01/23 Python
Python获取二维数组的行列数的2种方法
2020/02/11 Python
python图形开发GUI库wxpython使用方法详解
2020/02/14 Python
不到20行实现Python代码即可制作精美证件照
2020/04/24 Python
css3个性化字体_动力节点Java学院整理
2017/07/12 HTML / CSS
用CSS3打造HTML5的Logo(实现代码)
2016/06/16 HTML / CSS
美国婚礼和派对礼品网站:Kate Aspen(新娘送礼会、迎婴派对)
2018/03/28 全球购物
大学英语演讲稿(中英文对照)
2014/01/14 职场文书
2014年百日安全生产活动总结
2014/05/04 职场文书
目标责任书格式
2014/07/28 职场文书
领导干部民主生活会自我剖析材料范文
2014/09/20 职场文书
初中英语教学反思范文
2016/02/15 职场文书
nginx部署多前端项目的几种方法
2021/05/25 Servers
Redis Stream类型的使用详解
2021/11/11 Redis