2013-12-23 57 views
0

以下是我的代码片段:如何检查文件是否存在于目录中或不在PHP中?

<?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”目录中,则应该删除它。 我尝试了file_exists(),但无法理解如何将其用于特定目录。 任何人都可以在这方面指导我吗?任何形式的帮助将不胜感激。

+0

这个** ABC **目录在哪里?它是在包含PDF文件的目录中还是在它之外?你能否在问题中包含一个目录树? – Subin

+0

in'file_exists()'你可能必须传递完整路径而不仅仅是文件名。 – Theraot

回答

0

file_exists使用绝对路径来获取文件,使用这样的:

 $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"; 
    } 

检查:http://fr.php.net/manual/en/function.file-exists.php

+0

他询问文件是否位于名为** ABC **的目录** – Subin

-1

功能scandir是非常有用的。

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!"; 
+0

永远不要扫描以检测单个文件的存在。 file_exists()将是最佳实践。 scandir()需要最大的努力,应该首选目录迭代器(FilesystemIterator)或提取(glob())。 – tr0y

1

试试这个,并希望这会有所帮助。

$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!!!"; 
} 
+2

值得一提的是你应该使用'DIRECTORY_SEPARATOR'。由于在Linux中使用“\”将失败,并且“/”在Windows中失败。 – Theraot

+0

确实如此,但对于所问的问题,这可以是一个快速解决方案。编码人员应该尝试变化 –

0

使用php函数unlink()(删除文件)和file_exists()(检查文件是否存在)的组合。

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); 
} 
相关问题