工做中常常用php操做文件,所以把經常使用文件操做整理出來:php
1 class hylaz_file{ 2 /** 3 * Read file 4 * @param string $pathname 5 * @return string content 6 */ 7 public static function read_file($pathname){ 8 return @file_get_contents($pathname); 9 } 10 /** 11 * Write File 12 * @param string $pathname 文件名稱 13 * @param string $data 寫入到文件的數據 14 * @param string $md 打開文件模式 15 * @return int bool 16 */ 17 public static function write_file($pathname,$data,$md='wb'){ 18 if(!$fp=fopen($pathname,$mode)) 19 return false; 20 flock($fp,LOCK_EX); 21 for($result=$written=0,$length=strlen($data),$written<$length;$written+=$result){ 22 if(($result=fwrite($fp,substr($data,$written)))===FALSE){ 23 break; 24 } 25 } 26 flock($fp, LOCK_UN); 27 fclose($fp); 28 return is_int($result); 29 } 30 /** 31 * 獲取文件信息 32 * @param string path of file 33 * @param array array or comma separated string of information returned 34 * @return array 35 */ 36 public static function file_info($file,$return_value=array('name', 'server_path', 'size', 'date')){ 37 if(!file_exists($file)){ 38 return false; 39 } 40 if(is_string($return_value)){ 41 $return_value=explode(",",$return_value); 42 } 43 foreach($return_value as $key){ 44 switch ($key){ 45 case "name": 46 $fileinfo['name']=basename($path); 47 break; 48 case "server_path": 49 $fileinfo['server_path']=$file; 50 break; 51 case 'date': 52 $fileinfo['date']=filemtime($file); 53 break; 54 case 'size': 55 $fileinfo['size']=filesize($file); 56 break; 57 case 'readable': 58 $fileinfo['readable']=is_readable($file); 59 break; 60 case 'writable': 61 $fileinfo['writable']=is_writable($file); 62 break; 63 case 'executable': 64 $fileinfo['executable']=is_executable($file); 65 break; 66 case 'fileperms': 67 $fileinfo['fileperms']=fileperms($file); 68 break; 69 70 71 } 72 } 73 return $fileinfo; 74 } 75 /** 76 * 得到八進制的權限位 77 * @param string $perms 78 * @return string 79 */ 80 public static function octal_permissions($perms){ 81 return substr(sprintf("%o",$perms), -3); 82 } 83 }