分享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 相关文章推荐
[FAQ]PHP中的一些常识:类篇
Oct 09 PHP
php strtotime 函数UNIX时间戳
Jan 14 PHP
PHP6 mysql连接方式说明
Feb 09 PHP
PHP 程序员应该使用的10个组件
Oct 31 PHP
php与paypal整合方法
Nov 28 PHP
PHP基础之运算符的使用方法
Apr 28 PHP
PHP的error_reporting错误级别变量对照表
Jul 08 PHP
Yii学习总结之安装配置
Feb 22 PHP
php简单实现查询数据库返回json数据
Apr 16 PHP
PHP编写简单的App接口
Aug 28 PHP
php无限极分类实现方法分析
Jul 04 PHP
如何用PHP实现分布算法之一致性哈希算法
May 26 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
使用php语句将数据库*.sql文件导入数据库
2014/05/05 PHP
fireworks菜单生成器mm_menu.js在 IE 7.0 显示问题的解决方法
2009/10/20 Javascript
jquery批量控制form禁用的代码
2013/08/06 Javascript
使用Ajax生成的Excel文件并下载的实例
2016/11/21 Javascript
JavaScript用JSONP跨域请求数据实例详解
2017/01/06 Javascript
js实现不提示直接关闭网页窗口
2017/03/30 Javascript
vue代理和跨域问题的解决
2018/07/18 Javascript
JavaScript事件对象event用法分析
2018/07/27 Javascript
vue登录页面cookie的使用及页面跳转代码
2019/07/10 Javascript
javascript面向对象三大特征之封装实例详解
2019/07/24 Javascript
layui 实现二级弹窗弹出之后 关闭一级弹窗的方法
2019/09/18 Javascript
JS highcharts实现动态曲线代码示例
2020/10/16 Javascript
vue开发chrome插件,实现获取界面数据和保存到数据库功能
2020/12/01 Vue.js
[41:08]TNC vs VG 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
[01:01:41]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Magma BO3 第二场 1月31日
2021/03/11 DOTA
python 计算文件的md5值实例
2017/01/13 Python
python爬虫入门教程--HTML文本的解析库BeautifulSoup(四)
2017/05/25 Python
Tensorflow 利用tf.contrib.learn建立输入函数的方法
2018/02/08 Python
对Python中gensim库word2vec的使用详解
2018/05/08 Python
python数值基础知识浅析
2019/11/19 Python
python使用hdfs3模块对hdfs进行操作详解
2020/06/06 Python
CSS3网格的三个新特性详解
2014/04/04 HTML / CSS
澳大利亚婴儿、幼儿和儿童在线设计师商店:Smooch Baby
2019/02/16 全球购物
NBA欧洲商店(西班牙):NBA Europe Store ES
2019/04/16 全球购物
Java面试笔试题大全
2016/11/23 面试题
外国语学院毕业生自荐信
2013/10/28 职场文书
中学门卫岗位职责
2013/12/26 职场文书
物流管理专业职业生涯规划书
2014/01/06 职场文书
教师绩效工资方案
2014/02/01 职场文书
公司财务流程之主管工作流程
2014/03/03 职场文书
班主任先进事迹材料
2014/12/17 职场文书
2015年国庆节广播稿
2015/08/19 职场文书
如何利用python和DOS获取wifi密码
2021/03/31 Python
排查并解决Oracle sysaux表空间异常增长
2022/04/20 Oracle
python和Appium的移动端多设备自动化测试框架
2022/04/26 Python
浅谈音视频 pts dts基本概念及理解
2022/08/05 数码科技