I am building a rest api server and I am trying to send Content-Md5 header in curl request to api server. I am confused on How to calculate md5 hash to send in the request for post and put? We will not need that header for GET and Delete right?
You won't need to supply the header for any request that does not include a body. This means that in practice, assuming a simple CRUD API, you will only need to worry about it for PUT
and POST
requests, GET
and DELETE
won't need to include it.
The MD5 hash to include is calculated (in PHP) by passing the request body, in its entirety, through the md5()
function. When using cURL, this means that you must construct the request body as a string manually - you can no long pass an array to CURLOPT_POSTFIELDS
.
Lets imagine I want to send the following array to the server:
$array = array(
'thing' => 'stuff',
'other thing' => 'more stuff'
);
If I want to POST it as JSON, I would do something like this:
$body = json_encode($array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($body),
'Content-MD5: ' . base64_encode(md5($body, true))
));
// ...
Similarly if I wanted to send it as application/x-www-form-urlencoded
, I would just change the json_encode()
to http_build_query()
and change the Content-Type:
header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With