有用的函数-文件处理及其它

来源:互联网 发布:js 深度克隆 编辑:程序博客网 时间:2024/05/18 03:13

有用的函数-文件处理及其它

1.文件尺寸大小转换
  1. /** 
  2.     转换附件大小单位 
  3.     @param string $filesize 文件大小 kb 
  4. */ 
  5. function changeFileSize($filesize) 

  6.     if($filesize >= 1073741824) 
  7.     { 
  8.         $filesize = round($filesize / 1073741824  ,2) . ' Gb'; 
  9.     } elseif($filesize >= 1048576) 
  10.     { 
  11.         $filesize = round($filesize / 1048576 ,2) . ' Mb'; 
  12.     } elseif($filesize >= 1024) 
  13.     { 
  14.         $filesize = round($filesize / 1024, 2) . ' Kb'; 
  15.     } else 
  16.     { 
  17.         $filesize = $filesize . ' Bytes'; 
  18.     } 
  19.     return $filesize; 
  20. }
复制代码
2.按比例改变图片大小
  1. /** 
  2.     按照比例改变图片大小(非生成缩略图) 
  3.     @param string $img 图片路径 
  4.     @param int $max_w 最大缩放宽 
  5.     @param int $max_h 最大缩放高 
  6. */ 
  7. function chImageSize ($img,$max_w,$max_h) 

  8.     $size = @getimagesize($img); 
  9.         $w = $size[0]; 
  10.         $h     =    $size[1]; 
  11.     //计算缩放比例 
  12.     @$w_ratio = $max_w / $w; 
  13.     @$h_ratio =    $max_h / $h; 
  14.     //决定处理后的图片宽和高 
  15.     if( ($w <= $max_w) && ($h <= $max_h) ) 
  16.     { 
  17.         $tn['w'] = $w; 
  18.         $tn['h'] = $h; 
  19.     } 
  20.     else if(($w_ratio * $h) < $max_h) 
  21.     { 
  22.         $tn['h'] = ceil($w_ratio * $h); 
  23.         $tn['w'] = $max_w; 
  24.     } 
  25.     else 
  26.     { 
  27.         $tn['w'] = ceil($h_ratio * $w); 
  28.         $tn['h'] = $max_h; 
  29.     } 
  30.     $tn['rc_w'] = $w; 
  31.     $tn['rc_h'] = $h; 
  32.     return $tn ; 
  33. }
复制代码
3.创建多级目录
  1. function mk_dir( $target ) { 
  2.     $target = str_replace( '//', '/', $target ); 
  3.     if ( file_exists( $target ) ) 
  4.         return @is_dir( $target ); 
  5.     if ( @mkdir( $target ) ) { 
  6.         $stat = @stat( dirname( $target ) ); 
  7.         $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits. 
  8.         @chmod( $target, $dir_perms ); 
  9.         return true; 
  10.     } elseif ( is_dir( dirname( $target ) ) ) { 
  11.             return false; 
  12.     } 
  13.     // If the above failed, attempt to create the parent node, then try again. 
  14.     if ( ( $target != '/' ) && ( mk_dir( dirname( $target ) ) ) ) 
  15.         return mk_dir( $target ); 
  16.     return false; 
  17. }
复制代码
4.判断是绝对路径还是相对路径
  1. function path_is_absolute( $path ) { 
  2.     // this is definitive if true but fails if $path does not exist or contains a symbolic link 
  3.     if ( realpath($path) == $path ) 
  4.         return true; 
  5.     if ( strlen($path) == 0 || $path{0} == '.' ) 
  6.         return false; 
  7.     // windows allows absolute paths like this 
  8.     if ( preg_match('#^[a-zA-Z]:\\\\#', $path) ) 
  9.         return true; 
  10.     // a path starting with / or \ is absolute; anything else is relative 
  11.     return (bool) preg_match('#^[/\\\\]#', $path); 
  12. }
复制代码
5.得到文件类型
  1. function get_filetype($filename) { 
  2.     // Accepted MIME types are set here as PCRE unless provided. 
  3.     $mimes = array( 
  4.         'jpg|jpeg|jpe' => 'image/jpeg', 
  5.         'gif' => 'image/gif', 
  6.         'png' => 'image/png', 
  7.         'bmp' => 'image/bmp', 
  8.         'tif|tiff' => 'image/tiff', 
  9.         'ico' => 'image/x-icon', 
  10.         'asf|asx|wax|wmv|wmx' => 'video/asf', 
  11.         'avi' => 'video/avi', 
  12.         'divx' => 'video/divx', 
  13.         'mov|qt' => 'video/quicktime', 
  14.         'mpeg|mpg|mpe|mp4' => 'video/mpeg', 
  15.         'txt|c|cc|h' => 'text/plain', 
  16.         'rtx' => 'text/richtext', 
  17.         'css' => 'text/css', 
  18.         'htm|html' => 'text/html', 
  19.         'mp3|m4a' => 'audio/mpeg', 
  20.         'ra|ram' => 'audio/x-realaudio', 
  21.         'wav' => 'audio/wav', 
  22.         'ogg' => 'audio/ogg', 
  23.         'mid|midi' => 'audio/midi', 
  24.         'wma' => 'audio/wma', 
  25.         'rtf' => 'application/rtf', 
  26.         'js' => 'application/javascript', 
  27.         'pdf' => 'application/pdf', 
  28.         'doc|docx' => 'application/msword', 
  29.         'pot|pps|ppt|pptx' => 'application/vnd.ms-powerpoint', 
  30.         'wri' => 'application/vnd.ms-write', 
  31.         'xla|xls|xlsx|xlt|xlw' => 'application/vnd.ms-excel', 
  32.         'mdb' => 'application/vnd.ms-access', 
  33.         'mpp' => 'application/vnd.ms-project', 
  34.         'swf' => 'application/x-shockwave-flash', 
  35.         'class' => 'application/java', 
  36.         'tar' => 'application/x-tar', 
  37.         'zip' => 'application/zip', 
  38.         'gz|gzip' => 'application/x-gzip', 
  39.         'exe' => 'application/x-msdownload', 
  40.         // openoffice formats 
  41.         'odt' => 'application/vnd.oasis.opendocument.text', 
  42.         'odp' => 'application/vnd.oasis.opendocument.presentation', 
  43.         'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 
  44.         'odg' => 'application/vnd.oasis.opendocument.graphics', 
  45.         'odc' => 'application/vnd.oasis.opendocument.chart', 
  46.         'odb' => 'application/vnd.oasis.opendocument.database', 
  47.         'odf' => 'application/vnd.oasis.opendocument.formula', 
  48.     ); 
  49.     $type = false; 
  50.     $ext = false; 
  51.     foreach ( $mimes as $ext_preg => $mime_match ) { 
  52.         $ext_preg = '!\.(' . $ext_preg . ')$!i'; 
  53.         if ( preg_match( $ext_preg, $filename, $ext_matches ) ) { 
  54.             $type = $mime_match; 
  55.             $ext = $ext_matches[1]; 
  56.             break; 
  57.         } 
  58.     } 
  59.     return compact( 'ext', 'type' ); 
  60. }
复制代码
6.遍历文件夹中文件
  1. function list_files( $folder = '', $levels = 100 ) { 
  2.     if( empty($folder) ) 
  3.         return false; 
  4.     if( ! $levels ) 
  5.         return false; 
  6.     $files = array(); 
  7.     if ( $dir = @opendir( $folder ) ) { 
  8.         while (($file = readdir( $dir ) ) !== false ) { 
  9.             if ( in_array($file, array('.', '..') ) ) 
  10.                 continue; 
  11.             if ( is_dir( $folder . '/' . $file ) ) { 
  12.                 $files2 = list_files( $folder . '/' . $file, $levels - 1); 
  13.                 if( $files2 ) 
  14.                     $files = array_merge($files, $files2 ); 
  15.                 else 
  16.                     $files[] = $folder . '/' . $file . '/'; 
  17.             } else { 
  18.                 $files[] = $folder . '/' . $file; 
  19.             } 
  20.         } 
  21.     } 
  22.     @closedir( $dir ); 
  23.     return $files; 
  24. }
复制代码
7.判断爬虫函数
  1. function isCrawler() {    
  2.      if(ini_get('browscap')) {    
  3.          $browser= get_browser(NULL, true);    
  4.          if($browser['crawler']) {    
  5.              return true;    
  6.          }    
  7.      } else if (isset($_SERVER['HTTP_USER_AGENT'])){    
  8.          $agent= $_SERVER['HTTP_USER_AGENT'];    
  9.          $crawlers= array(    
  10.              "/Googlebot/",    
  11.              "/Yahoo! Slurp;/",    
  12.              "/msnbot/",    
  13.              "/Mediapartners-Google/",    
  14.              "/Scooter/",    
  15.              "/Yahoo-MMCrawler/",    
  16.              "/FAST-WebCrawler/",    
  17.              "/Yahoo-MMCrawler/",    
  18.              "/Yahoo! Slurp/",    
  19.              "/FAST-WebCrawler/",    
  20.              "/FAST Enterprise Crawler/",    
  21.              "/grub-client-/",    
  22.              "/MSIECrawler/",    
  23.              "/NPBot/",    
  24.              "/NameProtect/i",    
  25.              "/ZyBorg/i",    
  26.              "/worio bot heritrix/i",    
  27.              "/Ask Jeeves/",    
  28.              "/libwww-perl/i",    
  29.              "/Gigabot/i",    
  30.              "/bot@bot.bot/i",    
  31.              "/SeznamBot/i",    
  32.          );    
  33.          foreach($crawlers as $c) {    
  34.              if(preg_match($c, $agent)) {    
  35.                  return true;    
  36.              }    
  37.          }    
  38.      }    
  39.      return false;    
  40. }
复制代码
8.判断远程文件是否存在
  1. php 
  2. /* 
  3.   函数:remote_file_exists 
  4.   功能:判断远程文件是否存在 
  5.   参数: $url_file -远程文件URL 
  6.   返回:存在返回true,不存在或者其他原因返回false 
  7. */ 
  8. function remote_file_exists($url_file){ 
  9.        //检测输入 
  10.        $url_file = trim($url_file); 
  11.        if (empty($url_file)) { return false; } 
  12.        $url_arr = parse_url($url_file); 
  13.        if (!is_array($url_arr) || empty($url_arr)){return false; } 
  14.        //获取请求数据 
  15.        $host = $url_arr['host']; 
  16.        $path = $url_arr['path'] ."?".$url_arr['query']; 
  17.        $port = isset($url_arr['port']) ?$url_arr['port'] : "80"; 
  18.        //连接服务器 
  19.        $fp = fsockopen($host, $port, $err_no, $err_str,30); 
  20.        if (!$fp){ return false; } 
  21.        //构造请求协议 
  22.        $request_str = "GET ".$path."HTTP/1.1\r\n"; 
  23.     $request_str .= "Host:".$host."\r\n"; 
  24.     $request_str .= "Connection:Close\r\n\r\n"; 
  25.        //发送请求 
  26.     fwrite($fp,$request_str); 
  27.        $first_header = fgets($fp, 1024); 
  28.     fclose($fp); 
  29.        //判断文件是否存在 
  30.        if (trim($first_header) == ""){ return false;} 
  31.        if (!preg_match("/200/", $first_header)){ 
  32.               return false; 
  33.        } 
  34.        return true; 
  35. }
复制代码
9.多重判断文件函数删除
  1. function delete_file($file) 

  2.     if (file_exists($file)) 
  3.     { 
  4.         $delete = chmod ($file, 0777); 
  5.         $delete = unlink($file); 
  6.         if(file_exists($file)) 
  7.         { 
  8.             $filesys = eregi_replace("/","\\",$file); 
  9.             $delete = system("del $filesys"); 
  10.             clearstatcache(); 
  11.             if(file_exists($file)) 
  12.             { 
  13.                 $delete = chmod ($file, 0777); 
  14.                 $delete = unlink($file); 
  15.                 $delete = system("del $filesys"); 
  16.             } 
  17.         } 
  18.         clearstatcache(); 
  19.         if(file_exists($file)) 
  20.         { 
  21.             return 'Delete Faile         :        <font color=\'#ff0000\'>'.$file.'</font><br>'; 
  22.         } 
  23.         else 
  24.         { 
  25.             return 'Delete Successs        :        <font color=\'#6699cc\'>'.$file.'</font><br>'; 
  26.         } 
  27.     } 
  28.     else 
  29.     { 
  30.         return 'Delete Successs        :        <font color=\'#6699cc\'>'.$file.'</font><br>'; 
  31.     } 
  32. }
复制代码

1.删除目录(含文件)
  1. function removeDir($dirName)
  2. {
  3.     $result = false;
  4.     if(! is_dir($dirName))
  5.     {
  6.         trigger_error('Invalid Parameter', E_USER_ERROR);
  7.     }
  8.     $handle = opendir($dirName);
  9.     while(($file = readdir($handle)) !== false)
  10.     {
  11.         if($file != '.' && $file != '..')
  12.         {
  13.             $dir = $dirName . DIRECTORY_SEPARATOR . $file;
  14.             is_dir($dir) ? removeDir($dir) : unlink($dir);
  15.         }
  16.     }
  17.     closedir($handle);
  18.     $result = rmdir($dirName) ? true : false;
  19.     return $result;
  20. }
复制代码
2.复制目录
  1. function copyDir($source, $destination)
  2. {
  3.     $result = true;
  4.     if(! is_dir($source))
  5.     {
  6.         trigger_error('Invalid Parameter', E_USER_ERROR);
  7.     }
  8.     if(! is_dir($destination))
  9.     {
  10.         if(! mkdir($destination, 0700))
  11.         {
  12.             trigger_error('Invalid Parameter', E_USER_ERROR);
  13.         }
  14.     }
  15.     $handle = opendir($source);
  16.     while(($file = readdir($handle)) !== false)
  17.     {
  18.         if($file != '.' && $file != '..')
  19.         {
  20.             $src = $source . DIRECTORY_SEPARATOR . $file;
  21.             $dtn = $destination . DIRECTORY_SEPARATOR . $file;
  22.             if(is_dir($src))
  23.             {
  24.                 copyDir($src, $dtn);
  25.             }
  26.             else
  27.             {
  28.                 if(! copy($src, $dtn))
  29.                 {
  30.                     $result = false;
  31.                     break;
  32.                 }
  33.             }
  34.         }
  35.     }
  36.     closedir($handle);
  37.     return $result;
  38. }
复制代码

3.图像文件判别函数
  1. function imageType($file){
  2.     
  3.     $fp        = fopen($file, "rb");
  4.     $data    = fread($fp,20);
  5.     fclose($fp);
  6.     
  7.     $sign    = substr($data,0,2);

  8.     switch ($sign) {
  9.         
  10.         case "\x42\x4d":
  11.             return "bmp";

  12.         break;
  13.         
  14.         case "\x47\x49":
  15.             if(substr($data,0,3) == "\x47\x49\x46")
  16.                 return "gif";
  17.         break;
  18.         case "\x89\x50":
  19.             if(substr($data,0,8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
  20.                 return "png";
  21.         break;
  22.         case "\xFF\xD8":
  23.             if(substr($data,0,4) == "\xFF\xD8\xFF\xE0" && substr($data,6,5) == "\x4A\x46\x49\x46\x00")
  24.                 return "jpg";
  25.         break;

  26.                 
  27.     }

  28.         return 'unknown';

  29. }
复制代码


原创粉丝点击