如何在PHP中检查目录中是否存在文件?
以下是我的代码片段:如何在PHP中检查目录中是否存在文件?,php,file,pdf,filenames,file-exists,Php,File,Pdf,Filenames,File Exists,以下是我的代码片段: <?php $filename = $test_data['test_name'].".pdf"; //I want to check whether the above file with the same extension(.pdf) is existing in the directory having name say "ABC" is present or not ?> 如果“ABC”目录中没有这样的文件,那么它应该创建相同的文件。 如果文件存
<?php
$filename = $test_data['test_name'].".pdf";
//I want to check whether the above file with the same extension(.pdf) is existing in the directory having name say "ABC" is present or not
?>
如果“ABC”目录中没有这样的文件,那么它应该创建相同的文件。
如果文件存在于目录“ABC”中,则应将其删除。
我尝试使用文件\u exists()
,但不明白如何将其用于特定目录。
有谁能在这方面指导我吗?非常感谢您提供的任何帮助。文件\u使用绝对路径获取文件,因此如下所示:
$directorypath = dirname(__FILE__) . '/to/your/directory/';
$filename = $directorypath . $test_data['test_name'].".pdf";
if (file_exists($filename)) {
echo "The file $filename exists";
//delete file
unlink('$filename');
} else {
echo "The file $filename does not exist";
}
检查此项:功能非常有用
file_flag=0;
$input_file=scandir($full_path);
foreach ($input_file as $input_name){
if($input_name==$ABC)
file_flag=1;
else
file_flag=0;
}
if (file_flag==1)
echo "File exists!";
else
echo "File not found!";
试试这个,希望这会有帮助
$file_path = $_SERVER['DOCUMENT_ROOT']."/MyFolder/";
$file_name = "abc.pdf";
if( file_exists( $file_path.$file_name ))
{
echo "File Exists";
}
else
{
echo "File not found!!!";
}
结合使用php函数unlink()(删除文件)和file_exists()(检查文件是否存在)
这个ABC目录在哪里?它是在包含PDF文件的目录中还是在它之外?您能在问题中包括目录树吗?在
文件\u exists()
中,您可能需要传递完整路径,而不仅仅是文件名。他问文件是否位于名为ABCIt的目录中,值得一提的是,您应该使用目录\u分隔符。因为在Linux中使用“\”将失败,而在Windows中使用“/”将失败。这是正确的,但这是一个快速解决问题的方法。编码器应该尝试使用sureNever扫描的变体来检测单个文件的存在。文件_exists()将是最佳做法。scandir()需要最大的努力,应该首选目录迭代器(FileSystemEmitter)或提取(glob()。
Like
$filename = "./path to file/".$test_data['test_name'].".pdf";
if (file_exists($filename)) {
echo "The file $filename exists";
if(unlink ($filename)){
echo "deleted";
}else{
echo "not delete";
}
} else {
$file = fopen($filename,"w");
fwrite($file,"your content");
fclose($file);
}