展开

站内通知     

    查看: 83|回复: 0
    收起左侧

    [PHP] 分享10段PHP常用代码包括解码压缩64位编码解析JSON等

    [复制链接]
  • TA的每日心情
    擦汗
    4 天前
  • 签到天数: 53 天

    连续签到: 2 天

    [LV.5]常住居民I

    866

    主题

    1067

    帖子

    1万

    积分

    管理员站长大人】 :Rank: 9Rank: 9Rank: 9

    威望1859
    贡献1580
    蓝币5254

    最佳新人活跃会员热心会员推广达人灌水之王突出贡献优秀版主荣誉管理论坛元老

    发表于 2018-12-1 03:58:18 | 显示全部楼层 |阅读模式

    马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

    您需要 登录 才可以下载或查看,没有帐号?立即注册

    x
    本文汇集PHP开发中经常用到的十段代码,包括Email、64位编码和解码、解压缩、64位编码、解析JSON等,希望对您有所帮助。
    1、使用PHP Mail函数发送Email
    1. $to = "viralpatel.net@gmail.com";
    2. $subject = "VIRALPATEL.net";
    3. $body = "Body of your message here you can use HTML too. e.g. ﹤br﹥ ﹤b﹥ Bold ﹤/b﹥";
    4. $headers = "From: Peter\r\n";
    5. $headers .= "Reply-To: info@yoursite.com\r\n";
    6. $headers .= "Return-Path: info@yoursite.com\r\n";
    7. $headers .= "X-Mailer: PHP5\n";
    8. $headers .= 'MIME-Version: 1.0' . "\n";
    9. $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    10. mail($to,$subject,$body,$headers);
    11. ?﹥
    复制代码


    2、PHP中的64位编码和解码
    1. function base64url_encode($plainText) {
    2. $base64 = base64_encode($plainText);
    3. $base64url = strtr($base64, '+/=', '-_,');
    4. return $base64url;
    5. }
    6. function base64url_decode($plainText) {
    7. $base64url = strtr($plainText, '-_,', '+/=');
    8. $base64 = base64_decode($base64url);
    9. return $base64;
    10. }
    复制代码


    3、获取远程IP地址
    1. function getRealIPAddr()
    2. {
    3. if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
    4. {
    5. $ip=$_SERVER['HTTP_CLIENT_IP'];
    6. }
    7. elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
    8. {
    9. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    10. }
    11. else
    12. {
    13. $ip=$_SERVER['REMOTE_ADDR'];
    14. }
    15. return $ip;
    16. }
    复制代码


    4、 日期格式化
    1. function checkDateFormat($date)
    2. {
    3. //match the format of the date
    4. if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
    5. {
    6. //check weather the date is valid of not
    7. if(checkdate($parts[2],$parts[3],$parts[1]))
    8. return true;
    9. else
    10. return false;
    11. }
    12. else
    13. return false;
    14. }
    复制代码


    5、验证Email
    1. $email = $_POST['email'];
    2. if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).
    3.    ([a-zA-Z0-9]{2,4})~",$email)) {
    4. echo 'This is a valid email.';
    5. } else{
    6. echo 'This is an invalid email.';
    7. }
    复制代码


    6、在PHP中轻松解析XML
    1. //this is a sample xml string
    2. $xml_string="﹤?xml version='1.0'?﹥
    3. ﹤moleculedb﹥
    4. ﹤molecule name='Benzine'﹥
    5. ﹤symbol﹥ben﹤/symbol﹥
    6. ﹤code﹥A﹤/code﹥
    7. ﹤/molecule﹥
    8. ﹤molecule name='Water'﹥
    9. ﹤symbol﹥h2o﹤/symbol﹥
    10. ﹤code﹥K﹤/code﹥
    11. ﹤/molecule﹥
    12. ﹤/moleculedb﹥";
    13. //load the xml string using simplexml function
    14. $xml = simplexml_load_string($xml_string);
    15. //loop through the each node of molecule
    16. foreach ($xml-﹥molecule as $record)
    17. {
    18. //attribute are accessted by
    19. echo $record['name'], ' ';
    20. //node are accessted by -﹥ operator
    21. echo $record-﹥symbol, ' ';
    22. echo $record-﹥code, '﹤br /﹥';
    23. }
    复制代码


    7、数据库连接
    1. ﹤?php
    2. if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
    3. $dbHost = "localhost"; //Location Of Database usually its localhost
    4. $dbUser = "xxxx"; //Database User Name
    5. $dbPass = "xxxx"; //Database Password
    6. $dbDatabase = "xxxx"; //Database Name
    7. $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or
    8.    die ("Error connecting to database.");
    9. mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
    10. # This function will send an imitation 404 page if the user
    11. # types in this files filename into the address bar.
    12. # only files connecting with in the same directory as this
    13. # file will be able to use it as well.
    14. function send_404()
    15. {
    16. header('HTTP/1.x 404 Not Found');
    17. print '﹤!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"﹥'."n".
    18. '﹤html﹥﹤head﹥'."n".
    19. '﹤title﹥404 Not Found﹤/title﹥'."n".
    20. '﹤/head﹥﹤body﹥'."n".
    21. '﹤h1﹥Not Found﹤/h1﹥'."n".
    22. '﹤p﹥The requested URL '.
    23. str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
    24. ' was not found on this server.﹤/p﹥'."n".
    25. '﹤/body﹥﹤/html﹥'."n";
    26. exit;
    27. }
    28. # In any file you want to connect to the database,
    29. # and in this case we will name this file db.php
    30. # just add this line of php code (without the pound sign):
    31. # include"db.php";
    32. ?﹥
    复制代码


    8、创建和解析JSON数据
    1. $json_data = array ('id'=﹥1,'name'=﹥"rolf",'country'=﹥'russia',
    2. "office"=﹥array("google","oracle"));
    3. echo json_encode($json_data);
    复制代码


    9、处理MySQL时间戳
    1. $query = "select UNIX_TIMESTAMP(date_field) as mydate
    2. from mytable where 1=1";
    3. $records = mysql_query($query) or die(mysql_error());
    4. while($row = mysql_fetch_array($records))
    5. {
    6. echo $row;
    7. }
    复制代码


    10、解压缩Zip文件
    1. ﹤?php
    2. function unzip($location,$newLocation){
    3. if(exec("unzip $location",$arr)){
    4. mkdir($newLocation);
    5. for($i = 1;$i﹤ count($arr);$i++){
    6. $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
    7. copy($location.'/'.$file,$newLocation.'/'.$file);
    8. unlink($location.'/'.$file);
    9. }
    10. return TRUE;
    11. }else{
    12. return FALSE;
    13. }
    14. }
    15. ?﹥
    16. //Use the code as following:
    17. ﹤?php
    18. include 'functions.php';
    19. if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
    20. echo 'Success!';
    21. else
    22. echo 'Error';
    23. ?﹥
    复制代码


    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;





    上一篇:避坑宝典:如何选择HTML5游戏开发引擎
    明天通班,妥妥的想杀人……

    kefu@aceanow.com

    蓝鸢梦想客服邮箱
    周一至周日:08:00-22:00

    蓝鸢微信扫一扫

    ©2015-2019. All rights reserved. ( 湘ICP备15008664号-1 )  Powered by Discuz! X3.4  技术支持:蓝鸢梦想
    快速回复 返回顶部 返回列表