PHP LogoFile Operations (Read, Write, Upload)

File operations are fundamental for most dynamic web applications, allowing PHP scripts to interact with the server's file system. This includes reading content from existing files, writing new content to files, and handling user-uploaded files.

1. Reading Files
Reading files involves retrieving data stored in text, configuration, or other data files. PHP offers several functions for this purpose:

* `fopen()` and `fread()`/`fgets()`: This is the traditional method. `fopen()` opens a file and returns a file pointer. The mode 'r' (read-only) is commonly used. `fread()` reads a specified number of bytes, while `fgets()` reads a single line until a newline character or EOF is reached. `fclose()` is crucial to close the file pointer and release system resources.
* `file_get_contents()`: A simpler function that reads the entire content of a file into a string. It's often preferred for smaller files or when the entire content is needed at once.

2. Writing Files
Writing files allows scripts to create new files or modify existing ones. Common functions include:

* `fopen()` and `fwrite()`: `fopen()` opens a file, typically in 'w' (write-only, truncates file to zero length or creates it if it doesn't exist) or 'a' (append, opens for writing at the end of the file, creates if it doesn't exist) mode. `fwrite()` writes a string to the file. Remember to `fclose()`.
* `file_put_contents()`: A straightforward function to write data to a file. It can overwrite existing content or append to it (using `FILE_APPEND` flag). If the file doesn't exist, it will attempt to create it.

3. Uploading Files
File uploading enables users to send files from their local machine to the server. This is a multi-step process:

* HTML Form: A specific HTML form structure is required. The form tag must have `enctype="multipart/form-data"` and include an `<input type="file" name="your_file_input_name">` element.
* PHP `$_FILES` Superglobal: When the form is submitted, PHP populates the `$_FILES` superglobal array with information about the uploaded file(s). This array contains details like the original file name, its temporary location on the server (`tmp_name`), file type (`type`), size (`size`), and any upload errors (`error`).
* `move_uploaded_file()`: This is the most critical function for file uploads. It securely moves the uploaded file from its temporary server location to a permanent destination you specify. It's vital to use this function as it performs checks to ensure the uploaded file is legitimate and safe to move.

Security and Error Handling
* Error Checking: Always check the return values of file functions (e.g., `fopen` returning `false`, `move_uploaded_file` returning `false`) and handle `$_FILES['your_file_input_name']['error']` codes to provide robust error messages.
* File Permissions: Ensure the PHP process has appropriate read/write permissions for the directories involved.
* Upload Security: For file uploads, always validate the file type (both MIME type and extension), limit file size, rename uploaded files to prevent name collisions or malicious script execution, and store uploaded files outside web-accessible directories if possible. Never trust user-provided filenames directly.

Example Code

```php
<?php

// --- 1. File Reading Examples ---

// Create a sample file for reading
file_put_contents('sample.txt', "This is line 1.\nThis is line 2.\nLast line.\n");

echo "<h3>File Reading:</h3>";

// Method 1: Using file_get_contents() to read the entire file
$filePath = 'sample.txt';
if (file_exists($filePath)) {
    $fileContent = file_get_contents($filePath);
    echo "<p><b>Content using file_get_contents():</b></p><pre>{$fileContent}</pre>";
} else {
    echo "<p>Error: {$filePath} not found.</p>";
}

// Method 2: Using fopen(), fgets(), and fclose() to read line by line
echo "<p><b>Content using fopen(), fgets(), fclose():</b></p><pre>";
$handle = fopen($filePath, 'r');
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo htmlspecialchars($line);
    }
    fclose($handle);
} else {
    echo "Error: Could not open {$filePath} for reading.";
}
echo "</pre>";


// --- 2. File Writing Examples ---

echo "<h3>File Writing:</h3>";

$newFilePath = 'output.txt';
$dataToWrite = "Hello, PHP!\nThis is new content written using PHP.\n";

// Method 1: Using file_put_contents() to write (overwrite or create)
if (file_put_contents($newFilePath, $dataToWrite) !== false) {
    echo "<p>Successfully wrote to '{$newFilePath}' (overwrote/created).</p>";
    echo "<pre>" . htmlspecialchars(file_get_contents($newFilePath)) . "</pre>";
} else {
    echo "<p>Error writing to '{$newFilePath}'.</p>";
}

// Method 2: Using file_put_contents() to append
$additionalData = "This line was appended.\n";
if (file_put_contents($newFilePath, $additionalData, FILE_APPEND) !== false) {
    echo "<p>Successfully appended to '{$newFilePath}'.</p>";
    echo "<pre>" . htmlspecialchars(file_get_contents($newFilePath)) . "</pre>";
} else {
    echo "<p>Error appending to '{$newFilePath}'.</p>";
}

// Method 3: Using fopen(), fwrite(), fclose() to write
$traditionalFilePath = 'traditional_output.txt';
$traditionalData = "This is content from traditional fwrite.\n";
$handle = fopen($traditionalFilePath, 'w'); // 'w' mode truncates if exists, creates if not
if ($handle) {
    fwrite($handle, $traditionalData);
    fclose($handle);
    echo "<p>Successfully wrote to '{$traditionalFilePath}' using fopen/fwrite.</p>";
    echo "<pre>" . htmlspecialchars(file_get_contents($traditionalFilePath)) . "</pre>";
} else {
    echo "<p>Error: Could not open '{$traditionalFilePath}' for writing.</p>";
}

// --- 3. File Upload Example ---

// This section requires an HTML form and a PHP script to process it.
// Let's assume this PHP code is in 'upload_handler.php'

echo "<h3>File Upload:</h3>";
echo "<p>To test file upload, save the following HTML as 'upload_form.html' and this PHP code as 'upload_handler.php' in the same directory.</p>";

echo "<h4>HTML Form (upload_form.html):</h4>";
echo "<pre><!DOCTYPE html>\n<html lang="en">\n<head>\n    <meta charset="UTF-8">\n    <title>File Upload</title>\n</head>\n<body>\n    <h2>Upload a File</h2>\n    <form action="upload_handler.php" method="post" enctype="multipart/form-data">\n        <label for="fileToUpload">Select file to upload:</label>\n        <input type="file" name="fileToUpload" id="fileToUpload">\n        <br><br>\n        <input type="submit" value="Upload File" name="submit">\n    </form>\n</body>\n</html></pre>";

echo "<h4>PHP Upload Handler (upload_handler.php):</h4>";

// Simulate the upload_handler.php script's logic
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['fileToUpload'])) {
    $targetDir = "uploads/"; // Directory where files will be stored
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true); // Create directory if it doesn't exist
    }

    $fileName = basename($_FILES["fileToUpload"]["name"]);
    $targetFile = $targetDir . $fileName;
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo "<p style='color:red;'>Sorry, file already exists.</p>";
        $uploadOk = 0;
    }

    // Check file size (e.g., 500KB limit)
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "<p style='color:red;'>Sorry, your file is too large.</p>";
        $uploadOk = 0;
    }

    // Allow certain file formats (basic example, be more restrictive in production)
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" && $imageFileType != "txt" && $imageFileType != "pdf") {
        echo "<p style='color:red;'>Sorry, only JPG, JPEG, PNG, GIF, TXT, & PDF files are allowed.</p>";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "<p style='color:red;'>Sorry, your file was not uploaded.</p>";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
            echo "<p style='color:green;'>The file ". htmlspecialchars($fileName). " has been uploaded to '{$targetDir}'.</p>";
        } else {
            echo "<p style='color:red;'>Sorry, there was an error uploading your file. Error code: " . $_FILES["fileToUpload"]["error"] . "</p>";
        }
    }
} else if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_FILES['fileToUpload'])) {
    echo "<p style='color:orange;'>No file was selected for upload.</p>";
} else {
    echo "<p>Please use the HTML form ('upload_form.html') to upload a file.</p>";
}

// Clean up sample files (optional)
// unlink('sample.txt');
// unlink('output.txt');
// unlink('traditional_output.txt');
// rmdir('uploads/'); // Be careful with rmdir, it only removes empty directories.

?>
```