Pergunta

I have a complex php4 code and want to write something to a file, using file_put_contents, like the following:

$iCounter = 0;
foreach blah...
    ... code
    file_put_contents("/tmp/debug28364363264936214", "test" . $iCounter++ . "\n", FILE_APPEND);
    ...code

I am using FILE_APPEND to append the data to the given file, I am sure that what I print does not contain control characters, the random number sequence makes sure the file is not used in any other context, and the counter variable (only used for the printout) is used to control how often file_put_contents is called.

Executing the code and looking at the file content I just see

test8

while I expect to see

test1
test2
test3
test4
test5
test6
test7
test8

Is there a problem with my syntax? Maybe the code does not work for php4? What else can I use instead?

P.S. I am working on a very large, quite ancient php4 project, so there is no way to recode the project in php5. Not within 2 years...

Foi útil?

Solução

use fopen(); file_put_contents() is php5.

$file = fopen("/tmp/debug28364363264936214", "a+");
fwrite($file, "test" . $iCounter++ . "\n");
fclose($file);

Outras dicas

you can use foreach it there is an array input it will be a similuar procedure

for ($iCounter = 1; $iCounter <= 10; $iCounter++) {

$test_var .= "test" . $iCounter . PHP_EOL;

}


if (file_exists("/tmp/debug28364363264936214")) {

file_put_contents("/tmp/debug28364363264936214", $test_var, FILE_APPEND);

    echo "The file was written";
} else {
    echo "The file was not written";
}

php4 code

if (file_exists("/tmp/debug28364363264936214")) {

$fp = fopen('/tmp/debug28364363264936214', 'a');
fwrite($fp, $test_var);
fclose($fp);

    echo "The file was written";
} else {
    echo "The file was not written";
}

your code might be in php4 but it should work in php5 if using php5 which you should be. you just need to recode the errors.

if you want to append data then do as follows

 $file = "yourfile.txt";
 $data = file_get_contents($file);
 $data =  $data . $newdata;
 file_put_contents($file, $data);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top