W3docs

Alternative to file_get_contents?

file_get_contents() is a built-in PHP function that is commonly used to read the contents of a file into a string.

file_get_contents() is a built-in PHP function that is commonly used to read the contents of a file into a string. An alternative to this function is using the fopen() and fread() functions.

Example:

Example of using the fopen() and fread() functions as a file_get_contents() alternative in PHP

<?php

// Open the file for reading
$file = fopen("file.txt", "r");

// Check if the file was successfully opened
if ($file) {
  // Get the size of the file in bytes
  $file_size = filesize("file.txt");

  // Read the contents of the file
  $contents = fread($file, $file_size);

  // Output the contents of the file
  echo $contents;

  // Close the file
  fclose($file);
} else {
  // If the file could not be opened, output an error message
  echo "Error: Could not open the file for reading.";
}

?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

Another alternative is using the file() function, which reads the entire file into an array, with each element representing a line of the file.

Example:

Example of using the file() function as a file_get_contents() alternative in PHP

<?php

// Read the contents of the file into an array, where each line is an element in the array
$lines = file("file.txt");

// Loop through the array and output each line
foreach ($lines as $line) {
  // Output the line (file() already includes line endings)
  echo $line;
}

And also a modern approach is enhancing file_get_contents() with stream_context_create() to add custom headers or options.

Example of using stream_context_create() to configure file_get_contents() in PHP

<?php
// Define custom HTTP headers
$options = [
  'http' => [
    'method' => "GET",
    'header' => "Accept-language: en\r\n" . "Cookie: foo=bar\r\n",
  ],
];

// Create a stream context with the custom headers
$context = stream_context_create($options);

// Make an HTTP GET request to a URL that returns data and pass in the stream context
$response = file_get_contents('http://jsonplaceholder.typicode.com/posts', false, $context);

// Output the response
echo $response;
?>

It's up to you to choose which one suits your needs best.