https for stream_context_create

Viewed 7406

Iam new to trying like this, I have trying to get the token with https in magento2, it not working here my code

<?php
$base_url="https://myurl.com/";
$domain="myurl.com";
$url = $base_url.'index.php/rest/V1/integration/admin/token';
$body = '{"username":"ApiUser", "password":"ApiPass"}';

$context_options = array (
        'https' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/json"
            'content' => $body
            ),
        'ssl' => array('SNI_enabled'=>true,'SNI_server_name'=> $domain)
        );

$context = stream_context_create($context_options);
$token = json_decode(file_get_contents($url, false, $context));
echo $token; echo "<br/>";
?>

Please help, thanks in advance.

2 Answers

Sorry for the super late reply, but was just looking for this solution as well, to use https URL instead of http.

FROM the PHP manual page/example, the context should not be https, but rather http.: http://php.net/manual/it/function.stream-context-create.php#74795

INCORRECT:

$context_options = array (
    'https' => array ()
)

CORRECT:

$context_options = array (
    'http' => array ()
)

of if you need more SSL options, this comment: http://php.net/manual/it/function.stream-context-create.php#110158

$contextOptions = array(
    'ssl' => array(
        'verify_peer'   => true,
        'cafile'        => __DIR__ . '/cacert.pem',
        'verify_depth'  => 5,
        'CN_match'      => 'secure.example.com'
    )
);

The simplest way to create stream context with stream_context_create when working in SSL environment is to omit verification! This works just fine for me when I want to retrieve data with file_get_contents:

stream_context_create([
    'http' => [ /* your options here - eg: */ 'method' => 'POST', ],
    // 'https' => 'DON'T forget there is no "https", only "http" like above',
    'ssl'  => [ // here comes the actual SSL part...
        'verify_peer'      => false,
        'verify_peer_name' => false,
    ]
]);

php.net/manual/en/context.ssl.php:

verify_peer boolean
Require verification of SSL certificate used.
Defaults to TRUE.

verify_peer_name boolean
Require verification of peer name.
Defaults to TRUE.

Related