Home > Enterprise >  How do I return an error response from a XMLRPC server method in PHP?
How do I return an error response from a XMLRPC server method in PHP?

Time:12-11

If I use xmlrpc_server_call_method() in PHP, the resulting XML is generated for me. It works fine for regular responses, but let's say my method doesn't succeed (eg. post creation), how do I send a valid error response, like an error code?

Example:

function make_post($input) {
    
    // try to do a thing …
    
    if($post_created == true) {
        return $post_id;
    } else {
        // how do I trigger an actual error response?
        return false; // ?
    }
}

// set up a server
$server = xmlrpc_server_create();
xmlrpc_server_register_method($server, 'metaWeblog.newPost', 'make_post');

// fake a request
$request = xmlrpc_encode_request("metaWeblog.newPost", null, array('encoding' => 'utf-8'));

// call make_post()
$response = xmlrpc_server_call_method($server, $request, null, [
    'encoding' => 'utf-8'
]);

var_dump($response);

Output:

<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
<params>
 <param>
  <value>
   <boolean>0</boolean>
  </value>
 </param>
</params>
</methodResponse>

Expected: (or similar)

<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
    <fault>
        <value>
            <struct>
                <member>
                    <name>faultCode</name>
                    <value><int>4</int></value>
                </member>
                <member>
                    <name>faultString</name>
                    <value><string>Too many parameters.</string></value>
                </member>
            </struct>
        </value>
    </fault>
</methodResponse>

CodePudding user response:

Instead of false return array('faultCode' => 666, 'faultString' => 'DOH!') to have an xmlrpc fault response (with your own code and string naturally, 666 and 'DOH!' are just exemplary):

function make_post($input) {    
    // ...    
    if ($post_created) {
        return $post_id;
    }

    return array('faultCode' => 666, 'faultString' => 'DOH!');
}

You can verify such an array value as well with xmlrpc_is_fault(php) and that manual page also gives more description about that array:

Fault description is available in $arg["faultString"], fault code is in $arg["faultCode"].

  • Related