I use following PHP function:
file_get_contents('http://example.com');
Whenever I do this on a certain server, the result is empty. When I do it anywhere else, the result is whatever the page's content may be. When I however, on the server where the result is empty, use the function locally - without accessing an external URL (file_get_contents('../simple/internal/path.html');
), it does work.
Now, I am pretty sure it has something to do with a certain php.ini configuration. What I am however not sure about is, which one. Please help.
is best for http url, But how to open https url help me
This will also give external links an absolute path without having to use php.ini
Add:
in your
php.ini
file. If you are using shared hosting, create one first.The is related to the ini configuration setting
allow_url_fopen
.You should be aware that enable that option may make some bugs in your code exploitable.
For instance, this failure to validate input may turn into a full-fledged remote code execution vulnerability:
The setting you are looking for is
allow_url_fopen
.You have two ways of getting around it without changing php.ini, one of them is to use
fsockopen()
, and the other is to use cURL.I recommend using cURL over
file_get_contents()
anyways, since it was built for this.The answers provided above solve the problem but don't explain the strange behaviour the OP described. This explanation should help anyone testing communication between sites in a development environment where these sites all reside on the same host (and the same virtualhost; I'm working with apache 2.4 and php7.0).
There's a subtlety with
file_get_contents()
I came across that is absolutely relevant here but unaddressed (probably because it's either barely documented or not documented from what I can tell or is documented in an obscure php security model whitepaper I can't find).With
allow_url_fopen
set toOff
in all relevant contexts (e.g./etc/php/7.0/apache2/php.ini
,/etc/php/7.0/fpm/php.ini
, etc...) andallow_url_fopen
set toOn
in the command line context (i.e./etc/php/7.0/cli/php.ini
), calls tofile_get_contents()
for a local resource will be allowed and no warning will be logged such as:or
or
To conclude, the restriction
allow_url_fopen = Off
is analogous to aniptables
rule in theOUTPUT
chain, where the restriction is only applied when an attempt to "exit the system" or "change contexts" is made.N.B.
allow_url_fopen
set toOn
in the command line context (i.e./etc/php/7.0/cli/php.ini
) is what I had on my system but I suspect it would have no bearing on the explanation I provided even if it were set toOff
unless of course you're testing by running your scripts from the command line itself. I did not test the behaviour withallow_url_fopen
set toOff
in the command line context.