PHP Add string to text file-ThrowExceptions

Exception or error:

Possible Duplicate:
writing to a text file in php

Say I wanted to add the string $ip to the text file ip.txt in the same directory. I am currently using file_get_contents to read from the text file.

How to solve:

You could use file_put_contents

  $ip = "foo";
  file_put_contents("ip.txt", $ip, FILE_APPEND);

FILE_APPEND will append the text. Absence of this flag will cause file-overwriting.


file_put_contents() with FILE_APPEND flag appends text to given file:

file_put_contents('filename.txt', $stringToAppend, FILE_APPEND);


file_put_contents to put contents into a file.

if(!file_put_contents("path/to/file.txt", $ip, FILE_APPEND)){
    // failure

Leave a Reply

Your email address will not be published. Required fields are marked *