PHP File handling


File handling in PHP involves reading from and writing to files on the server. PHP provides a set of functions for manipulating files, allowing you to perform operations like creating, opening, reading, writing, and deleting files. Here’s a comprehensive overview of file handling in PHP:

Basic File Operations

1. Opening a File

You use fopen() to open a file and obtain a file handle. The file handle is then used in other file operations.

Syntax:

$fileHandle = fopen(string $filename, string $mode);
  • $filename: The path to the file.
  • $mode: The mode in which to open the file (e.g., r, w, a).

Example:

<?php $fileHandle = fopen("example.txt", "r"); // Open file for reading if ($fileHandle) { echo "File opened successfully."; } else { echo "Failed to open file."; } ?>

2. Reading from a File

Once a file is opened, you can read its contents using functions like fread(), fgets(), or file_get_contents().

  • fread(): Reads a specified number of bytes from a file.

    Example:

    <?php $fileHandle = fopen("example.txt", "r"); $content = fread($fileHandle, filesize("example.txt")); // Read the entire file fclose($fileHandle); echo $content; ?>
  • fgets(): Reads a single line from a file.

    Example:

    <?php $fileHandle = fopen("example.txt", "r"); while (($line = fgets($fileHandle)) !== false) { echo $line . "<br>"; } fclose($fileHandle); ?>
  • file_get_contents(): Reads the entire file into a string.

    Example:

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

3. Writing to a File

You can write to a file using fwrite() or file_put_contents().

  • fwrite(): Writes a string to a file.

    Example:

    <?php $fileHandle = fopen("example.txt", "w"); fwrite($fileHandle, "Hello, World!"); fclose($fileHandle); ?>
  • file_put_contents(): Writes data to a file. It is a simpler way to write data to a file and can also create the file if it does not exist.

    Example:

    <?php file_put_contents("example.txt", "Hello, World!"); ?>

4. Appending to a File

To add data to the end of a file without overwriting its existing content, use the a mode in fopen().

Example:

<?php $fileHandle = fopen("example.txt", "a"); fwrite($fileHandle, "Appended text."); fclose($fileHandle); ?>

5. Closing a File

After performing file operations, close the file using fclose() to free up system resources.

Example:

<?php $fileHandle = fopen("example.txt", "r"); // Perform file operations fclose($fileHandle); // Close the file ?>

File Handling Functions

  • file_exists($filename): Checks if a file or directory exists.

    Example:

    <?php if (file_exists("example.txt")) { echo "File exists."; } else { echo "File does not exist."; } ?>
  • filesize($filename): Returns the size of a file in bytes.

    Example:

    <?php echo "File size: " . filesize("example.txt") . " bytes."; ?>
  • fopen() Modes:

    • r - Read-only. Opens the file for reading.
    • w - Write-only. Opens the file for writing (creates a new file or truncates an existing file).
    • a - Append-only. Opens the file for writing (appends data to the end).
    • x - Write-only. Creates a new file, returns false if file already exists.

Error Handling

When working with files, always check if file operations are successful and handle errors gracefully.

Example:

<?php $fileHandle = @fopen("example.txt", "r"); if (!$fileHandle) { die("Failed to open file."); } $content = fread($fileHandle, filesize("example.txt")); fclose($fileHandle); echo $content; ?>

File Uploads

To handle file uploads in PHP, use the $_FILES superglobal array. The form must use multipart/form-data encoding.

Example HTML Form:

<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileToUpload"> <input type="submit" value="Upload File"> </form>

Example PHP Script (upload.php):

<?php $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // Check if file already exists if (file_exists($targetFile)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size (limit: 5MB) if ($_FILES["fileToUpload"]["size"] > 5000000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if ($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // If everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) { echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>