How to write files to disk with PHP

Saving files to disk is a pretty simple task in PHP with file_put_contents(). Here’s how to write a string to a file:

$string = 'I AM STRING!!'
file_put_contents('/path/to/destination', $string

It is generally good practice to only do with when you are dealing with smaller strings as you can run into memory errors if you are trying to assemble a super large string. In situations where this may occur, you can rely on our trusty filesystem functions and write to the file line by line:

$file = fopen('/path/to/destination', 'w'

for ($i = 0 $i <= 1000000 $i++)
{
	fwrite($file, $i . "n"
}

fclose($file

For the most part file_put_contents will get the job done, but if not, you can still get the job done!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.