分享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 代码规范小结
Mar 08 PHP
PHP程序漏洞产生的原因分析与防范方法说明
Mar 06 PHP
腾讯CMEM的PHP扩展编译安装方法
Sep 25 PHP
php判断手机浏览还是web浏览,并执行相应的动作简单实例
Jul 28 PHP
PHP实现支持加盐的图片加密解密
Sep 09 PHP
php版微信公众平台开发之验证步骤实例详解
Sep 23 PHP
PHP-FPM运行状态的实时查看及监控详解
Nov 18 PHP
thinkphp自定义权限管理之名称判断方法
Apr 01 PHP
PHP仿qq空间或朋友圈发布动态、评论动态、回复评论、删除动态或评论的功能(上)
May 26 PHP
Laravel框架基于中间件实现禁止未登录用户访问页面功能示例
Jan 17 PHP
PHP设计模式之工厂模式(Factory Pattern)的讲解
Mar 21 PHP
PHP实现腾讯短网址生成api接口实例
Dec 08 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写的serv-u的web申请账号的程序
2006/10/09 PHP
比较strtr, str_replace和preg_replace三个函数的效率
2013/06/26 PHP
Yii2框架使用计划任务的方法
2016/05/25 PHP
php7安装yar扩展的方法详解
2017/08/03 PHP
PHP实现数据库的增删查改功能及完整代码
2018/04/18 PHP
php自定义排序uasort函数示例【二维数组按指定键值排序】
2019/06/19 PHP
jQuery队列控制方法详解queue()/dequeue()/clearQueue()
2010/12/02 Javascript
给事件响应函数传参数的四种方式小结
2013/12/05 Javascript
ff chrome和ie下全局动态定位的异同及全局高度的取法
2014/06/30 Javascript
js读取csv文件并使用json显示出来
2015/01/09 Javascript
jQuery焦点图轮播插件KinSlideshow用法分析
2016/06/08 Javascript
Vue 单文件中的数据传递示例
2017/03/21 Javascript
使用ef6创建oracle数据库的实体模型遇到的问题及解决方案
2017/11/09 Javascript
React组件refs的使用详解
2018/02/09 Javascript
vee-validate vue 2.0自定义表单验证的实例
2018/08/28 Javascript
vue实现可视化可拖放的自定义表单的示例代码
2019/03/20 Javascript
详解vue在项目中使用百度地图
2019/03/26 Javascript
Vue使用Proxy监听所有接口状态的方法实现
2019/06/07 Javascript
Vue如何使用混合Mixins和插件开发详解
2020/02/05 Javascript
python遍历文件夹并删除特定格式文件的示例
2014/03/05 Python
Python的消息队列包SnakeMQ使用初探
2016/06/29 Python
Ubuntu下创建虚拟独立的Python环境全过程
2017/02/10 Python
python删除某个字符
2018/03/19 Python
python flask中静态文件的管理方法
2018/03/20 Python
python 列表降维的实例讲解
2018/06/28 Python
如何使用Flask-Migrate拓展数据库表结构
2019/07/24 Python
Python numpy矩阵处理运算工具用法汇总
2020/07/13 Python
关于Python3的import问题(pycharm可以运行命令行import错误)
2020/11/18 Python
美国电力供应商店/电气批发商:USESI
2018/10/12 全球购物
捷克家具销售网站:SCONTO Nábytek
2020/01/02 全球购物
单位成立周年感言
2014/01/26 职场文书
汽车队司机先进事迹材料
2014/02/01 职场文书
管理失职检讨书
2015/05/05 职场文书
同意报考公务员证明
2015/06/17 职场文书
生活小常识广播稿
2015/08/19 职场文书
接收函
2019/04/22 职场文书