Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SoapClient(): send "User-Agent" and "Accept" HTTP Header

Due to a firewall audit, requests must always have the "UserAgent" and "Accept" header.

I tried this:

$soapclient = new soapclient('http://www.soap.com/soap.php?wsdl',
    array('stream_context' => stream_context_create(
        array(
            'http'=> array(
                'user_agent' => 'PHP/SOAP',
                'accept' => 'application/xml')
            )
        )
    )
);

the request received by the server soap

GET /soap.php?wsdl HTTP/1.1
Host: www.soap.com
User-Agent: PHP/SOAP
Connection: close

the expected result

GET /soap.php?wsdl HTTP/1.1
Host: www.soap.com
Accept application/xml
User-Agent: PHP/SOAP
Connection: close

Why "Accept" has not been sent? "User-Agent" works!

like image 204
ar099968 Avatar asked Apr 29 '14 07:04

ar099968


2 Answers

The SoapClient constructor will not read all of the stream_context options when generating the request headers. However, you can place arbitrary headers in a single string in a header option inside http:

$soapclient = new SoapClient($wsdl, [
    'stream_context' => stream_context_create([
        'user_agent' => 'PHP/SOAP',
        'http'=> [
            'header' => "Accept: application/xml\r\n
                         X-WHATEVER: something"               
        ]
    ])
]);

For setting more than one, separate them by \r\n.

(As mentioned by Ian Phillips, the "user_agent" can be placed either at the root of the stream_context, or inside the "http" part.)

like image 153
alepeino Avatar answered Sep 22 '22 13:09

alepeino


According to the PHP SoapClient manual page, user_agent is a top-level option. So you should modify your example like so:

$soapclient = new SoapClient('http://www.soap.com/soap.php?wsdl', [
    'stream_context' => stream_context_create([
        'http' => ['accept' => 'application/xml'],
    ]),
    'user_agent' => 'My custom user agent',
]);
like image 33
Ian Phillips Avatar answered Sep 20 '22 13:09

Ian Phillips