PHP File Open/Read/Close

In PHP, you can open, read, and close a file using built-in functions like fopen(), fread(), and fclose(). Here's a basic example:

Example: Open, Read, and Close a File in PHP

// File path $filename = "example.txt";
// Open the file for reading ("r" = read-only) $file = fopen($filename, "r");
// Check if file opened successfully if ($file) {
// Read the entire file $contents = fread($file, filesize($filename));
// Display contents echo $contents;
// Close the file fclose($file); } else { echo "Error: Unable to open the file."; } ?>

Explanation:

  • fopen($filename, "r"): Opens the file in read-only mode.

  • fread($file, filesize($filename)): Reads the entire content.

  • fclose($file): Closes the file to free up resources.