Search code examples
phpxmlcurlsoapsigned

In PHP how to send signed xml as soap request using curl


The following curl command is working fine.

curl --header "Content-Type: application/soap+xml" --header "Accept: text/xml" --header "SOAPAction: ''" --data-binary @signedSoapRequest.xml http://server:8081/WebService

I am trying to replicate same from PHP using curl as shown below. But it fails with error code 403

    $message = <?xml version="1.0"....signed xml data...</SOAP-ENV:Envelope>
    $headers = array(
        "Content-type: text/xml;charset=\"utf-8\"",
        "Accept: text/xml",
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "SOAPAction: ''",
        "Content-length: ".strlen($message),
    );

    $result = array();

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_VERBOSE, false);
    curl_setopt($ch, CURLOPT_URL, $this->endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
    $result['soap_result'] = $this->cleanXML(curl_exec($ch));

If in $message I store a simple xml and not the signed xml data like below curls command. curl --header "Content-Type: application/soap+xml" --header "Accept: text/xml" --header "SOAPAction: ''" --data @SoapRequest.xml http://server:8081/WebService

For this curl coommand the PHP code works fine. As this curl command use --data flag which means a text file/data and not binary/signed data.

Any idea how it can work with signed xml also. I tried setting content-type: applicaton/octet-stream but same 403 error. (403)Forbidden


Solution

  • Code curl_setopt($ch, CURLOPT_POSTFIELDS, $message); replaced with curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('soapRequest.xml'))

    And it started working fine.

    Instead of specifying value of file in $message variable and then setting $message in CURLOPT_POSTFIELDS, now using file_get_contents() to read file and set CURLOPT_POSTFIELDS.

    Taken hint from PHP cURL: how to set body to binary data?