PHP File Create / Write

πŸ“ PHP File Create / Write Tutorial

PHP allows you to create new files and write data into them using built-in functions like fopen() and fwrite(). This is useful for storing logs, user input, or any dynamic data.


1️⃣ Create a New File


 

  • "w" mode: Write mode

    • Creates the file if it doesn’t exist

    • Overwrites the file if it already exists


2️⃣ Write Data to a File


 

Output in newfile.txt:


 


3️⃣ Append Data to an Existing File


 

βœ… "a" mode adds new content without overwriting existing content.


4️⃣ Using file_put_contents() (Shortcut)

You can create/write a file in a single step:


 

  • Overwrites existing content by default.

  • Use FILE_APPEND to append:


 


5️⃣ Key Points

  • Modes matter: "w" = write/overwrite, "a" = append

  • Always close the file after writing with fclose()

  • file_put_contents() is a simpler alternative

  • Ensure write permissions in the folder


🏁 Summary

  1. fopen() + fwrite() β†’ Create/write files

  2. "w" β†’ Overwrite or create file

  3. "a" β†’ Append to file

  4. file_put_contents() β†’ Shortcut for write/append

  5. Always close files with fclose()

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

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