• Write a file using PHP

    Using PHP code, it is possible to open a file on you server and also write to it. File will be created if it does not exists. Please note that, chmod must set to 777 to do write on that file.
    First, open a file if you want to write on it. Then write in to that using fwrite command. Please refer following code for the same.

    1
    
     

    Here fclose at the end is used close the file. And \n at the end of content strings is for serving line breaks. After running this script, filename.txt will contain following text:
    Hello.
    How r u?
    If we run the same code with different content, old content will be erased and filename.txt will contain new content. For example,

    1
    
     

    Then filename.txt will contain following text.
    Hey.
    I am fine.
    If you do not want to rewrite file and want to append text to the existing text, you should write ‘a’ instead of ‘w’ in fopen argument as follows.

    1
    
     

    Now filename.txt will contain following text.

    Hello.
    How are you?

    Hey.

    I am fine.

    Tags:

Comments on this post

Leave a Reply

  • Security Code :


    × 3 = eighteen