Description

This function is similar to file(), except that
file_get_contents() returns the file in a
string, starting at the specified offset
up to maxlen bytes. On failure,
file_get_contents() will return FALSE.

file_get_contents() is the preferred way to read the
contents of a file into a string. It will use memory mapping techniques if
supported by your OS to enhance performance.

Note:

If you're opening a URI with special characters, such as spaces, you
need to encode the URI with urlencode().

Parameters

filename

Name of the file to read.

use_include_path

Note:

As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used
to trigger include path
search.

context

A valid context resource created with
stream_context_create(). If you don't need to use a
custom context, you can skip this parameter by NULL.

offset

The offset where the reading starts on the original stream.

Seeking (offset) is not supported with remote files.
Attempting to seek on non-local files may work with small offsets, but this
is unpredictable because it works on the buffered stream.

maxlen

Maximum length of data read. The default is to read until end
of file is reached. Note that this parameter is applied to the
stream processed by the filters.

Return Values

The function returns the read data or FALSE on failure.

Warning

This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.

Errors/Exceptions

An E_WARNING level error is generated if filename cannot be found, maxlength
is less than zero, or if seeking to the specified offset in the stream fails.

// Open the file using the HTTP headers set above$file = file_get_contents('http://www.example.com/', false, $context);?>

Changelog

Version

Description

5.1.0

Added the offset and
maxlen parameters.

Notes

Note: This function is
binary-safe.

Tip

A URL can be used as a
filename with this function if the fopen wrappers have been enabled.
See fopen() for more details on how to specify the
filename. See the Supported Protocols and Wrappers for links to information
about what abilities the various wrappers have, notes on their usage,
and information on any predefined variables they may
provide.

Warning

When using SSL, Microsoft IIS
will violate the protocol by closing the connection without sending a
close_notify indicator. PHP will report this as "SSL: Fatal
Protocol Error" when you reach the end of the data. To work around this, the
value of error_reporting should be
lowered to a level that does not include warnings.
PHP 4.3.7 and higher can detect buggy IIS server software when you open
the stream using the https:// wrapper and will suppress the
warning. When using fsockopen() to create an
ssl:// socket, the developer is responsible for detecting
and suppressing this warning.

A UTF-8 issue I've encountered is that of reading a URL with a non-UTF-8 encoding that is later displayed improperly since file_get_contents() related to it as UTF-8. This small function should show you how to address this issue:

Seems file looks for the file inside the current working (executing) directory before looking in the include path, even with the FILE_USE_INCLUDE_PATH flag specified.

Same behavior as include actually.

By the way I feel the doc is not entirely clear on the exact order of inclusion (see include). It seems to say the include_path is the first location to be searched, but I have come across at least one case where the directory containing the file including was actually the first to be searched.

I had a problem when trying to read information from a ttf, which is primarily hex data. A binary-safe file read automatically replaces byte values with their corresponding ASCII characters, so I thought that I could use the binary string when I needed readable ASCII strings, and bin2hex() when I needed hex strings.

However, this became a problem when I tried to pass those ASCII strings into other functions (namely gd functions). var_dump showed that a 5-character string contained 10 characters, but they weren't visible. A binary-to-"normal" string conversion function didn't seem to exist and I didn't want to have to convert every single character in hex using chr().

I used unpack with "c*" as the format flag to see what was going on, and found that every other character was null data (ordinal 0). To solve it, I just did

str_replace(chr(0), "", $string);

which did the trick.

This took forever to figure out so I hope this helps people reading from hex data!

This is an easy way to trigger scripts by listening for POSTs. I simply point a service's webhook url to the script, which file_get_contents("php://input"), cast to an array, and then simplexml_load_string() to parse it and use one of the keys' data as the parameter for my script.

here is another (maybe the easiest) way of doing POST http requests from php using its built-in capabilities. feel free to add the headers you need (notably the Host: header) to further customize the request.

If you want to insert tracking-scripts into your shopping-system, some scripts doesn't support intelligent detection of HTTPS, so i made a script i put on the server that rewrites 'http' to 'https' in the script, assuming everything has to be UTF-8 encoded (as a fallback it makes a redirect).

Use the previous example if you want to request the server for a special part of the content, IF and only if the server accepts the method.
If you want a simple example to ask the server for all the content, but only save a portion of it, do it this way:
<?php
$content=file_get_contents("http://www.google.com",FALSE,NULL,0,20);
echo $content;
?>

If working file is bigger than 64kb and you getting deadlock. Your buffer is overflow. Here are two way how to avoid that.
1) use temporary file for descriptor
<?php
$descriptorspec = array(
0 => array("file", "/tmp/ens/a.ens","r"), // stdin is a pipe that the child will read from
1 => array("file", "/tmp/ens/a.html","w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/ens/error-output.txt", "a") // stderr is a file to write to
);
?>

If your file_get_contents freezes during several seconds, here is maybe your answer:

Beware that the default keepalive timeout of Apache 2.0 httpd is 15 seconds. This is true for HTTP/1.1 connections, which is not the default behavior of file_get_contents but you can force it, especially if you are trying to act as a web browser. I don't know if this is also the case for HTTP/1.0 connections.

Forcing the server to close the connection would make you gain those 15 seconds in your script:

Another way of resolving slowness issues is to use cURL or fsockopen. Bear in mind that contrary to the behavior of web browsers, file_get_contents doesn't return the result when the web page is fully downloaded (i.e. HTTP payload length = value of the response HTTP "Content-Length" header) but when the TCP connection is closed.
I hope this behavior will change in future releases of PHP.
This has been experienced with PHP 5.3.3.

Python works a bit like PHP. Human readable code is handled without having to produce a compiled version. You DO have the opportunity of compiling the code (from a .py file to a .pyc file).

Once compiled, I installed this as a service (instsrv and srvany - parts of the Windows Resource Kit), so when the server is turned on (not logged in), the Python based NTLM Authentication Proxy Server is running.

Then, and here is the bit I'm really interested in, you need to tell PHP you intend to route http/ftp requests through the NTLM APS.

If you want to check if the function returned error, in case of a HTTP request an, it's not sufficient to test it against false. It may happen the return for that HTTP request was empty. In this case it's better to check if the return value is a bool.

Warning: file_get_contents(url): failed to open stream: HTTP request failed! in xx on line yy

If you are behind a SonicWall firewall, read this:https://bugs.php.net/bug.php?id=40197(this little line: uncheck a box in the internal settings of the firewall labled "Enforce Host Tag Search with for CFS")

Apparently by default SonicWall blocks any HTTP request without a "Host:" header, which is the case in the PHP get_file_contents(url) implementation.

This is why, if you try to get the same URL from the same machine with cURL our wget, it works.

I hope this will be useful to someone, it took me hours to find out :)

On Centos 5, and maybe other Red Hat based systems, any attempt to use file_get_contents to access a URL on an http port other than 80 (e.g. "http://www.example.com:8040/page") may fail with a permissions violation (error 13) unless the box you are running php on has its seLinux set to 'permissive' not 'enforcing' . Otherwise the request doesn't even get out of the box, i.e. the permissions violation is generated locally by seLinux.

Now you may use this code,to fetch the partial content like this:<?php$context=array('http' => array ('header'=> 'Range: bytes=1024-', ),);$xcontext = stream_context_create($context);$str=file_get_contents("http://www.fcicq.net/wp/",FALSE,$xcontext);?>that's all.

The funniest thing there is that seeking on non local files may, or may not work. This is unpredictable, and thus should throw rather than doing some magical stuff.Also trying to read non local file which doesn't exists results in FALSE returned and no single warning emitted.

Despite the comment about file_get_contents being faster do to memory mapping, file_get_contents is slowest in both of the above examples. If you need the best performance out of your production box, you might want to throw together a script to check out which method is fastest for what size files on that particular machine, then optimize your code to check the file size and use the appropriate function for it.