PHP File Handling

📁 PHP File Handling Tutorial

PHP provides functions to create, open, read, write, append, and delete files. File handling is useful for storing data, logs, user input, or configuration without using a database.


1️⃣ Opening a File (fopen)


 

Modes in fopen()

Mode Description
r Read only (file must exist)
w Write only (creates file or truncates existing file)
a Append only (creates file if not exists)
r+ Read and write (file must exist)
w+ Read and write (creates or truncates file)
a+ Read and append (creates file if not exists)

2️⃣ Writing to a File (fwrite)


 

w mode overwrites existing content.


3️⃣ Appending to a File (a Mode)


 


4️⃣ Reading a File (fread)


 


5️⃣ Reading a File Line by Line (fgets)


 


6️⃣ Reading a File into an Array (file())


 


7️⃣ Deleting a File (unlink)


 


8️⃣ Checking if a File Exists (file_exists)


 


9️⃣ File Upload Example

HTML Form:


 

PHP Script (upload.php):


 


🏁 Summary

  • Use fopen(), fread(), fwrite(), fclose() for basic file operations.

  • a mode appends data; w mode overwrites.

  • file() reads file into array; fgets() reads line by line.

  • Always check with file_exists() before reading or deleting.

  • unlink() deletes a file.

  • File upload requires enctype="multipart/form-data" in the form.

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 *