-2

I have been trying to get the html content from a webpage using file_get_contents(). It works perfectly on localhost but not on live server.

Some more information is as follows:

  • PHP version is 7+
  • http, https are included in Registered PHP Streams
  • allow_url_fopen is On
  • used cURL, but it redirects to some other page and uses my domain as the referrer.
  • executing this in the browser by putting the code in a php file
  • output of the below code on live server is false
$url = 'https://trafficsecrets.com/ts-free-book';

$context = stream_context_create(
    array (
        'http' => array (
            'method' => 'GET',
            'follow_location' => true,
            'max_redirects' => 5,
            'header' => array('User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201', ),
        ),
        "ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ),
    )
);
echo var_dump(file_get_contents($url, false, $context));

Why this code gives the html on localhost and not on the server?

user5955461
  • 746
  • 2
  • 8
  • 13

1 Answers1

0

Maybe try this to catch the error:

set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, $severity, $severity, $file, $line);
    }
);

try {
    file_get_contents($url, false, $context));
}
catch (Exception $e) {
    echo $e->getMessage();
}

restore_error_handler();

Source: How can I handle the warning of file_get_contents() function in PHP?

Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11
  • Got this error: `file_get_contents(https://trafficsecrets.com/ts-free-book): failed to open stream: HTTP request failed! HTTP/1.1 503 Service Temporarily Unavailable` – user5955461 Aug 11 '20 at 07:44
  • @user5955461 Maybe the destination has (temporarily?) blacklisted the server's IP. – kmoser Aug 11 '20 at 14:44