PHP Manual
/
Working with files

File_put_contents

22. 08. 2019

Obsah článku

The **file_put_contents** function is suitable for automatic writing to a file. Alternatively, you can also use fopen(), which I don't recommend for beginners.

Sample

$file = 'file.txt';
$content = 'Content to be saved to file.';
file_put_contents($file, $content);

file_put_contents takes 2 parameters:

  • filename where to write,
  • the content of the file to write.

Note: file_put_contents() overwrites the file with the latest contents.

Watch out for overwriting

If you save via file_put_contents, beware of overwriting the data. The function will delete all the current content and replace it with the new content. So if you just want to append the text, you can either add it to the beginning or to the end using your own script:

$file = 'file.txt';
$content = 'New content.';
$oldContent = file_get_contents($file);
file_put_contents($file, $content . $oldContent);

So first the file is opened, then the new content is written, and the original content is written after it...

If we want to add the old content before the new, we just need to modify the script slightly:

$file = 'file.txt';
$content = New content.';
$oldContent = file_get_contents($file);
file_put_contents($file, $oldContent . $content);

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

1.
Status:
All systems normal.
2024