php中文件操作常用函数有哪些
一、总结
一句话总结:读写文件函数 判断文件或者目录是否存在函数 创建目录函数
file_exists() mkdir() file_get_content() file_put_content()
1、php检查文件或者目录是否存在函数是什么?
file_exists()
file_exists — 检查文件或目录是否存在
}else{echo "The file $filename does not exist";
}?>
2、php创建一个目录的函数是什么?
mkdir() $ans=mkdir($file_path,0777,true);
mkdir — 新建目录
$ans=mkdir ($file_path,0777,true);
二、php中如何创建文件夹
参考:php中如何创建文件夹
https://www.cnblogs.com/modou/p/5991365.html
这个功能比较简单,直接上代码了:
$dir = iconv("UTF-8", "GBK", "Public/bookcover");if (!file_exists($dir)){mkdir ($dir,0777,true);echo '创建文件夹bookcover成功';
}else{echo '需创建的文件夹bookcover已经存在';
}
iconv方法是为了防止中文乱码,保证可以创建识别中文目录,不用iconv方法格式的话,将无法创建中文目录
mkdir方法的第一个参数是要创建的目录路径,第二个参数是指创建目录的权限,在windows系统下该参数会被忽略,第三个参数是指是否创建多级目录,默认为false
三、php 判断文件或目录是否存在
参考:php 判断文件或目录是否存在
https://www.cnblogs.com/diony/p/5541458.html
判断文件或目录是否存在有自带的函数
file_exists:文件是否存在
$file = "check.txt";
if(file_exists($file))
{
echo "当前目录中,文件".$file."存在";
}
else
{
echo "当前目录中,文件".$file."不存在";
}
is_dir:目录是否存在
if(is_dir($dir))
{
echo "当前目录下,目录".$dir."存在";
}
else
{
echo "当前目录下,目录".$dir."不存在";
}
四、thinkphp5自写的文件缓存代码
1 //5、【下一题】按钮逻辑---确定这道题目开始的做题时间
2 public functionquestion_next(){3 $back_data=[];4 $back_data['operation_success']=false;5 if(request()->isAjax()){6 $question_index_num=input('question_index_num');7 $dataIn=[];8 $dataIn['space_type']=input('space_type');9 $dataIn['xiulian_type']=input('xiulian_type');10 $dataIn['sort_type']=input('sort_type');11 $dataIn['time_type']=input('time_type');12
13 //2.1、取出缓存
14 $question_list_path='data_record/blog_question_record/'.$dataIn['space_type'].'/sort_type_'.$dataIn['sort_type'].'/time_'.$dataIn['time_type'].'/xiulian_type_'.$dataIn['xiulian_type'].'.php';15 if(file_exists($question_list_path)) {16 $back_data['operation_success']=true;17 $question_list = file_get_contents($question_list_path);18 $question_list = json_decode($question_list, true);19
20 //2.2、确定题目的开始时间
21 $question_list[$question_index_num]['bq_question_begin_time']=time();22 $back_data['bq_question_begin_time']=time();23 //2.4、提交缓存
24 $createDirAns=appindexmodeloolsfileDirectory::createDir($question_list_path);25 if($createDirAns){26 $result=file_put_contents($question_list_path,json_encode($question_list));27 //dump($result);
28 $back_data['cache_result']=$result;29 }30 }31
32 return $back_data;33 }34 return $back_data;35 }
1 <?php2 namespace appindexmodeloolsfile;3 useappindexmodelBase;4
5 class Directory extendsBase6 {7 //1、创建指定目录的文件夹
8 public static function createDir($file_path){9
10 $dir = iconv("GBK", "UTF-8", "$file_path");11 //步骤一:去掉文件路径的文件名,只留下文件名
12 $file_arr=explode('/',$file_path);13 //1、去掉为空的
14 $file_arr_new=[];15 foreach ($file_arr as $key=>$val){16 if(strlen($val)>=1) $file_arr_new[]=$val;17 }18 $file_arr=$file_arr_new;19 array_pop($file_arr);20 $file_path=implode('/',$file_arr);21 if (!file_exists($file_path)){22 $ans=mkdir ($file_path,0777,true);23 if($ans===false) return false;24 return true;25 } else{26 return true;27 }28 }29 }