PHP - Cannot access external URLs

2019-02-26 00:53发布

问题:

I have recently upgraded my website's servers due to high amounts of traffic. On the new servers, some aspects of PHP seem to be broken. I have a very specific code that isn't working. However, due to copyright reasons, I can only show the non-confidential equivalent to you:

<?php
echo file_get_contents('http://www.google.com');
?>

This code worked absolutely flawlessly before the upgrade, and now some odd setting here or there has prevented this code for working.

To be specific, the file_get_contents function doesn't work at all, regardless of what external URL you put in (file_get_contents('index.php') works fine);

Any help is appreciated!

UPDATE #1
This code does not work either:

<?php
ini_set("allow_url_fopen", "On");
echo file_get_contents('http://www.google.com');
?>

UPDATE #2
This code works...

<?php
    ini_set("allow_url_fopen", "On");
    $url = "http://www.google.com/";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    echo $data;
?>

... but if I try to do simplexml_load_file($data); bad things happen. Same if I do simplexml_load_file('http://www.google.com')...

回答1:

Try CURL instead.

$url = "http://google.com/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

The contents will be stored in $data.



回答2:

First check file_get_contents return value. If the value is FALSE then it could not read it. If the value is NULL then the function itself is disabled.



回答3:

You could throw in headers

reference file-get-contents

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

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


回答4:

I found the answer but the credit goes to Krasi;

I used CURL and then used simplexml_load_string($data);

Thanks for all of your help