1 获取文件信息
1.1 第一种方式(fopen、fstat、file_exists)
<?php
$file_full_path = './test.txt';
if(file_exists($file_full_path)){ // 检查文件或目录是否存在,存在则返回 TRUE,否则返回 FALSE
$fp = fopen($file_full_path, 'r'); // 打开文件或url,成功时返回文件指针资源,如果打开失败,本函数返回 FALSE。
$fileinfo_arr = fstat($fp); // 通过已打开的文件指针取得文件信息,返回一个数组具有该文件的统计信息
echo '<pre>';
var_dump($fileinfo_arr);
echo '文件的大小是:' . $fileinfo_arr['size'] . '个字节';
echo '文件的创建时间是:' . date('Y-m-d H:i:s', $fileinfo_arr['ctime']);
echo '文件的访问时间是:' . date('Y-m-d H:i:s', $fileinfo_arr['atime']);
echo '文件的修改时间是:' . date('Y-m-d H:i:s', $fileinfo_arr['mtime']);
}else{
echo '文件不存在';
}
1.2 第二种方式
<?php
$file_full_path = './test.txt';
if(file_exists($file_full_path)){
echo '文件的大小是:' . filesize($file_full_path);
echo '文件的类型是:' . filetype($file_full_path);
echo '文件的创建时间是:' . date('Y-m-d H:i:s', filectime($file_full_path));
echo '文件的访问时间是:' . date('Y-m-d H:i:s', fileatime($file_full_path));
echo '文件的修改时间是:' . date('Y-m-d H:i:s', filemtime($file_full_path));
}else{
echo '文件不存在';
}
2 读取文件内容
2.1 第一种方式,fread
<?php
$file_full_path = './test.txt';
if(file_exists($file_full_path)){
// 1、打开文件
$fp = fopen($file_full_path, 'r');
// 2、获取文件的大小
$file_size = filesize($file_full_path);
// 3、读取内容
$con_str = fread($fp, $file_size); // 返回所读取的字符串, 或者在失败时返回 FALSE。
fclose($fp);
// 替换换行符
$con_str = str_replace("\r\n", '<br>', $con_str);
$con_str = str_replace("\n", '<br>', $con_str);
// 替换 tab
$con_str = str_replace(" ", " ", $con_str);
echo $con_str;
}else{
echo '文件不存在';
}
2.2 第二种方式,feof
<?php
$file_full_path = './test.txt';
if(file_exists($file_full_path)){
$fp = fopen($file_full_path, 'r');
// 设置缓冲
$buffer = '';
$buffer_size = 1024;
$con_str = '';
while(!feof($fp)){ // 测试文件指针是否到了文件结束的位置,到达返回true,否则返回false
$buffer = fread($fp, $buffer_size);
$con_str .= $buffer;
}
// 关闭文件
fclose($fp);
$con_str = str_replace("\r\n", '<br>', $con_str);
$con_str = str_replace("\n", '<br>', $con_str);
$con_str = str_replace(" ", ' ', $con_str);
echo $con_str;
}else{
echo '文件不存在';
}