Modifying PHP / SOAP code to add HTTP Header in all requests

11,744

Add a stream context to provide the additional headers to the HTTP call.

function soap_connect() {
    $context = array('http' =>
        array(
            'header'  => 'Authorization: WRAP access_token=Z-H7SnqL49eQ2Qp5pLH8k-RVxHfewgIIDt4VCeI2CNnrS4-gBMzPWbfZuMhgvISVV-uTSikS1SqO0n2PRkH3ysQ-uWbvU9podPAm6HiiIS5W2mtpXUfN9ErBmkjF6hDw'
        )
    );
    $soap_options = array(
        'soap_version' => SOAP_1_2,
        'encoding' => 'UTF-8',
        'exceptions' => FALSE,
        'stream_context' => stream_context_create($context)
    );
    try {
        $this->soap_client = new SoapClient($this->configuration['wsdl'], $soap_options);
    } catch (SoapFault $fault) {
        return FALSE;
    }
    return TRUE;
}

Please see SoapClient::__construct() and HTTP context options for further information,

Share:
11,744
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin almost 2 years

    I;ve inherited some php SOAP code and due to changes in the service we are using, I need to modify to "add an authorization in the HTTP headers of all requests". I'm not sure what to do and if its even possible.

    Part of the relevant code looks like this:

        function soap_connect() {
                $soap_options = array(
                        'soap_version' => SOAP_1_2,
                        'encoding' => 'UTF-8',
                        'exceptions' => FALSE
                );
                try {
                        $this->soap_client = new SoapClient($this->configuration['wsdl'], $soap_options);
                } catch (SoapFault $fault) {
                        return FALSE;
                }
                return TRUE;
        }
    

    I think, as I understand it, it should be just outputting the following (right now):

    Content-Type: application/soap+xml;charset=UTF-8;action="http://ws.testserver.net/nsp/client/hsserve/listHardware"
    Content-Length: 255
    ...
    

    The documentatino says that the final HTTP request should look like:

    Content-Type: application/soap+xml;charset=UTF-8;action="http://ws.testserver.net/nsp/client/hsserve/listHardware"
    Authorization: WRAP access_token=Z-H7SnqL49eQ2Qp5pLH8k-RVxHfewgIIDt4VCeI2CNnrS4-gBMzPWbfZuMhgvISVV-uTSikS1SqO0n2PRkH3ysQ-uWbvU9podPAm6HiiIS5W2mtpXUfN9ErBmkjF6hDw
    Content-Length: 255