PHP File Handling

Read, write and upload files.

✍️ 2 exercises in this lesson
  • file_put_contents($file, $data): write a file (add FILE_APPEND to append).
  • file_get_contents($file): read a whole file.
  • file($file): read lines into an array.
  • file_exists(), unlink() (delete), mkdir()
  • fopen(), fgets(), fwrite(), fclose() for line-by-line work on big files.

Uploaded files arrive in $_FILES; move them with move_uploaded_file() after checking size and type.

Key Takeaways: PHP File Handling

Mastering PHP File Handling helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP File Handling Code Example

PHP
<?php
$file = "notes.txt";
file_put_contents($file, "Line 1\n");
file_put_contents($file, "Line 2\n", FILE_APPEND);

echo nl2br(file_get_contents($file));
echo "Lines: " . count(file($file)) . "<br>";

unlink($file);
var_dump(file_exists($file));
Output
Line 1
Line 2
Lines: 2
bool(false)
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP File Handling Practice Exercises

Check what you learned in “PHP File Handling”.

/ 2 solved
Fill in the blank

Read a whole file into a string.

$text = ("notes.txt");
✓ Correct! Not quite. Try again.
Multiple choice

Which function deletes a file?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services