PHP文件及目录操作

fopen

打开模式

  •  r    只读模式
  •  r+  读写模式,数据从前面插入
  • w    数据从前面写入,原数据清空
  • w+ 读写模式, 数据从前面写入,原数据清空
  • a     追加写,数据从末尾写入
  • a+   读写模式,数据从末尾写入

$file_dir = './hello.txt';
$handle_r = fopen($file_dir,'r');
$content =  fread($handle_r,filesize($file_dir));   //haha
var_dump($content);

$handle_w = fopen($file_dir,'w');
var_dump(file_get_contents($file_dir));   //''    内容已被清空
fwrite($handle_w,'test '.$content);
var_dump(file_get_contents($file_dir));   // test haha
fclose($handle_w);

$handle_a = fopen($file_dir,'a');
fwrite($handle_a,' bbq');   //追加写
var_dump(file_get_contents($file_dir)); //test haha bbq
fclose($handle_a);复制代码

写入函数

fwrite/fputs 

读取函数

fread   读取第二个参数length 字节

fgets   读取第一行

fgetc    读取第一个字符

关闭函数

fclose

不需要fopen打开文件,可使用

file_get_contents

file_put_contents

  进行读写


其它读取函数

file  把整个文件读入一个数组中。如果想字符串返回,需要使用file_get_contents 

readfile  读取文件并写入到输出缓冲 返回值为文件字节数

//强制下载
if (file_exists($file_dir)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file_dir).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file_dir));
    readfile($file_dir);
    exit;
}复制代码

 

   目录遍历

$dir = 'D:\phpStudy\PHPTutorial';
function loopDir($dir,$deep=0){
    $handle = opendir($dir);
    while(($file = readdir($handle)) !== false){
        if($file != '.' && $file != '..'){
            if(filetype($dir.'/'.$file) == 'dir'){
                loopDir($dir.'/'.$file,$deep+1);
            }else{
                echo str_repeat('--',$deep).$file.'<br/>';
            }
        }
    }
}
loopDir($dir);复制代码


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值