txt-dosyaya fwrite

2 Cevap php

Şu anda PHP ile bir txt dosyası yazmak çalışıyorum, ben bu küçük senaryoyu buldum:

<?php
$filename = 'testFile.txt';
$somecontent = "Add this to the file\n";

if (is_writable($filename)) {

    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";
    fclose($handle);

} 

else {
    echo "The file $filename is not writable";
}
?>

Ben bir başarı mesajı alıyorum, ama hiçbir şey dosyaya yazılır. Ben txt dosyasını silmek bile ben hala başarı mesajı almak

Herkes böyle bir durum giderilir nasıl biliyor mu?

2 Cevap

Sizin kod mükemmel çalışıyor. Ancak, dosya henüz yoksa is_writable onay başarısız olacağını unutmayın.

Eğer bir web sunucusu aracılığıyla çalıştırmak, bir önbelleğe alınmış yanıt incelemekte olmadığından emin olun.

Your first check with is_writable is not useful, as it fails if the file does not exist. When you use fopen with the "a" parameter you appent to the file if it exists otherwise it will create a new one.

Eğer dosya file_exists (http://php.net/manual/en/function.file-exists.php) ile can var, ama gerçekten gerekli olup olmadığını denetlemek istiyorsanız.

Kodunuzu, dosyayı silmek eğer aslında bir "Dosya yazılabilir değil" hata almalısınız ... Eğer exactly bu kodu var emin misin?

Aksi takdirde, ben kod çalıştı ve (ilk olmadan if) çalışıyor.