2012-03-24 106 views
3

如果PHP中不存在文件,只能用PHP編寫文件嗎?fwrite如果文件不存在?

$file = fopen("test.txt","w"); 
echo fwrite($file,"Some Code Here"); 
fclose($file); 

因此,如果該文件確實存在的代碼不會寫代碼,但如果文件不存在,它會創建一個新的文件,並寫入代碼

提前感謝!

回答

6

可以使用fopen()x代替w的模式,這將使得FOPEN如果該文件已經存在失敗。與使用file_exists相比,這樣檢查的好處在於,如果在檢查是否存在和實際打開文件之間創建文件,則它不會有錯誤。缺點是它(有點奇怪)會在文件已經存在的情況下生成E_WARNING。

換句話說(在@ ThiefMaster的評論的幫助下),類似的;

$file = @fopen("test.txt","x"); 
if($file) 
{ 
    echo fwrite($file,"Some Code Here"); 
    fclose($file); 
} 
+1

我想你需要'@fopen(...)'來抑制拋出的警告。 – ThiefMaster 2012-03-24 08:47:08

+0

@ThiefMaster謝謝,當我忘記_that_時,我的PHP顯然是生鏽的:) – 2012-03-24 08:51:01

+0

謝謝我一直在尋找這段代碼的年齡:) – 2012-03-24 09:01:08

4

如果在執行代碼之前文件存在,請使用file_exists($ filename)進行檢查。

if (!file_exists("test.txt")) { 
    $file = fopen("test.txt","w"); 
    echo fwrite($file,"Some Code Here"); 
    fclose($file); 
} 
0

創建一個名爲$ file的變量。該變量包含我們想要創建的文件的名稱。

使用PHP的is_file函數,我們檢查文件是否已經存在。

如果is_file返回布爾FALSE值,那麼我們的文件名不存在。

如果文件不存在,我們使用函數file_put_contents創建文件。

//The name of the file that we want to create if it doesn't exist. 
$file = 'test.txt'; 

//Use the function is_file to check if the file already exists or not. 
if(!is_file($file)){ 
    //Some simple example content. 
    $contents = 'This is a test!'; 
    //Save our content to the file. 
    file_put_contents($file, $contents); 
}