php常见的类库-文件操作类

时间:2024-09-25 08:36:50

工作中经常用php操作文件,因此把常用文件操作整理出来:

 class hylaz_file{
/**
* Read file
* @param string $pathname
* @return string content
*/
public static function read_file($pathname){
return @file_get_contents($pathname);
}
/**
* Write File
* @param string $pathname 文件名称
* @param string $data 写入到文件的数据
* @param string $md 打开文件模式
* @return int bool
*/
public static function write_file($pathname,$data,$md='wb'){
if(!$fp=fopen($pathname,$mode))
return false;
flock($fp,LOCK_EX);
for($result=$written=0,$length=strlen($data),$written<$length;$written+=$result){
if(($result=fwrite($fp,substr($data,$written)))===FALSE){
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
return is_int($result);
}
/**
* 获取文件信息
* @param string path of file
* @param array array or comma separated string of information returned
* @return array
*/
public static function file_info($file,$return_value=array('name', 'server_path', 'size', 'date')){
if(!file_exists($file)){
return false;
}
if(is_string($return_value)){
$return_value=explode(",",$return_value);
}
foreach($return_value as $key){
switch ($key){
case "name":
$fileinfo['name']=basename($path);
break;
case "server_path":
$fileinfo['server_path']=$file;
break;
case 'date':
$fileinfo['date']=filemtime($file);
break;
case 'size':
$fileinfo['size']=filesize($file);
break;
case 'readable':
$fileinfo['readable']=is_readable($file);
break;
case 'writable':
$fileinfo['writable']=is_writable($file);
break;
case 'executable':
$fileinfo['executable']=is_executable($file);
break;
case 'fileperms':
$fileinfo['fileperms']=fileperms($file);
break; }
}
return $fileinfo;
}
/**
* 获得八进制的权限位
* @param string $perms
* @return string
*/
public static function octal_permissions($perms){
return substr(sprintf("%o",$perms), -3);
}
}