PHP File Handling

📘 PHP 👁 34 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

What is File Handling in PHP?

PHP file handling allows you to create, read, write, update, and delete files on the server. It is commonly used for log files, data storage, file uploads, and configuration files.


File Handling Functions in PHP

Some commonly used PHP file functions are:

  • fopen()

  • fread()

  • fwrite()

  • fclose()

  • file()

  • file_get_contents()

  • file_put_contents()

  • unlink()


Opening a File – fopen()

The fopen() function opens a file in a specified mode.

Syntax:

fopen(filename, mode);

File Modes:

ModeDescription
rRead only
wWrite only (creates/overwrites)
aAppend
xCreate new file
r+Read & Write
w+Read & Write (overwrite)
a+Read & Append

Reading a File

Using fread()

$file = fopen("data.txt", "r"); echo fread($file, filesize("data.txt")); fclose($file);

Using fgets()

Reads one line at a time.

$file = fopen("data.txt", "r"); while (!feof($file)) { echo fgets($file) . "
"
; } fclose($file);

Using file_get_contents()

echo file_get_contents("data.txt");

Writing to a File

Using fwrite()

$file = fopen("data.txt", "w"); fwrite($file, "Hello PHP File Handling"); fclose($file);

Using file_put_contents()

file_put_contents("data.txt", "New Content");

Appending Data to a File

$file = fopen("data.txt", "a"); fwrite($file, "\nAppended Text"); fclose($file);

Creating a File

$file = fopen("newfile.txt", "x"); fclose($file);

Deleting a File

unlink("data.txt");

Checking File Existence

if (file_exists("data.txt")) { echo "File exists"; }

File Upload Handling

HTML Form

<form method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit"> </form>

PHP Code

<?php if (isset($_FILES['file'])) { move_uploaded_file( $_FILES['file']['tmp_name'], "uploads/" . $_FILES['file']['name'] ); } ?>

File Permissions

chmod("data.txt", 0644);

Security Tips for File Handling

  • Validate file types before upload

  • Limit file size

  • Use unique file names

  • Restrict upload directories

  • Never trust user input


Best Practices

  • Always close files after use

  • Check file existence before reading

  • Use file_get_contents() for small files

  • Handle errors properly


Conclusion

PHP file handling provides powerful tools to manage files efficiently. When used correctly with proper validation and security, it helps build reliable and scalable applications.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes