2013-12-23 53 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); 
} 
相關問題