Writing files

The quick method with file_put_contents() comes after the fwrite() method in this document.

Say we have a string with contents,

$some_var = <<<eof
This is a string that contains some words.
eof
;

Say we want to write the contents of $some_var to the file myfile.txt.

Here is the brute force way to write the contents.

$fp = fopen("myfile.txt","w");
fwrite($fp,$some_var);
fclose($fp);

You can find the specifics at http://docs.php.net/fopen », http://docs.php.net/fwrite » and http://docs.php.net/fclose ».

Anyway, if you have a web application writing to the same file, you may want to put a lock on the file to prevent overwriting. In PHP you can use flock() » with LOCK_EX to get an exclusive lock on the file.

Here is the easy way to write to files.

file_put_contents("myfile.txt",$some_var);

By using file_put_contents() you by pass having to use multiple functions to write files. You can also create a lock on the file with the command.

file_put_contents("myfile.txt",$some_var,LOCK_EX);

You can also append contents to the file with FILE_APPEND.

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.