Php

Working with File Systems

Why Work with the File System?

You can:

  • Store data without a database

  • Handle uploads

  • Manage logs, configuration files, or user-generated content


️ Common File Operations in PHP

1. Opening a File

php
$file = fopen("example.txt", "r"); // "r" = read mode
Mode Description
r Read-only
w Write (truncates file)
a Append
x Create new, fail if exists
r+ Read/write

2. Reading a File

php
$file = fopen("example.txt", "r");

while (!feof($file)) {
echo fgets($file); // Read line by line
}

fclose($file); // Close after use


3. Writing to a File

php
$file = fopen("example.txt", "w"); // Overwrites existing content
fwrite($file, "Hello, file system!");
fclose($file);

Or appending:

php
$file = fopen("example.txt", "a"); // Adds to end of file
fwrite($file, "\nThis is a new line.");
fclose($file);

4. Reading the Entire File at Once

php
$content = file_get_contents("example.txt");
echo $content;

5. Writing a Whole File

php
file_put_contents("example.txt", "Quick write");

Directory Operations

✅ Create a Directory

php
mkdir("newFolder");

✅ Check if File/Folder Exists

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

✅ Delete a File or Directory

php
unlink("example.txt"); // Delete a file
rmdir("newFolder"); // Delete empty folder

File Upload Example

HTML Form:

html
<form action="upload.php" method="POST" enctype="multipart/form-data">
Select file: <input type="file" name="myFile">
<input type="submit" value="Upload">
</form>

PHP (upload.php):

php
if ($_FILES["myFile"]["error"] === 0) {
move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $_FILES["myFile"]["name"]);
echo "File uploaded successfully!";
} else {
echo "Upload failed!";
}

Best Practices

  • Always check file_exists() before reading or writing.

  • Use fclose() to release system resources.

  • Use htmlspecialchars() when displaying file content in the browser.

  • Validate and sanitize file uploads to prevent security risks.

Leave a Reply

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