分享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类
Jul 15 PHP
PHP统计目录下的文件总数及代码行数(去除注释及空行)
Jan 17 PHP
windows下开发并编译PHP扩展的方法
Mar 18 PHP
php数组函数序列之in_array() - 查找数组中是否存在指定值
Nov 07 PHP
PHP排序算法的复习和总结
Feb 15 PHP
PHP设计模式之调解者模式的深入解析
Jun 13 PHP
php通过字符串调用函数示例
Mar 02 PHP
Thinkphp搭建包括JS多语言的多语言项目实现方法
Nov 24 PHP
PHP模块化安装教程
Jun 01 PHP
laravel 5.1下php artisan migrate的使用注意事项总结
Jun 07 PHP
PHP FileSystem 文件系统常用api整理总结
Jul 12 PHP
Laravel框架Eloquent ORM修改数据操作示例
Dec 03 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
解决FastCGI 进程超过了配置的活动超时时限的问题
2013/07/03 PHP
PHP的关于变量和日期处理的一些面试题目整理
2015/08/10 PHP
CodeIgniter视图使用注意事项
2016/01/20 PHP
thinkPHP2.1自定义标签库的导入方法详解
2016/07/20 PHP
php 调用百度sms来发送短信的实现示例
2018/11/02 PHP
在JavaScript中遭遇级联表达式陷阱
2007/03/08 Javascript
测试你的JS的掌握程度的代码
2009/12/09 Javascript
js中回调函数的学习笔记
2014/07/31 Javascript
JavaScript判断数组是否包含指定元素的方法
2015/07/01 Javascript
JS实现完全语义化的网页选项卡效果代码
2015/09/15 Javascript
JavaScript函数的调用以及参数传递
2015/10/21 Javascript
js类式继承与原型式继承详解
2016/04/07 Javascript
Javascript 实现微信分享(QQ、朋友圈、分享给朋友)
2016/10/21 Javascript
requirejs按需加载angularjs文件实例
2017/06/08 Javascript
Vue 项目代理设置的优化
2018/04/17 Javascript
浅析Vue中拆分视图层代码的5点建议
2019/08/15 Javascript
Vue.js仿Select下拉框效果
2020/02/18 Javascript
JavaScript实现随机点名小程序
2020/10/29 Javascript
Scrapy框架基本命令与settings.py设置
2020/02/06 Python
Python hashlib模块的使用示例
2020/10/09 Python
python 多线程中join()的作用
2020/10/29 Python
CSS3 calc()会计算属性详解
2018/02/27 HTML / CSS
美国学校用品、教室和教学商店:Discount School Supply
2018/04/04 全球购物
FILA德国官方网站:来自意大利的体育和街头服饰品牌
2019/07/19 全球购物
岗位职责定义及内容
2013/11/08 职场文书
偷看我的初中毕业鉴定
2014/01/29 职场文书
工伤赔偿协议书范本
2014/04/15 职场文书
中国梦演讲稿教师篇
2014/04/23 职场文书
法人授权委托书
2014/09/16 职场文书
婚前协议书范本两则
2014/10/16 职场文书
财产保全担保书
2015/01/20 职场文书
接收函格式
2015/01/30 职场文书
2016公司年会主持词
2015/07/01 职场文书
初中英语教师个人工作总结2015
2015/07/21 职场文书
Nginx下配置Https证书详细过程
2021/04/01 Servers
解决mysql模糊查询索引失效问题的几种方法
2021/06/18 MySQL