How to write files to disk with PHP

Josh Sherman
1 min read
Software Development 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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles