分享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生成静态HTML速度快类库
Mar 18 PHP
php实现的简单压缩英文字符串的代码
Apr 24 PHP
php mysql索引问题
Jun 07 PHP
PHP与MySQL开发的8个技巧小结
Dec 17 PHP
浅谈使用 PHP 进行手机 APP 开发(API 接口开发)
Aug 11 PHP
PHP实现绘制3D扇形统计图及图片缩放实例
Oct 01 PHP
从性能方面考虑PHP下载远程文件的3种方法
Dec 29 PHP
PHP实现文件上传与下载实例与总结
Mar 13 PHP
php版微信自动登录并获取昵称的方法
Sep 23 PHP
掌握PHP垃圾回收机制详解
Mar 13 PHP
php下的原生ajax请求用法实例分析
Feb 28 PHP
laravel入门知识点整理
Sep 15 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与javascript的两种交互方式
2006/10/09 PHP
php excel reader读取excel内容存入数据库实现代码
2012/12/06 PHP
做了CDN获取用户真实IP的函数代码(PHP与Asp设置方式)
2013/04/13 PHP
PHP入门教程之数学运算技巧总结
2016/09/11 PHP
PHP对象、模式与实践之高级特性分析
2016/12/08 PHP
PHP将字符串首字母大小写转换的实例
2017/01/21 PHP
js的with语句使用方法
2007/09/21 Javascript
JavaScript加密解密7种方法总结分析
2007/10/07 Javascript
asp批量修改记录的代码
2008/06/25 Javascript
Span元素的width属性无效果原因及解决方案
2010/01/15 Javascript
javascript判断css3动画结束 css3动画结束的回调函数
2015/03/10 Javascript
jQuery使用animate创建动画用法实例
2015/08/07 Javascript
js验证真实姓名与身份证号是否匹配
2015/10/13 Javascript
Bootstrap表单控件使用方法详解
2017/01/11 Javascript
jQuery为某个div加入行样式
2017/06/09 jQuery
Vue Cli与BootStrap结合实现表格分页功能
2017/08/18 Javascript
详解Vue之父子组件传值
2019/04/01 Javascript
JavaScript中将值转换为字符串的五种方法总结
2019/06/06 Javascript
详解JavaScript自定义函数
2020/07/29 Javascript
vue print.js打印支持Echarts图表操作
2020/11/13 Javascript
python使用WMI检测windows系统信息、硬盘信息、网卡信息的方法
2015/05/15 Python
python抽象基类用法实例分析
2015/06/04 Python
Python简单读取json文件功能示例
2017/11/30 Python
Python3实现发送QQ邮件功能(附件)
2020/12/23 Python
Python绘制频率分布直方图的示例
2019/07/08 Python
Python中print函数简单使用总结
2019/08/05 Python
Python json解析库jsonpath原理及使用示例
2020/11/25 Python
文史专业毕业生自荐信
2013/11/17 职场文书
办公室前台的岗位职责
2013/12/20 职场文书
法人代表委托书
2014/04/04 职场文书
公司委托书格式范文
2014/10/09 职场文书
稽核岗位职责
2015/02/10 职场文书
新员工试用期自我评价
2015/03/10 职场文书
研讨会通知
2015/04/27 职场文书
幼儿园小班开学寄语
2015/05/27 职场文书
Java多条件判断场景中规则执行器的设计
2021/06/26 Java/Android