i漂泊

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 3735|回复: 0

超实用PHP函数总结整理

[复制链接]
TA的礼物信息
  • 收到:0
  • 送出:2
发表于 2017-2-27 12:49:25 | 显示全部楼层 |阅读模式
1、PHP加密解密

PHP加密和解密函数可以用来加密一些有用的字符串存放在数据库里,并且通过可逆解密字符串,该函数使用了base64和MD5加密和解密。
  1. function encryptDecrypt($key, $string, $decrypt){
  2.     if($decrypt){
  3.         $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
  4.         return $decrypted;
  5.     }else{
  6.         $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
  7.         return $encrypted;
  8.     }
  9. }
复制代码
使用方法如下:
  1. //以下是将字符串“Helloweba欢迎您”分别加密和解密
  2. //加密:
  3. echo encryptDecrypt('password', 'Helloweba欢迎您',0);
  4. //解密:
  5. echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);
复制代码
2、PHP生成随机字符串

当我们需要生成一个随机名字,临时密码等字符串时可以用到下面的函数:
  1. function generateRandomString($length = 10) {
  2.     $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  3.     $randomString = '';
  4.     for ($i = 0; $i < $length; $i++) {
  5.         $randomString .= $characters[rand(0, strlen($characters) - 1)];
  6.     }
  7.     return $randomString;
  8. }
复制代码
使用方法如下:
  1. echo generateRandomString(20);
复制代码
3、PHP获取文件扩展名(后缀)

以下函数可以快速获取文件的扩展名即后缀。
  1. function getExtension($filename){
  2.   $myext = substr($filename, strrpos($filename, '.'));
  3.   return str_replace('.','',$myext);
  4. }
复制代码
使用方法如下:
  1. $filename = '我的文档.doc';
  2. echo getExtension($filename);
复制代码
4、PHP获取文件大小并格式化

以下使用的函数可以获取文件的大小,并且转换成便于阅读的KB,MB等格式。
  1. function formatSize($size) {
  2.     $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
  3.     if ($size == 0) {  
  4.         return('n/a');  
  5.     } else {
  6.       return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);  
  7.     }
  8. }
复制代码
使用方法如下:
  1. $thefile = filesize('test_file.mp3');
  2. echo formatSize($thefile);
复制代码
5、PHP替换标签字符

有时我们需要将字符串、模板标签替换成指定的内容,可以用到下面的函数:
  1. function stringParser($string,$replacer){
  2.     $result = str_replace(array_keys($replacer), array_values($replacer),$string);
  3.     return $result;
  4. }
复制代码
使用方法如下:
  1. $string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
  2. $replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br />');

  3. echo stringParser($string,$replace_array);
复制代码
6、PHP列出目录下的文件名

如果你想列出目录下的所有文件,使用以下代码即可:
  1. function listDirFiles($DirPath){
  2.     if($dir = opendir($DirPath)){
  3.          while(($file = readdir($dir))!== false){
  4.                 if(!is_dir($DirPath.$file))
  5.                 {
  6.                     echo "filename: $file<br />";
  7.                 }
  8.          }
  9.     }
  10. }
复制代码
使用方法如下:
  1. listDirFiles('home/some_folder/');
复制代码
7、PHP获取当前页面URL

以下函数可以获取当前页面的URL,不管是http还是https。
  1. function curPageURL() {
  2.     $pageURL = 'http';
  3.     if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}
  4.     $pageURL .= "://";
  5.     if ($_SERVER["SERVER_PORT"] != "80") {
  6.         $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  7.     } else {
  8.         $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  9.     }
  10.     return $pageURL;
  11. }
复制代码
使用方法如下:
  1. echo curPageURL();
复制代码
8、PHP强制下载文件

有时我们不想让浏览器直接打开文件,如PDF文件,而是要直接下载文件,那么以下函数可以强制下载文件,函数中使用了application/octet-stream头类型。
  1. function download($filename){
  2.     if ((isset($filename))&&(file_exists($filename))){
  3.        header("Content-length: ".filesize($filename));
  4.        header('Content-Type: application/octet-stream');
  5.        header('Content-Disposition: attachment; filename="' . $filename . '"');
  6.        readfile("$filename");
  7.     } else {
  8.        echo "Looks like file does not exist!";
  9.     }
  10. }
复制代码
使用方法如下:
  1. download('/down/test_45f73e852.zip');
复制代码
9、PHP截取字符串长度

我们经常会遇到需要截取字符串(含中文汉字)长度的情况,比如标题显示不能超过多少字符,超出的长度用…表示,以下函数可以满足你的需求。
  1. /*
  2. Utf-8、gb2312都支持的汉字截取函数
  3. cut_str(字符串, 截取长度, 开始长度, 编码);
  4. 编码默认为 utf-8
  5. 开始长度默认为 0
  6. */
  7. function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){
  8.     if($code == 'UTF-8'){
  9.         $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]/";
  10.         preg_match_all($pa, $string, $t_string);

  11.         if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
  12.         return join('', array_slice($t_string[0], $start, $sublen));
  13.     }else{
  14.         $start = $start*2;
  15.         $sublen = $sublen*2;
  16.         $strlen = strlen($string);
  17.         $tmpstr = '';

  18.         for($i=0; $i<$strlen; $i++){
  19.             if($i>=$start && $i<($start+$sublen)){
  20.                 if(ord(substr($string, $i, 1))>129){
  21.                     $tmpstr.= substr($string, $i, 2);
  22.                 }else{
  23.                     $tmpstr.= substr($string, $i, 1);
  24.                 }
  25.             }
  26.             if(ord(substr($string, $i, 1))>129) $i++;
  27.         }
  28.         if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
  29.         return $tmpstr;
  30.     }
  31. }
复制代码
使用方法如下:
  1. $str = "jQuery插件实现的加载图片和页面效果";
  2. echo cutStr($str,16);
复制代码
10、PHP获取客户端真实IP

我们经常要用数据库记录用户的IP,以下代码可以获取客户端真实的IP:
  1. /获取用户真实IP
  2. function getIp() {
  3.     if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  4.         $ip = getenv("HTTP_CLIENT_IP");
  5.     else
  6.         if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
  7.             $ip = getenv("HTTP_X_FORWARDED_FOR");
  8.         else
  9.             if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  10.                 $ip = getenv("REMOTE_ADDR");
  11.             else
  12.                 if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  13.                     $ip = $_SERVER['REMOTE_ADDR'];
  14.                 else
  15.                     $ip = "unknown";
  16.     return ($ip);
  17. }
复制代码
使用方法如下:
  1. echo getIp();
复制代码
11、PHP防止SQL注入

我们在查询数据库时,出于安全考虑,需要过滤一些非法字符防止SQL恶意注入,请看一下函数:
  1. function injCheck($sql_str) {  
  2.     $check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);
  3.     if ($check) {
  4.         echo '非法字符!!';
  5.         exit;
  6.     } else {
  7.         return $sql_str;
  8.     }
  9. }
复制代码
使用方法如下:
  1. echo injCheck('1 or 1=1');
复制代码
12、PHP页面提示与跳转

我们在进行表单操作时,有时为了友好需要提示用户操作结果,并跳转到相关页面,请看以下函数:
  1. function message($msgTitle,$message,$jumpUrl){
  2.     $str = '<!DOCTYPE HTML>';
  3.     $str .= '<html>';
  4.     $str .= '<head>';
  5.     $str .= '<meta charset="utf-8">';
  6.     $str .= '<title>页面提示</title>';
  7.     $str .= '<style type="text/css">';
  8.     $str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/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}';
  9.     $str .= '</style>';
  10.     $str .= '</head>';
  11.     $str .= '<body>';
  12.     $str .= '<div>';
  13.     $str .= '<h3>'.$msgTitle.'</h3>';
  14.     $str .= '<div>';
  15.     $str .= '<h4>'.$message.'</h4>';
  16.     $str .= '<p>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="{$jumpUrl}">这里</a> 跳转</p>';
  17.     $str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>";
  18.     $str .= '</div>';
  19.     $str .= '</div>';
  20.     $str .= '</body>';
  21.     $str .= '</html>';
  22.     echo $str;
  23. }
复制代码
使用方法如下:
  1. message('操作提示','操作成功!','http://www.helloweba.com/');
复制代码
13、PHP计算时长

我们在处理时间时,需要计算当前时间距离某个时间点的时长,如计算客户端运行时长,通常用hh:mm:ss表示。
  1. function changeTimeType($seconds) {
  2.     if ($seconds > 3600) {
  3.         $hours = intval($seconds / 3600);
  4.         $minutes = $seconds % 3600;
  5.         $time = $hours . ":" . gmstrftime('%M:%S', $minutes);
  6.     } else {
  7.         $time = gmstrftime('%H:%M:%S', $seconds);
  8.     }
  9.     return $time;
  10. }
复制代码
使用方法如下:
  1. $seconds = 3712;
  2. echo changeTimeType($seconds);
复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|手机版|IPiaoBo Inc. ( 渝ICP备17002826号 )

GMT+8, 2025-5-7 11:03 , Processed in 0.114640 second(s), 43 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表