PHP常用工具方法集...

PHP常用工具方法集,更新时间  2018-7-14

<?php
/*** 常用工具方法集* Author: zj*//**
工具总述
1.加密解密
2.生成随机字符串
3.获取文件扩展名(后缀)
4.文件大小格式化
5.替换标签字符
6.列出目录下的文件名
7.获取当前页面URL
8.让浏览器强制下载文件
9.字符串显示长度,超出使用...显示
10.获取客户端真实IP
11.防止SQL注入,判断是否有非法字符
12.页面提示与跳转
13.计算时长
14.写入日志文件
16.过滤特殊字符的函数  utf-8可用
17.统计文章字数和图片数
18.封装页面跳转函数
19.获取当前文件路径
20.获取当前文件目录
21.获取当前时间字符串
22.获取时间戳格式化时间字符串*///1.加密解密,$decrypt:0->加密,1->解密
function encryptDecrypt($key, $string, $decrypt){if($decrypt){$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");return $decrypted;}else{$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));return $encrypted;}
}//2.生成随机字符串
function generateRandomString($length = 10) {$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';$randomString = '';for ($i = 0; $i < $length; $i++) {$randomString .= $characters[rand(0, strlen($characters) - 1)];}return $randomString;
}//3.获取文件扩展名(后缀)
function getExtension($filename){$myext = substr($filename, strrpos($filename, '.')); //strrpos:最后位置return str_replace('.','',$myext);
}//4.文件大小格式化
function formatSize($size) {$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");if ($size == 0) {return('n/a');} else {//log(x,base):指定了可选的参数 base,log() 返回 logbasex ,否则 log() 返回参数 x 的自然对数;//pow(x,y):返回 x 的 y 次方的幂,如x=4,y=2,结果为16//重点获取$i:1024*1024*1024...级别对数return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);}
}//5.替换标签字符
/* 使用方法
$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
$replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br />');
echo stringParser($string,$replace_array);*/
function stringParser($string, $replacer){//str_replace对应替换多个字符$result = str_replace(array_keys($replacer), array_values($replacer), $string);return $result;
}//6.列出目录下的文件名,不列出文件夹名
function listDirFiles($DirPath){if($dir = opendir($DirPath)){while(($file = readdir($dir)) !== false){if(!is_dir($DirPath.$file)){echo "filename: $file<br />";}}}
}//7.获取当前页面URL
function curPageURLhost() {$pageURL = 'http';if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}$pageURL .= "://"; //拼接if ($_SERVER["SERVER_PORT"] != "80") {$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];} else {$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];}return $pageURL;
}//7-2.获取当前页面URL目录
function curPageURLaddrCatalog() {$pageURL = curPageURLhost();return $pageURL=substr($pageURL,0, strrpos($pageURL, '/')+1);
}//8.让浏览器强制下载文件-原文件名
function download($filepath){if ((isset($filepath))&&(file_exists($filepath))){header("Content-length: ".filesize($filepath));header('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="' . substr($filepath,strrpos($filepath, '/')+1, strlen($filepath)) . '"');readfile("$filepath");} else {echo "文件不存在!";}
}//8.让浏览器强制下载文件-文件重命名
function downloadScel($filepath, $filename){if ((isset($filepath))&&(file_exists($filepath))){header("Content-length: ".filesize($filepath));header('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="' . $filename.'.'.getExtension($filepath) . '"');readfile("$filepath");} else {echo "文件不存在!";}
}//9.字符串显示长度,超出使用...显示
/*Utf-8、gb2312都支持的汉字截取函数cut_str(字符串, 截取长度, 开始长度, 编码);编码默认为 utf-8开始长度默认为 0显示不能超过多少字符,超出的长度用…表示
*/
function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){if($code == 'UTF-8'){$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";preg_match_all($pa, $string, $t_string);if(count($t_string[0]) - $start > $sublen){return join('', array_slice($t_string[0], $start, $sublen))."...";}return join('', array_slice($t_string[0], $start, $sublen));}else{$start = $start*2;$sublen = $sublen*2;$strlen = strlen($string);$tmpstr = '';for($i=0; $i<$strlen; $i++){if($i>=$start && $i<($start+$sublen)){if(ord(substr($string, $i, 1))>129){$tmpstr.= substr($string, $i, 2);}else{$tmpstr.= substr($string, $i, 1);}}if(ord(substr($string, $i, 1))>129){$i++;}}if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";return $tmpstr;}
}//10.获取客户端真实IP
function getIp() {if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))$ip = getenv("HTTP_CLIENT_IP");elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))$ip = getenv("HTTP_X_FORWARDED_FOR");elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))$ip = getenv("REMOTE_ADDR");elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))$ip = $_SERVER['REMOTE_ADDR'];else$ip = "unknown";return ($ip);
}//11.防止SQL注入,判断是否有非法字符
function injCheck($sql_str) {$check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);if ($check) {echo '非法字符!!';exit;} else {return $sql_str;}
}//12.页面提示与跳转
function message($msgTitle,$message,$jumpUrl){$str = '<!DOCTYPE HTML>';$str .= '<html>';$str .= '<head>';$str .= '<meta charset="utf-8">';$str .= '<title>页面提示</title>';$str .= '<style type="text/css">';$str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:14px/18px Tahoma, Arial,  sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}';$str .= '</style>';$str .= '</head>';$str .= '<body>';$str .= '<div>';$str .= '<h3>'.$msgTitle.'</h3>';$str .= '<div>';$str .= '<h4>'.$message.'</h4>';$str .= '<p>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="'.$jumpUrl.'">这里</a> 跳转</p>';$str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>";$str .= '</div>';$str .= '</div>';$str .= '</body>';$str .= '</html>';echo $str;
}//13.计算时长
function changeTimeType($seconds) {if ($seconds > 3600) {$hours = intval($seconds / 3600);$minutes = $seconds % 3600;$time = $hours . ":" . gmstrftime('%M:%S', $minutes);} else {$time = gmstrftime('%H:%M:%S', $seconds);}return $time;
}/*** 14.写入日志文件* @parm1	: 日志文件名称* @parm2	: 记录的信息*/
function logFile($filename, $msg){$str = "[".date("Y-m-d H:i:s",time())."] ".$msg . PHP_EOL;file_put_contents($filename, $str,FILE_APPEND);
}//16.过滤特殊字符的函数  utf-8可用,过滤例如'&'中的'amp;'
function filterSpechars ($string){return preg_replace('/[\x00-\x1F\x7F-\x9F]/u', '', $string);
}/*** 17.统计文章字数和图片数* 参数:文章内容字符串* 返回:array*/
function countWords($str){$str = trim($str);$pattern = "/\[#img_[0-9]+_[a-z]*_[0-9]+_[a-zA-Z]*/i";#统计图片数preg_match_all($pattern, $str, $match_arrs);$picCount = count($match_arrs[0]);##增加新的图片记数方式preg_match_all('/<img /i',$str,$match_arrs);$picCount = $picCount + count($match_arrs[0]);#统计字数$str = preg_replace($pattern, "", $str);$str = preg_replace("/<img([^>].+)>/iU","", $str);    ##去掉图片标签$str = str_replace(' ','', $str);               ##去掉空格$wordCount = mb_strwidth(trim(strip_tags($str)));return array('wordCount'=>$wordCount,'picCount'=>$picCount,);
}/** 18.封装页面跳转函数* @param $url 目标地址* @param $info 提示信息* @param $sec 等待时间* return void
*/
function jump($url,$info=null,$sec=3)
{if(is_null($info)){header("Location:$url");}else{// header("Refersh:$sec;URL=$url");echo"<meta http-equiv=\"refresh\" content=".$sec.";URL=".$url.">";echo $info;}die(); //结束当前脚本运行
}/** 19.获取当前文件路径* return path
*/
function getThisPath()
{return __FILE__;
}/** 20.获取当前文件目录* 等价方法:getcwd();* return path
*/
function getThisCatalog()
{return __DIR__.'\\';
}/** 21.获取当前时间字符串* @param 可选参数,格式化* return date
*/
function getNowDateTime($format='Y-m-d H:i:s')
{return date($format);
}/** 22.获取时间戳格式化时间字符串* @param 时间戳* @param 可选参数,格式化* return date
*/
function getFormatDateTime($timestamp, $format='Y-m-d H:i:s')
{return date($format, $timestamp);
}

 

 

 

持续更新中...

 

 

 

 

 

转载于:https://www.cnblogs.com/qq1995/p/10359009.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/279873.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一题多解 面试题

最近在其他论坛上看到几个网友的面试题&#xff0c;这些天&#xff0c;QQ群内的人都在讨论怎么解答才最简单&#xff0c;下面列出题目&#xff1a; 文件a&#xff1a; 文件b: a b c a b c b c a b c a c b a …

什么是Google On.Here,以及如何设置?

Google Wi-Fi is similar to other mesh Wi-Fi systems, but one big feature separates it from the pack: Google On.Here. Google Wi-Fi与其他网状Wi-Fi系统相似&#xff0c;但其中一个重要功能将其与众不同&#xff1a;Google On.Here。 发生什么了&#xff1f; (What Is O…

一张图看懂 SQL 的各种 join 用法

原文链接https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins 转载于:https://www.cnblogs.com/xuchao0506/p/10559951.html

1Python全栈之路系列Web框架介绍

Python全栈之路系列之Web框架介绍 所有的语言Web框架本质其实就是起一个socket服务端,监听一个端口,然后运行起来 Web框架包含两部分,一部分是socket,另外一部分是业务的逻辑处理,根据请求的不同做不同的处理 Python的Web框架分成了两类, 即包含socket也包含业务逻辑处理的(tor…

『 再看.NET7』数值类型

在C#中&#xff0c;有int16&#xff0c;用short来定义&#xff1b;有int32&#xff0c;用int定义&#xff1b;用int64&#xff0c;用long来定义。在.NET7中&#xff0c;添加了int128&#xff0c;和unint128&#xff0c;位数更大的整型。var i16 short.MaxValue; Console.Write…

获取帮助命令

whatis 基于数据库的查找,查找内容比较慢 优点&#xff1a;查找速度快 缺点&#xff1a;没有实时性 [rootlocalhost ~]# whatis ls ls (1) - list directory contents ls (1p) - list directory contents 数据库文件 Centos6:/…

笔记本电脑升级固态硬盘好吗_如何升级笔记本电脑硬盘

笔记本电脑升级固态硬盘好吗Upgrading your laptop’s hard drive is a great way to get some extra life out of an old machine (or resurrect a dead one). Read on as we walk you through the prep work, the installation, and the followup. 升级笔记本电脑的硬盘驱动器…

购物单

小明刚刚找到工作&#xff0c;老板人很好&#xff0c;只是老板夫人很爱购物。老板忙的时候经常让小明帮忙到商场代为购物。小明很厌烦&#xff0c;但又不好推辞。 这不&#xff0c;XX大促销又来了&#xff01;老板夫人开出了长长的购物单&#xff0c;都是有打折优惠的。 …

Seay源代码审计系统

这是一款基于C#语言开发的一款针对PHP代码安全性审计的系统&#xff0c;主要运行于Windows系统上。这款软件能够发现SQL注入、代码执行、命令执行、文件包含、文件上传、绕过转义防护、拒绝服务、XSS跨站、信息泄露、任意URL跳转等漏洞。 下载链接 https://pan.baidu.com/s/1V…

dotnet 世界猜测 随机数的小测试

这是一个半技术向的博客&#xff0c;主题来源于我读过的某本书的片段&#xff0c;这是一个稍稍有些前置知识的故事&#xff0c;主题的大概内容就是假定世界存在某个规则序列&#xff0c;通过一代代的探索&#xff0c;可以获取到此序列的内容。本文将模拟此情形&#xff0c;写一…

python 批量修改密码

下午闲来无事&#xff0c;就搞个批量密码修改工具玩玩... #!/usr/bin/env python import paramiko import time ip_list(ip1,ip2) log_fileopen(mpwdok.log,w) log_file1open(mpwderr.log,w) for ip in ip_list: try: s paramiko.Transport((ip, 22)) s.c…

如何在Android Wear上节省电池寿命

If you’re rocking Android on your wrist, there’s a chance you’ve learned to rely on its convenience pretty heavily. And if you’re in that position, then you probably also know how annoying it can be if your watch runs out of juice in the middle of the …

css3 伪类选择器

1.target&#xff1a;表示当前的url片段的元素类型&#xff0c;这个元素必须是E &#xff08;作用类似于选项卡&#xff09; 2.&#xff1a;&#xff1a;before{content&#xff1a;“要添加的内容”} 添加到......之前 3.rgb&#xff08;&#xff09; 颜色 4.rgba&#xf…

城市统计【BFS】

题目大意&#xff1a; 中山市的地图是一个n*n的矩阵&#xff0c;其中标号为1的表示商业区&#xff0c;标号为0的表示居民区。为了考察市内居民区与商业区的距离&#xff0c;并对此作出评估&#xff0c;市长希望你能够编写一个程序完成这一任务。  居民区i到商业区的距离指的是…

使用 DataAnnotations(数据注解)实现通用模型数据校验

.net 跨平台参数校验的意义在实际项目开发中&#xff0c;无论任何方式、任何规模的开发模式&#xff0c;项目中都离不开对接入数据模型参数的合法性校验&#xff0c;目前普片的开发模式基本是前后端分离&#xff0c;当用户在前端页面中输入一些表单数据时&#xff0c;点击提交按…

网线的做法 及 POE的介绍

网线的做法 以太网线采用差分方式传输。所谓差分方式传输&#xff0c;就是发送端在两条信号线上传输幅值相等相位相反的电信号&#xff0c;接收端对接受的两条线信号作减法运算&#xff0c;这样获得幅值翻倍的信号。其抗干扰的原理是&#xff1a;假如两条信号线都受到了同样&am…

unity 使用tile_如何使用Tile从网上查找电话

unity 使用tileTile is a fantastic little gadget that can help you find your lost keys or wallet. However, it can also locate and ring your phone, even if you never buy a single physical Tile. Here’s how to find your lost phone using the Tile app on the we…

你与一份好简历之间的距离

阅读本文大概需要 2.7 分钟。每年年初都是企业的招聘旺季&#xff0c;对应的三四月份绝对跳槽、找工作的好时机&#xff0c;业内经常称呼这两个月为金三银四。实力雄厚的人&#xff0c;那个月找工作问题都不大&#xff0c;但是也会尽量挑选个好时机&#xff0c;能有更多的选择。…

Python 循环删除指定文件夹下所有的.longtian类型文件

# -*- coding: utf-8 -*-import os#遍历文件夹删除文件 def traversing_dir(rootDir):#遍历根目录for root,dirs,files in os.walk(rootDir):for file in files:#文件后缀名extFileos.path.splitext(file)[1]if extFile".longtian":os.remove(os.path.join(root,file…

《ASP.NET Core 6框架揭秘实例》演示[35]:利用Session保留语境

客户端和服务器基于HTTP的消息交换就好比两个完全没有记忆能力的人在交流&#xff0c;每次单一的HTTP事务体现为一次“一问一答”的对话。单一的对话毫无意义&#xff0c;在在同一语境下针对某个主题进行的多次对话才会有结果。会话的目的就是在同一个客户端和服务器之间建立两…