How to write into a file in PHP?

brilliant picture brilliant · Nov 20, 2009 · Viewed 284.9k times · Source

I have this script on one free PHP-supporting server:

<html>
<body>

<?php
$file = fopen("lidn.txt","a");


fclose($file);
?>

</body>
</html>

It creates the file lidn.txt, but it's empty.

How can I create a file and write something into it, for example the line "Cats chase mice"?

Answer

Savageman picture Savageman · Nov 20, 2009

You can use a higher-level function like:

file_put_contents($filename, $content);

which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.

Docs: file_put_contents