W3docs

Get file content from URL?

To get the contents of a file from a URL in PHP, you can use the file_get_contents function.

To get the contents of a file from a URL in PHP, you can use the file_get_contents function. This function reads data from a file or URL, and returns it as a string.

Here's an example of how you can use file_get_contents to retrieve the contents of a file from a URL:

How to get the file content from a URL in PHP?

<?php

$url = 'https://jsonplaceholder.typicode.com/posts/1';
echo 'Fetching contents from URL: ' . $url ;
$contents = file_get_contents($url);

if ($contents === false) {
    echo 'Failed to fetch contents.';
} else {
    // Do something with $contents...
}

The $contents variable will now contain the contents of the file as a string.

It's important to note that this function can only be used to retrieve files that are accessible over HTTP or HTTPS, and the allow_url_fopen directive must be enabled in your php.ini configuration. If you need to retrieve a file from a different protocol (such as FTP or SFTP), you will need to use a different method.

You can also specify additional options when calling file_get_contents, such as the number of bytes to read or the offset at which to start reading the file. You can also pass a stream context created with stream_context_create(); see the optional $context argument on the file_get_contents reference page:

$context = stream_context_create([
    'http' => [
        'timeout' => 5,
    ]
]);
// offset and maxlen are passed as the 4th and 5th arguments to file_get_contents
$contents = file_get_contents($url, false, $context, 0, 1024);

For complex HTTP requests, cURL or Guzzle are often preferred in modern PHP applications.