如何在php中生成post和put请求的Content-Md5头


How to generate Content-Md5 header of post and put request in php

我正在构建一个rest api服务器,我正试图在curl请求中向api服务器发送内容md5头。我对如何计算md5哈希发送post和put请求感到困惑?GET和Delete不需要标头?

您不需要为任何不包含正文的请求提供标题。这意味着在实践中,假设一个简单的CRUD API,您只需要为PUTPOST请求担心它,GETDELETE不需要包含它。

要包含的MD5哈希值(在PHP中)是通过传递请求体来计算的,整个请求体通过md5()函数。当使用cURL时,这意味着您必须手动将请求体构造为字符串—您不能再将数组传递给CURLOPT_POSTFIELDS

假设我想发送以下数组到服务器:

$array = array(
    'thing' => 'stuff',
    'other thing' => 'more stuff'
);

如果我想把它作为JSON发布,我会这样做:

$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))
));
// ...

同样,如果我想将其发送为application/x-www-form-urlencoded,我只需将json_encode()更改为http_build_query()并更改Content-Type:头。