php append to file

I like php’s file_put_contents function, which can write a string to a file with single line of code:

file_put_contents("file.txt","content");

Few languages have such powerful function. In C language, you need to open a file first, set some strange open mode, call the write function to write actual content, and close the file in the end. That is really troublesome as we just want to write a string to a file which should be done in a line of code.

Although file_put_contents is easy to use, you may wonder how to append to file instead of overwriting existed file. The above code will overwrite the existing file with the new content. To append to file, you should use the FILE_APPEND flag:

file_put_contents("file.txt","content",FILE_APPEND);

Now the string “content” is appended to file.txt. If file.txt does not exist, it is created and the string is put into the newly created file.

Note that this function does not add new line to the string automatically. So, if you call it multiple times, the strings will be concated together without line breaks between them. Typically, you may want to append a new line after the string so that every string will be put on a new line. You need to append new lines manually:

file_put_contents("file.txt","content\r\n",FILE_APPEND);

 reference

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Leave a Reply