分享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 相关文章推荐
php学习 函数 课件
Jun 15 PHP
[原创]效率较高的php下读取文本文件的代码
Jul 02 PHP
Zend studio for eclipse中使php可以调用mysql相关函数的设置方法
Oct 13 PHP
php小偷相关截取函数备忘
Nov 28 PHP
PHP 调试工具Debug Tools
Apr 30 PHP
php代码运行时间查看类代码分享
Aug 06 PHP
探讨php define()函数及defined()函数使用详解
Jun 09 PHP
easyui的tabs update正确用法分享
Mar 21 PHP
Yii2下session跨域名共存的解决方案
Feb 04 PHP
Laravel 模型关联基础教程详解
Sep 17 PHP
laravel Task Scheduling(任务调度)在windows下的使用详解
Oct 22 PHP
PHP反射基础知识回顾
Sep 10 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中操作Excel实例代码
2010/04/29 PHP
php curl常见错误:SSL错误、bool(false)
2011/12/28 PHP
thinkphp学习笔记之多表查询
2014/07/28 PHP
jquery实现每个数字上都带进度条的幻灯片
2013/02/20 Javascript
JQuery判断radio(单选框)是否选中和获取选中值方法总结
2015/04/15 Javascript
jquery判断单选按钮radio是否选中的方法
2015/05/05 Javascript
介绍JavaScript中Math.abs()方法的使用
2015/06/14 Javascript
jQuery实现平滑滚动页面到指定锚点链接的方法
2015/07/15 Javascript
jQuery prototype冲突的2种解决方法(附demo示例下载)
2016/01/21 Javascript
jQuery视差滚动效果网页实现方法经验总结
2016/09/29 Javascript
NodeJS收发GET和POST请求的示例代码
2017/08/25 NodeJs
js仿微信抢红包功能
2020/09/25 Javascript
微信小程序实现滚动消息通知
2018/02/02 Javascript
20行JS代码实现粘贴板复制功能
2018/02/06 Javascript
解决webpack+Vue引入iView找不到字体文件的问题
2018/09/28 Javascript
解决layui富文本编辑器图片上传无法回显的问题
2019/09/18 Javascript
[51:28]EG vs Mineski 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/16 DOTA
Python的类实例属性访问规则探讨
2015/01/30 Python
对于Python中线程问题的简单讲解
2015/04/03 Python
python使用matplotlib画柱状图、散点图
2019/03/18 Python
基于sklearn实现Bagging算法(python)
2019/07/11 Python
python 用所有标点符号分隔句子的示例
2019/07/15 Python
Python DataFrame一列拆成多列以及一行拆成多行
2019/08/06 Python
基于python调用psutil模块过程解析
2019/12/20 Python
python super用法及原理详解
2020/01/20 Python
css3使网页、图片变成灰色兼容大多数浏览器
2014/07/02 HTML / CSS
HTML5进阶段内联标签汇总(小篇)
2016/07/13 HTML / CSS
html5借用repeating-linear-gradient实现一把刻度尺(ruler)
2019/09/09 HTML / CSS
PHP如何防止SQL注入
2014/05/03 面试题
.NET初级开发工程师面试题
2014/04/18 面试题
计算机专业个人简短的自我评价
2013/10/23 职场文书
工作建议书范文
2014/05/13 职场文书
财务会计实训报告
2014/11/05 职场文书
幼儿园2014年度工作总结
2014/11/10 职场文书
那些美到让人窒息的诗句,值得你收藏!
2019/08/20 职场文书
在js中修改html body的样式
2021/11/11 Javascript