Frage

PHP help needed for the beginner here.

I am trying to write(or append) some string to empty .txt file with if statement.
And then also opening the file but it fails due to 0 length issue.

$filename = 'sometext.txt';  //empty text file
$size = filesize($filename);
if( $size <= 0 ) {
    $handle = fopen($filename, 'a');
    fwrite($handle, 'blah blah blah...');
    fclose($handle);
}

$handle = fopen($filename, 'r');
$current = fread($handle,filesize($filename));

This wont let me write or append to $filename.
But if I comment out if statement, then it works.

Why is that happening?

War es hilfreich?

Lösung

Why do you open the file in append mode, if you know, the file doesn't contain something? You should also change your fwrite line, because you use the wrong handle

$filename = 'sometext.txt';  //empty text file
$size = filesize($filename);
if( $size <= 0 ) {
    $handle = fopen($filename, 'w');
    fwrite($handle, 'blah blah blah...');
    fclose($handle);
}

$handle = fopen($filename, 'r');
$current = fread($handle,filesize($filename));

If you want to append something to an existing file, you have to change your compare statement to >=

Andere Tipps

You're asking if the filesize is < or = 0. If the filesize is for example 1 Byte, you will never reach the fopen/fwrite/fclose calls in your if-section.

If you comment $size = filesize($filename) out, $size is not defined. In PHP not defined and 0 are equal and you reach the if-section. That's why it works then.

Try this...

$my_file = 'emptytxt.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
$size = filesize($my_file);
$data = 'New data line 1';
if($size <= 0)
{
fwrite($handle, $data);
}
fclose($handle);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top