侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

分享10段PHP常用代码

php  /  管理员 发布于 7年前   181

本文汇集PHP开发中经常用到的十段代码,包括Email、64位编码和解码、解压缩、64位编码、解析JSON等,希望对您有所帮助。

1、使用PHP Mail函数发送Email

$to = "[email protected]"; $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: [email protected]\r\n"; $headers .= "Return-Path: [email protected]\r\n"; $headers .= "X-Mailer: PHP5\n"; $headers .= 'MIME-Version: 1.0' . "\n"; $headers .= 'Content-type: text/html; ' . "\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 dateif (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)){//check weather the date is valid of notif(checkdate($parts[2],$parts[3],$parts[1]))return true;elsereturn false;}elsereturn 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' symbolben/symbol codeA/code /molecule molecule name='Water' symbolh2o/symbol codeK/code /molecule/moleculedb";//load the xml string using simplexml function$xml = simplexml_load_string($xml_string);//loop through the each node of moleculeforeach ($xml-molecule as $record){ //attribute are accessted by echo $record['name'], ' '; //node are accessted by - operator echo $record-symbol, ' '; echo $record-code, 'br /';}

7、数据库连接

?phpif(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". 'htmlhead'."n". 'title404 Not Found/title'."n". '/headbody'."n". 'h1Not Found/h1'."n". 'pThe 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:?phpinclude '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 '
';
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 '
';$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.'
Objective-C '.$num;echo $str1;echo '
';$str2 = "$str
Objective-C $num"; //另一中简便的写法echo $str2;

您可能感兴趣的文章:

  • Thinkphp无限级分类代码
  • 2款PHP无限级分类实例代码
  • PHP防止刷新重复提交页面的示例代码
  • php抓取并保存网站图片的实现代码
  • PHP文件缓存类实现代码
  • 一个简单至极的PHP缓存类代码
  • php防止网站被攻击的应急代码
  • php限制文件下载速度的代码
  • PHP代码判断设备是手机还是平板电脑(两种方法)
  • jQuery+Ajax+PHP“喜欢”评级功能实现代码
  • PHP抽奖算法程序代码分享
  • php视频拍照上传头像功能实现代码分享
  • PHP常用的小程序代码段


  • 上一条:
    php验证码生成代码
    下一条:
    php+mysql实现无限级分类
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客