Search code examples
phpjsonslimslim-3

PHP can't get json from local page, only remote url


I'm currently building a site using the Slim framework. I have an endpoint setup on my site and it is working but when trying to get it using PHP file_get_contents() and json_decode() nothing is returned. When I run the same code but change out the url to a remote public API, the json is decoded and output to the page.

Working Code

$url = "https://jsonplaceholder.typicode.com/users";
$contents = file_get_contents($url); 
$results = json_decode($contents); // Returns JSON array

Does not work with local site

$url = "https://local/api/endpoint";
$contents = file_get_contents($url); 
$results = json_decode($contents); // Returns NULL

Any ideas on what could be causing this? Possibly headers?


Solution

  • Your local endpoint is failing because php is unable to verify the SSL certificate, in the case you are using a self signed certificate. In local development you can circumvent SSL CA checking by modifying the default stream context:

    $stream_opts = [
        "ssl" => [
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ]
    ];  
    $response = file_get_contents("https://local/api/endpoint",
               false, stream_context_create($stream_opts));