PHP File Create / Write

PHP Tutorial

PHP File Create / Write 

In PHP, file creation and writing allow you to store data permanently on the server.
This is widely used for logs, reports, configuration files, user data, and backups.


 What is File Create / Write in PHP?

Using PHP, you can:

  • Create a new file

  • Write data into a file

  • Overwrite existing content

  • Append new content to an existing file

 If a file does not exist, PHP can create it automatically.


 File Write Basics – fopen() Modes

ModeDescription
wWrite only (creates file / overwrites existing)
aAppend (creates file / adds data at end)
w+Read + Write (overwrite)
a+Read + Append

 Create & Write File Using fopen() + fwrite()

Example: Create a New File and Write Data

  •  Creates data.txt if it doesn’t exist
  •  Overwrites content if file already exists

 Write Multiple Lines

\n → new line (works on servers)


Append Data to File

(Most Common in Real Projects)

  •  Old data remains
  •  New data added at the end

Write File Using Shortcut – file_put_contents()

Create / Overwrite

Append Data

Simpler and faster than fopen() + fwrite()


Check File Permission Before Writing


 Error Handling While Writing Files

 Prevents script failure


 Common Mistakes

  •  Using w instead of a (data loss)
  •  Forgetting fclose() 
  •  Writing without permission
  •  Not handling errors

Interview Questions & MCQs (Very Important)

Q1. Which function writes data to a file?

A) file()
B) fwrite()
C) fread()
D) readfile()

Answer: B


Q2. Which mode appends data?

A) w
B) r
C) a
D) x

Answer: C


Q3. Which function creates & writes file in one line?

A) fopen()
B) fwrite()
C) file_put_contents()
D) file_get_contents()

Answer: C


Q4. What happens if file doesn’t exist in w mode?

A) Error
B) Nothing
C) File created
D) PHP stops

Answer: C


Q5. Which constant is used to append data?

A) FILE_ADD
B) FILE_APPEND
C) FILE_WRITE
D) FILE_NEW

Answer: B


Q6. Why is fclose() important?

A) Releases memory
B) Saves data properly
C) Prevents file corruption
D) All of the above

Answer: D


Real-Life Use Cases

  •  User activity logs
  •  Error logging
  •  Configuration storage
  •  Report generation
  •  File-based caching

 Summary

  • fopen() + fwrite() → manual file writing

  • file_put_contents() → fastest method

  • w overwrites, a appends

  • Always close file after writing

  • Handle permissions & errors

  • Very important for PHP exams & interviews

You may also like...