How to get file_get_contents() to work with HTTPS?

To get file_get_contents() to work with HTTPS, you may need to make sure that PHP has been compiled with the OpenSSL extension. You can check if the OpenSSL extension is enabled by using the phpinfo() function and looking for the OpenSSL section.

If the OpenSSL extension is not enabled, you will need to recompile PHP with the --with-openssl option.

Watch a course Learn object oriented PHP

If the OpenSSL extension is enabled, but you are still having trouble with file_get_contents() and HTTPS, there are a few other things you can try:

  1. Make sure that the server has a valid SSL certificate installed.
  2. Make sure that your version of PHP is compiled with the --with-curl option, as file_get_contents() can sometimes use cURL for HTTPS requests if it is available.
  3. Try specifying the ssl stream context option when calling file_get_contents(), like this:
<?php

$options = [
  'ssl' => [
    'verify_peer' => false,
    'verify_peer_name' => false,
  ],
];

$context = stream_context_create($options);

$url = 'https://jsonplaceholder.typicode.com/posts/1';
$response = file_get_contents($url, false, $context);

$data = json_decode($response, true);

echo 'Title: ' . $data['title'] . PHP_EOL;
echo 'Body: ' . $data['body'] . PHP_EOL;

This disables SSL certificate verification, which can be useful for testing purposes, but it is not recommended for production environments.