PHP文件操作函数

梦里梦外; 2022-09-17 13:30 255阅读 0赞

一 、解析路径:

1 获得文件名:
basename();
给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix 结束的,那这一部分也会被去掉。
eg:

$path = “ /home/httpd/html/index.php “ ;
$file = basename ( $path , “ .php “ ); // $file is set to “index”

2 得到目录部分:
dirname();
给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名。
eg:

$path = “ /etc/passwd “ ;
$file = dirname ( $path ); // $file is set to “/etc”

3 得到路径关联数组
pathinfo();
得到一个指定路径中的三个部分:目录名,基本名,扩展名。
eg:

$pathinfo = pathinfo ( “ www/test/index.html “ );
var_dump ( $pathinfo );
// $path[‘dirname’]
$path [ ‘ basename ‘ ]
$path [ ‘ extenssion ‘ ]

二、文件类型

  1. filetype();
    返回文件的类型。可能的值有 fifo,char,dir,block,link,file 和 unknown。
    eg:

echo filetype ( ‘ /etc/passwd ‘ ); // file
echo filetype ( ‘ /etc/ ‘ ); // dir

三、得到给定文件有用信息数组(很有用)

  1. fstat();
    通过已打开的文件指针取得文件信息
    获取由文件指针 handle 所打开文件的统计信息。本函数和 stat() 函数相似,除了它是作用于已打开的文件指针而不是文件名。
    eg:

// 打开文件
$fp = fopen ( “ /etc/passwd “ , “ r “ );
// 取得统计信息
$fstat = fstat ( $fp );
// 关闭文件
fclose ( $fp );
// 只显示关联数组部分
print_r ( array_slice ( $fstat , 13 ));

  1. stat()
    获取由 filename 指定的文件的统计信息(类比fstat())

四、计算大小

  1. filesize()
    返回文件大小的字节数,如果出错返回 FALSE 并生成一条 E_WARNING 级的错误。
    eg:

// 输出类似:somefile.txt: 1024 bytes
$filename = ‘ somefile.txt ‘ ;
echo $filename . ‘ : ‘ . filesize ( $filename ) . ‘ bytes ‘ ;

  1. disk_free_space()
    获得目录所在磁盘分区的可用空间(字节单位)
    eg

// $df 包含根目录下可用的字节数
$df = disk_free_space ( “ / “ );
// 在 Windows 下:
disk_free_space ( “ C: “ );
disk_free_space ( “ D: “ );

  1. disk_total_space()
    返回一个目录的磁盘总大小
    eg:(同上,换掉函数)

另:如需要计算一个目录大小,可以编写一个递归函数来实现

ExpandedBlockStart.gif代码

function dir_size( $dir ){
$dir_size = 0 ;
if ( $dh = @ opendir ( $dir )){
while (( $filename = readdir ( $dh )) != false ){
if ( $filename != ‘ . ‘ and $filename != ‘ .. ‘ ){

  1. if ( is\_file ( $dir . ' / ' . $filename ))\{

$dir_size += filesize ( $dir . ‘ / ‘ . $filename );

} else if ( is_dir ( $dir . ‘ / ‘ . $filename )){

  1. $dir\_size \+= dir\_size( $dir . ' / ' . $filename );

}
}

  1. \} \# end while
  2. \} \# end opendir

@ closedir ( $dh );
return $dir_size ;
} # end function

五、 访问与修改时间

  1. fileatime(): 最后访问时间
  2. filectime(): 最后改变时间(任何数据的修改)
  3. filemtime(): 最后修改时间(指仅是内容修改)

六、 文件的I/O操作

  1. fopen — 打开文件或者 URL

mode 说明
‘r’ 只读方式打开,将文件指针指向文件头。
‘r+’ 读写方式打开,将文件指针指向文件头。
‘w’ 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
‘w+’ 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
‘a’ 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
‘a+’ 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
‘x’ 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,
‘x+’ 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE
eg:

$handle = fopen ( “ /home/rasmus/file.txt “ , “ r “ );

  1. file — 把整个文件读入一个数组中(此函数是很有用的)
    和 file_get_contents() 一样,只除了 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败 file() 返回 FALSE。
    eg:

ExpandedBlockStart.gif代码

$lines = file ( ‘ http://www.example.com/ ‘ );
// 在数组中循环,显示 HTML 的源文件并加上行号。
foreach ( $lines as $line_num => $line ) {
echo “ Line #{ $line_num } : “ . htmlspecialchars ( $line ) . “
\n “ ;
}
// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。
$html = implode ( ‘’ , file ( ‘ http://www.example.com/ ‘ ));

  1. fgets — 从文件指针中读取一行
    从 handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。
    eg:

$handle = @ fopen ( “ /tmp/inputfile.txt “ , “ r “ );
if ( $handle ) {
while ( ! feof ( $handle )) {
$buffer = fgets ( $handle , 4096 );
echo $buffer ;
}
fclose ( $handle );
}

  1. fgetss — 从文件指针中读取一行并过滤掉 HTML 标记
    和 fgets() 相同,只除了 fgetss 尝试从读取的文本中去掉任何 HTML 和 PHP 标记。

    可以用可选的第三个参数指定哪些标记不被去掉

另:对的目录的操作:

  1. opendir -- 打开目录句柄,打开一个目录句柄,可用于之后的 closedir(),readdir() 和 rewinddir() 调用中。
  2. readdir — 从目录句柄中读取条目,返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。
    eg:

ExpandedBlockStart.gif代码

// 注意在 4.0.0-RC2 之前不存在 !== 运算符

if ( $handle = opendir ( ‘ /path/to/files ‘ )) {
echo “ Directory handle: $handle \n “ ;
echo “ Files:\n “ ;

while ( false !== ( $file = readdir ( $handle ))) {
echo “ $file \n “ ;
}

while ( $file = readdir ( $handle )) {
echo “ $file \n “ ;
}
closedir ( $handle );
}

  1. scandir -- 列出指定路径中的文件和目录(很有用),返回一个 array,包含有 directory 中的文件和目录。
    默认的排序顺序是按字母升序排列。如果使用了可选参数 sorting_order(设为 1),则排序顺序是按字母降序排列。
    eg:

$dir = ‘ /tmp ‘ ;
$files1 = scandir ( $dir );
$files2 = scandir ( $dir , 1 );

print_r ( $files1 );
print_r ( $files2 );

另外注:

七、 对文件属性的操作(操作系统环境不同,可能有所不一样,这点要注意)

  1. 1文件是否可读:

boolis_readable ( string filename )

  1. 如果由 `filename` 指定的文件或目录存在并且可读则返回 **TRUE**。
  2. 记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。
  3. 2 文件是否可写
  4. bool **is\_writable** ( string filename )
  5. 如果文件存在并且可写则返回 **TRUE**。`filename` 参数可以是一个允许进行是否可写检查的目录名。
  6. 记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制

3 检查文件是否存在

boolfile_exists ( string filename )

  1. 如果由 `filename` 指定的文件或目录存在则返回 **TRUE**,否则返回 **FALSE**

=====================================PHP文件操作类=========================================

[php] view plain copy

  1. <?php
  2. /***************************************************************************************
  3. 文件名:File.cls.php
  4. 文件简介:类clsFile的定义,对文件操作的封装
  5. 版本:2.0 最后修改日期:2011-8-23
  6. ****************************************************************************************/
  7. !defined(‘INIT_PHPV’) && die(‘No direct script access allowed’);
  8. class clsFile
  9. {
  10. private $fileName_str; //文件的路径
  11. private $fileOpenMethod_str; //文件打开模式
  12. function __construct($fileName_str=’’,$fileOpenMethod_str=’readOnly’)//路径,默认为空;模式,默认均为只读
  13. {
  14. //构造函数,完成数据成员的初始化
  15. $this->fileName_str=$fileName_str;
  16. $this->fileOpenMethod_str=$fileOpenMethod_str;
  17. }
  18. function __destruct()
  19. {
  20. //析构函数
  21. }
  22. public function __get($valName_val)//欲取得的数据成员名称
  23. {
  24. //特殊函数,取得指定名称数据成员的值
  25. return $this->$valName_val;
  26. }
  27. private function on_error($errMsg_str=’Unkown Error!’,$errNo_int=0)//错误信息,错误代码
  28. {
  29. echo ‘程序错误:’.$errMsg_str.’错误代码:’.$errNo_int;//出错处理函数
  30. }
  31. public function open()
  32. {
  33. //打开相应文件,返回文件资源标识
  34. //根据fileOpenMethod_str选择打开方式
  35. switch($this->fileOpenMethod_str)
  36. {
  37. case ‘readOnly’:
  38. $openMethod_str=’r’; //只读,指针指向文件头
  39. break;
  40. case ‘readWrite’:
  41. $openMethod_str=’r+’; //读写,指针指向文件头
  42. break;
  43. case ‘writeAndInit’:
  44. $openMethod_str=’w’; //只写,指针指向文件头将大小截为零,不存在则创建
  45. break;
  46. case ‘readWriteAndInit’:
  47. $openMethod_str=’r+’; //读写,指针指向文件头将大小截为零,不存在则创建
  48. break;
  49. case ‘writeAndAdd’:
  50. $openMethod_str=’a’; //只写,指针指向文件末尾,不存在则创建
  51. break;
  52. case ‘readWriteAndAdd’:
  53. $openMethod_str=’a+’; //读写,指针指向文件末尾,不存在则创建
  54. break;
  55. default:
  56. $this->on_error(‘Open method error!’,310);//出错处理
  57. exit;
  58. }
  59. //打开文件
  60. if(!$fp_res=fopen($this->fileName_str,$openMethod_str))
  61. {
  62. $this->on_error(‘Can\‘t open the file!’,301);//出错处理
  63. exit;
  64. }
  65. return $fp_res;
  66. }
  67. public function close($fp_res)//由open返回的资源标识
  68. {
  69. //关闭所打开的文件
  70. if(!fclose($fp_res))
  71. {
  72. $this->on_error(‘Can\‘t close the file!’,302);//出错处理
  73. exit;
  74. }
  75. }
  76. public function write()//$fp_res,$data_str,$length_int:文件资源标识,写入的字符串,长度控制
  77. {
  78. //将字符串string_str写入文件fp_res,可控制写入的长度length_int
  79. //判断参数数量,调用相关函数
  80. $argNum_int=func_num_args();//参数个数
  81. $fp_res=func_get_arg(0); //文件资源标识
  82. $data_str=func_get_arg(1); //写入的字符串
  83. if($argNum_int==3)
  84. {
  85. $length_int=func_get_arg(2); //长度控制
  86. if(!fwrite($fp_res,$data_str,$length_int))
  87. {
  88. $this->on_error(‘Can\‘t write the file!’,303);//出错处理
  89. exit;
  90. }
  91. }
  92. else
  93. {
  94. if(!fwrite($fp_res,$data_str))
  95. {
  96. $this->on_error(‘Can\‘t write the file!’,303);//出错处理
  97. exit;
  98. }
  99. }
  100. }
  101. public function read_line()//$fp_res,$length_int:文件资源标识,读入长度
  102. {
  103. //从文件fp_res中读入一行字符串,可控制长度
  104. //判断参数数量
  105. $argNum_int=func_num_args();
  106. $fp_res=func_get_arg(0);
  107. if($argNum_int==2)
  108. {
  109. $length_int=func_get_arg(1);
  110. if($string_str=!fgets($fp_res,$length_int))
  111. {
  112. $this->on_error(‘Can\‘t read the file!’,304);//出错处理
  113. exit;
  114. }
  115. return $string_str;
  116. }
  117. else
  118. {
  119. if(!$string_str=fgets($fp_res))
  120. {
  121. $this->on_error(‘Can\‘t read the file!’,304);//出错处理
  122. exit;
  123. }
  124. return $string_str;
  125. }
  126. }
  127. public function read($fp_res,$length_int)//文件资源标识,长度控制
  128. {
  129. //读入文件fp_res,最长为length_int
  130. if(!$string_str=fread($fp_res,$length_int))
  131. {
  132. $this->on_error(‘Can\‘t read the file!’,305);//出错处理
  133. exit;
  134. }
  135. return $string_str;
  136. }
  137. public function is_exists($fileName_str)//文件名
  138. {
  139. //检查文件$fileName_str是否存在,存在则返回true,不存在返回false
  140. return file_exists($fileName_str);
  141. }
  142. /******************取得文件大小*********************/
  143. /*
  144. 取得文件fileName_str的大小
  145. $fileName_str 是文件的路径和名称
  146. 返回文件大小的值
  147. */
  148. public function get_file_size($fileName_str)//文件名
  149. {
  150. return filesize($fileName_str);
  151. }
  152. /******************转换文件大小的表示方法*********************/
  153. /*
  154. $fileSize_int文件的大小,单位是字节
  155. 返回转换后带计量单位的文件大小
  156. */
  157. public function change_size_express($fileSize_int)//文件名
  158. {
  159. if($fileSize_int>1024)
  160. {
  161. $fileSizeNew_int=$fileSize_int/1024;//转换为K
  162. $unit_str=’KB’;
  163. if($fileSizeNew_int>1024)
  164. {
  165. $fileSizeNew_int=$fileSizeNew_int/1024;//转换为M
  166. $unit_str=’MB’;
  167. }
  168. $fileSizeNew_arr=explode(‘.’,$fileSizeNew_int);
  169. $fileSizeNew_str=$fileSizeNew_arr[0].’.’.substr($fileSizeNew_arr[1],0,2).$unit_str;
  170. }
  171. return $fileSizeNew_str;
  172. }
  173. /******************重命名文件*********************/
  174. /*
  175. 将oldname_str指定的文件重命名为newname_str
  176. $oldName_str是文件的原名称
  177. $newName_str是文件的新名称
  178. 返回错误信息
  179. */
  180. public function rename_file($oldName_str,$newName_str)
  181. {
  182. if(!rename($oldName_str,$newName_str))
  183. {
  184. $this->on_error(‘Can\‘t rename file!’,308);
  185. exit;
  186. }
  187. }
  188. /******************删除文件*********************/
  189. /*
  190. 将filename_str指定的文件删除
  191. $fileName_str要删除文件的路径和名称
  192. 返回错误信息
  193. */
  194. public function delete_file($fileName_str)//
  195. {
  196. if(!unlink($fileName_str))
  197. {
  198. $this->on_error(‘Can\‘t delete file!’,309);//出错处理
  199. exit;
  200. }
  201. }
  202. /******************取文件的扩展名*********************/
  203. /*
  204. 取filename_str指定的文件的扩展名
  205. $fileName_str要取类型的文件路径和名称
  206. 返回文件的扩展名
  207. */
  208. public function get_file_type($fileName_str)
  209. {
  210. $fileNamePart_arr=explode(‘.’,$fileName_str);
  211. while(list(,$fileType_str)=each($fileNamePart_arr))
  212. {
  213. $type_str=$fileType_str;
  214. }
  215. return $type_str;
  216. }
  217. /******************判断文件是否是规定的文件类型*********************/
  218. /*
  219. $fileType_str规定的文件类型
  220. $fileName_str要取类型的文件路径和名称
  221. 返回false或true
  222. */
  223. public function is_the_type($fileName_str,$fileType_arr)
  224. {
  225. $cheakFileType_str=$this->get_file_type($fileName_str);
  226. if(!in_array($cheakFileType_str,$fileType_arr))
  227. {
  228. return false;
  229. }
  230. else
  231. {
  232. return true;
  233. }
  234. }
  235. /******************上传文件,并返回上传后的文件信息*********************/
  236. /*
  237. $fileName_str本地文件名
  238. $filePath上传文件的路径,如果$filePath是str则上传到同一目录用一个文件命名,新文件名在其加-1,2,3..,如果是arr则顺序命名
  239. $allowType_arr允许上传的文件类型,留空不限制
  240. $maxSize_int允许文件的最大值,留空不限制
  241. 返回的是新文件信息的二维数组:$reFileInfo_arr
  242. */
  243. public function upload_file($fileName_str,$filePath,$allowType_arr=’’,$maxSize_int=’’)
  244. {
  245. $fileName_arr=$_FILES[$fileName_str][‘name’]; //文件的名称
  246. $fileTempName_arr=$_FILES[$fileName_str][‘tmp_name’]; //文件的缓存文件
  247. $fileSize_arr=$_FILES[$fileName_str][‘size’];//取得文件大小
  248. $reFileInfo_arr=array();
  249. $num=count($fileName_arr)-1;
  250. for($i=0;$i<=$num;$i++)
  251. {
  252. if($fileName_arr[$i]!=’’)
  253. {
  254. if($allowType_arr!=’’ and !$this->is_the_type($fileName_arr[$i],$allowType_arr))//判断是否是允许的文件类型
  255. {
  256. $this->on_error(‘The file is not allowed type!’,310);//出错处理
  257. break;
  258. }
  259. if($maxSize_int!=’’ and $fileSize_arr[$i]>$maxSize_int)
  260. {
  261. $this->on_error(‘The file is too big!’,311);//出错处理
  262. break;
  263. }
  264. $j=$i+1;
  265. $fileType_str=$this->get_file_type($fileName_arr[$i]);//取得文件类型
  266. if(!is_array($filePath))
  267. {
  268. $fileNewName_str=$filePath.’-‘.($j).’.’.$fileType_str;
  269. }
  270. else
  271. {
  272. $fileNewName_str=$filePath_arr[$i].’.’.$fileType_str;
  273. }
  274. copy($fileTempName_arr[$i],$fileNewName_str);//上传文件
  275. unlink($fileTempName_arr[$i]);//删除缓存文件
  276. //———————-存储文件信息——————————//
  277. $doFile_arr=explode(‘/‘,$fileNewName_str);
  278. $doFile_num_int=count($doFile_arr)-1;
  279. $reFileInfo_arr[$j][‘name’]=$doFile_arr[$doFile_num_int];
  280. $reFileInfo_arr[$j][‘type’]=$fileType_str;
  281. $reFileInfo_arr[$j][‘size’]=$this->change_size_express($fileSize_arr[$i]);
  282. }
  283. }
  284. return $reFileInfo_arr;
  285. }
  286. /******************备份文件夹*********************/
  287. }
  288. ?>

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PHP文件操作函数

    一 、解析路径: 1 获得文件名: basename(); 给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix 结束的,

    相关 php文件函数

    1、int     filesize(string filename),获取文件的大小。对于2~4GB之间的文件,可以使用sprintf("%u",filesize($file

    相关 PHP文件操作

    文件操作:对文件的增删改查。(文件夹也是文件) 为什么要使用文件操作? 1.有一些数据:不经常被修改,但是又经常被使用,数据量小,使用文件来保存数据(配置文件,xml文件

    相关 php操作文件

    前言 正常来说,php操作mysql才是绝配,但是如果考虑到安全问题,或者磁盘空间问题,加上涉及的数据比较少的话,那么久可以考虑采用文件的方式进行存储。但是需要注意的时候