开发者

What is wrong to this php code? file_get_contents replacement

$var1 = $_REQUEST['id'];
$var2 = file_get_contents('http://example.com/script.php?z=$var1');
echo $var2;
开发者_JAVA技巧

it seems that file_get_contents it is disabled.

with what i can replace file_get_contents to get this working?


You are using single quotes, which means $var1 isn't being substituted into the string. Even if you used double quotes, though, your query string still might not be escaped correctly.

You should use http_build_query to ensure that you are building a valid URL:

$url = 'http://example.com/script.php?' . http_build_query(array(
  'z' => $_REQUEST['id']
));

As Patrick's answer pointed out, if file_get_contents is disabled and issuing a warning, you may be able to enable it. If not, you can try to use cURL to make the request, like so:

$url = 'http://example.com/script.php?' . http_build_query(array(
  'z' => $_REQUEST['id']
));
$ch = curl_init();
curl_setopt_array($ch, array(
  CURLOPT_URL => $url,
  CURLOPT_HEADER => 0,
  CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
if ($result === false) {
  trigger_error(curl_error($ch));
} else {
  // do something with $result
}
curl_close($ch);


If you are getting an error message similar to:

Warning: file_get_contents() [function.file-get-contents]: URL file-access is disabled in the server configuration in...

Make a php.ini file with only the line:

allow_url_fopen = On


you need to use double quotes:

$var2 = file_get_contents("http://example.com/script.php?z=$var1");


That should work but I'm pretty sure you can't do variable substitution in strings (PHP name for it?) when using single quotes. Try it with double quotes or by doing something like 'http://example.com/script.php?z=' . $var1. Let me know if that does it for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜