Search code examples
phpjsonfile-get-contents

file_get_contents - failed to open stream: HTTP request failed


I am getting the following error when I am trying to pass url values into "file_get_content" :

file_get_contents(https://api.sandbox.amadeus.com/v1.2/flights/low-fare-search?origin=$origin&destination=$destination&departure_date=$departure_date&return_date=$return_date&number_of_results=$number_of_results&apikey=$apikey): failed to open stream: HTTP request failed! HTTP/1.1 401

I read different possible solutions, but none of them seemed to work in my case

$origin = $_GET['origin'];
$destination = $_GET['destination'];
$departure_date = $_GET['departure_date'];
$return_date = $_GET['return_date'];
$number_of_results = $_GET['number_of_results'];
$apikey = "sdflsdksdksdsdskd";

ini_set("allow_url_fopen", 1);

$json_url = file_get_contents('https://api.sandbox.amadeus.com/v1.2/flights/low-fare-search?origin=$origin&destination=$destination&departure_date=$departure_date&return_date=$return_date&number_of_results=$number_of_results&apikey=$apikey');

The result from the $json_url is a simple valid JSON Any help will be highly appreciated.

EDIT: The problem is not with the API Key, when I hard-code it, the error code is different (400 Bad Request), but still file_get_contents - failed to open stream: HTTP request failed


Solution

  • The problem is that your url is read literally due to '.
    If you use " then the variables in the string will be used as variables but now your string is '...apikey=$api' instead of '...apikey=sdflsdksdksdsdskd'

    So change the line

    $json_url = file_get_contents('https://api.sandbox.amadeus.com/v1.2/flights/low-fare-search?origin=$origin&destination=$destination&departure_date=$departure_date&return_date=$return_date&number_of_results=$number_of_results&apikey=$apikey');
    

    To

    $json_url = file_get_contents("https://api.sandbox.amadeus.com/v1.2/flights/low-fare-search?origin=$origin&destination=$destination&departure_date=$departure_date&return_date=$return_date&number_of_results=$number_of_results&apikey=$apikey");