https for stream_context_create - php

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.

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

Using an array as request headers in PHP

I'm trying to send a GET request to an API using PHP stream_context_create and file_get_contents.
I need to add API keys to the headers of my request, I'm storing these in an array so I easily edit them later and use them in multiple functions. What is a good way to include these arrays as headers?
In this case the key of the array would be the header keys and the value of the array the value of the header.
Some code to explain the problem
<?php
$api = array(
"X-Api-Id" => "id",
"X-Api-Key" => "key",
"X-Api-Secret" => "secret"
);
$options = array(
"http" => array(
"header" => "Content-type: application/x-www-form-urlencoded\r\n", // here I need to add the $api array
"method" => "GET"
)
);
return file_get_contents("example.com", FALSE, stream_context_create($options));
?>
Simply add the info to the header.
<?php
$api = [
'X-Api-Id' => 'id',
'X-Api-Key' => 'key',
'X-Api-Secret' => 'secret',
];
$headerData['Content-type'] = 'application/x-www-form-urlencoded';
$headerData = array_merge($headerData, $api);
array_walk($headerData, static function(&$v, $k) { $v = $k.': '.$v; });
$options = array(
'http' => [
'header' => implode("\n", $headerData),
'method' => 'GET'
]
);
return file_get_contents('example.com', FALSE, stream_context_create($options));
?>
To encode the data you can use http_build_query().
To add it to the header options you should be able to do something like:
$options = array(
"http" =>array(
'method' => 'POST', // GET in your case(?)
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($api)
)
);

Unable to connect to WSDL

I was working with older version of OpenSSL(OpenSSL 0.9.8o) and I was forced to use newer OpenSSL 1.0.1e-fips as the result I was unable to connect to WSDL:
Message: SoapClient::SoapClient(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
I need to disable SSL certification check, I tried:
$client = new SoapClient("https://IP:443/sdk/vimService?wsdl",
array(
"trace" => 1,
"location" => "https://IP:443/sdk/",
"stream_context" => stream_context_create(
array(
'ssl' => array(
'verify_peer' => false,
'allow_self_signed' => true,
)
)
)
)
);
`
And it throw:
Message: SoapClient::SoapClient(): Peer certificate CN=localhost.localdom' did not match expected CN=SAME IP AS IN SoapClient()'
Then I added 'peer_name'=> 'localhost.localdom', in stream_context and then it says XML file is empty:
Fatal error: Uncaught SoapFault exception: [Client] looks like we got no XML document
PHP 5.5
Okey, I was able to found issue.
You can avoid this mess using stable PHP 5.5 version
Recently I learned that error: "looks like we got no XML document" is caused because of PHP version - PHP 5.6 in 5.5 working like a charm.
How to fix it in PHP 5.6
1) Remove SSL certificate check in PHP 5.6:
In 5.6 version SSL certification was enabled by default, so if you want to disabled it you must pass context stream:
"stream_context" => stream_context_create(
array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
)
)
)
2) Deleted ?wsdl and added .wsdl instead (with ?wsdl, it didn't worke for me)
<?php
$client = new SoapClient("https://IP:443/sdk/vimService.wsdl",
array(
"trace" => 1,
"location" => "https://IP:443/sdk/",
'exceptions' => 1,
"stream_context" => stream_context_create(
array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
)
)
)
)
);
$soapmsg["_this"] = array( "_" => "ServiceInstance", "type" => "ServiceInstance");
$result = $client->RetrieveServiceContent($soapmsg);
$ServiceContent = $result->returnval;
$soapmsg = NULL;
$soapmsg["_this"] = $ServiceContent->sessionManager;
$soapmsg["userName"] = "USERNAME";
$soapmsg["password"] = "PASSWORD";
$result = $client->Login($soapmsg);
$UserSession = $result->returnval;
echo "User, " . $UserSession->userName . ", successfully logged in!\n";
$soapmsg = NULL;
$soapmsg["_this"] = $ServiceContent->sessionManager;
$result = $client->Logout($soapmsg);
In my case stream_context_create didn't worked.
So I download this file here : https://curl.haxx.se/ca/cacert.pem
and placed it in my localhost as : F:\xampp\apache\cert.pem
and gave the same path for
openssl.cafile=F:\xampp\apache\cert.pem in my phpini
This made the localhost to acquire certificate and things worked great...!!
Posting this in case this may help some one going through my situation.
In my case was needed to add the crypt_method
"stream_context" => stream_context_create(
array(
'ssl' => array(
'verify_peer' => true,
'verify_peer_name' => true,
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
)
)
)
In my case "stream_context" did the magic, i've just added the code :
`"stream_context" => stream_context_create(
array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
)
)
)`

How to disable redirects when doing a URLFetch in PHP for Google App Engine?

I'm trying to set up two PHP on GAE sites: One to act as a web services layer, and another to act as the front-end. So far, things are great. I'm trying to secure communications between these two layers, so that not only I can call my web services.
I found this article that talks about making requests, and by doing so, it can set the X-Appengine-Inbound-Appid header, which is exactly what I want.
https://developers.google.com/appengine/docs/php/urlfetch/#PHP_Making_requests
To do this, the article says I should "consider telling the UrlFetch service to not follow redirects when invoking it."; then promptly does not provide any documentation on how you actually DO that.
My request looks like this:
$data = ['data' => 'this', 'data2' => 'that'];
$data = http_build_query($data);
$context = [
'http' => [
'method' => 'get',
'header' => "custom-header: custom-value\r\n" . "custom-header-two: custome-value-2\r\n",
'content' => $data,
]
];
$context = stream_context_create($context);
$result = file_get_contents('urlgoeshere', false, $context);
Thoughts & help are appreciated!
Two ways, either set follow_location to false and/or max_redirects to 0.
$context = [
'http' => [
'method' => 'get',
'header' => "custom-header: custom-value\r\n" . "custom-header-two: custome-value-2\r\n",
'content' => $data,
'follow_location' => false,
]
];
or
$context = [
'http' => [
'method' => 'get',
'header' => "custom-header: custom-value\r\n" . "custom-header-two: custome-value-2\r\n",
'content' => $data,
'max_redirects' => 0,
]
];

PHP Soap call through https

i have a problem with running methods with SOAP. I'm using Apache and PHP.
this is the PHP code:
$opts = array(
'ssl' => array('ciphers'=>'RC4-SHA')
);
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$client = new SoapClient('https://host?wsdl', array (
'stream_context' => stream_context_create($opts),
"trace" => 1,
"exceptions" => 0,
"connection_timeout"=>2000));
var_dump($client->__getFunctions());
$params = array ("key" => "value");
$result = $client->availabeFunction($params);
var_dump($result);
The __getFunctions() It returns me all of the available functions.
Then when i'm trying to call the the available function with parameters.
It returns me a strage error message:
public 'faultstring' => string 'Could not connect to host' (length=25)
public 'faultcode' => string 'HTTP' (length=4)
So i presume it is for some reasons are connecting to through the HTTP, but not through HTTPS.
I've looked up the web, and in some cases they are using a local_cert value with a .pem file.
It it neccecity to have it? Or i'm missing something else?
It's an openssl library bug.
At first try to disable SSL check by adding this params
"stream_context" => stream_context_create(
array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
)
)
)
And next try to not use ?wsdl in location link, try use something like
.wsdl
The solution was much easier as i thoguht it will be:
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$location = 'https://host';
$client = new SoapClient($location . '?wsdl', array (
"trace" => 1,
"exceptions" => 0,
"connection_timeout"=>2000,
"location"=>$location // <- this was the reqiured parameter
));
Everything else is same as before.
This beeing cause by WSDL file configuration, that instead of https URL, it has http.

Https webservice php

Keep getting could not connect to host this is the server code that I have
<?php
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$soap_server = new SoapServer('Notification.wsdl');
$soap_server->addFunction('Notify');
function Notify($message)
{
return array('message' => $message);
}
$soap_server->handle();
?>
And this is my client code which is what is throwing the error. The endpoint is https. the wsdl file is local.
<?php
$context = stream_context_create(array(
'https' => array(
'cafile' => 'APX_WS_API1.cer',
'verify_peer' => true
)
));
$soap_client = new SoapClient('http://localhost:8888/Receiver/Notification.wsdl',
array('stream_context' => $context,'local_cer' => 'APX_WS_API1.cer'));
try{
$result = $soap_client->__soapCall('Notify',array('message' => 'Hello World'));
echo $result;
}catch(SoapFault $e){
echo "Error: " . $e->faultstring;
}
?>
Could someone please tell me what am i doing wrong. Thanks in advance
Is your certificate valid?
Try this option:
$context = stream_context_create(array(
'ssl' => array(
'verify_peer' => false,
'allow_self_signed' => true
)
));
If it works that means your cert is invalid.

Categories