如何动态计算内容长度?

时间:2018-03-19 11:37:11

标签: php api https

这就是我在PHP中调用API的方式。为了使用它,我需要Content-Length。我不确定内容长度是多少,因为身体总是会根据我传递的变量而改变 - 我也可以在身体中添加额外的线条。在这种情况下,计算内容长度的最佳方法是什么?

$opts = array();
$opts = [
    "http" => [
            "method" => "POST",
            "header" => "Header1: xxx \r\n"  .
            "Header2: xxx \r\n"  .
            "Content-Length: ???", <---------???
            "body" => "FirstName: FirstName \r\n"  .
            "LastName: LastName \r\n"  .
            "AddressLine1: Ad1  \r\n"  .
            "AddressLine2: Ad2  \r\n"  .
            "AddressLine3: Ad3  \r\n"  .
            "AddressLine4: Ad4  \r\n"  .
            "AddressLine5: Ad5  \r\n"  .
            "Telephone: Telephone  \r\n"  .
            "EmailAddress: EmailAddress  \r\n"  .
            ]
        ];

$context = stream_context_create($opts);
$url = 'https://url.com/endpoint';
$file = file_get_contents($url, false, $context);

echo $file;

?>

1 个答案:

答案 0 :(得分:1)

我在https://www.sk89q.com/2010/04/introduction-to-php-streams找到了以下示例:

$postdata = array(
  'var1' => 'value1',
  'var2' => 'value2',
);

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => http_build_query($postdata, '', '&'),
    'timeout' => 5,
  )
);

$context = stream_context_create($opts);

echo file_get_contents("http://example.com", 0, $context);

这表明可能不需要内容长度。

如果我将此与第一个注释结合起来:http://php.net/manual/en/function.stream-context-create.php

我明白了:

$postdata = http_build_query(['var1' => 'value1',
                              'var2' => 'value2'],'','&'));

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n".
                 'Content-Length: '.strlen($postData)."\r\n",
    'content' => $postData,
    'timeout' => 5,
  )
);

$context = stream_context_create($opts);

echo file_get_contents("http://example.com", 0, $context);

这对你有用吗?我注意到你打电话给内容&#39;但这取决于你。