1. Home
  2. Docs
  3. Web Technology II
  4. File and Form Handling
  5. Reading a File in PHP

Reading a File in PHP

In PHP, reading a file means accessing its contents and retrieving data stored within it.

  • PHP provides various functions to read files, making it possible to access file data for displaying, processing, or performing specific operations.

The following built-in functions in PHP’s library can help us perform the read operation:

  • fgets() — Reads a single line from a file
  • fread() — Reads a specified number of bytes from a file
  • fgetc() — Reads a single character from a file
// Open the file
$file = fopen("example.txt", "r");
if ($file) {
    // Read each line one by one
    while (($line = fgets($file)) ! = = false) {
        echo $line . "<br>";
    }
    fclose($file);
} else {
    echo "Unable to open the file.";
}

This function is efficient for handling large files as it reads the file in specified chunks.

$file = fopen("example.txt", "r");
if ($file) {
    // Read file in 1024-byte chunks
    while (!feof($file)) {
        $chunk = fread($file, 1024);
        echo $chunk;
    }
    fclose($file);
} else {
    echo "Unable to open the file.";
}
$file = fopen("example.txt", "r");
if ($file) {
    // Read one character at a time
    while (($char = fgetc($file)) ! = = false) {
        echo $char;
    }
    fclose($file);
} else {
    echo "Unable to open the file.";
}

How can we help?

Leave a Reply

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