【问题标题】:Emulating form POST with php cURL, headers ignored?用php cURL模拟表单POST,忽略标题?
【发布时间】:2020-08-25 17:48:01
【问题描述】:

我正在尝试使用 PHP cURL 向 ymlp.com 发送简报注册请求

一个 html 表单可以很好地与此代码配合使用(我正在使用 ptsv2.com 来测试 POST):

<form method="post" action="http://ptsv2.com/t/stacktest/post?id=abcdefghijk">
  <input class="text" size="20" name="EMA0" type="text" placeholder="Type your email..." />
  <input class="submit" value="Subscribe to Newsletter" type="submit" />
</form>

所以我尝试使用以下代码在 PHP cURL 请求中模仿此代码:

<?php
$cURLConnection = curl_init('http://ptsv2.com/t/stacktest/post?id=abcdefghijk');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURLConnection, CURLINFO_HEADER_OUT, true);    
curl_setopt($cURLConnection, CURLOPT_POST, true);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, ['EMA0' => 'deleteme@gmail.com']);
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
$response = curl_exec($cURLConnection);
curl_close($cURLConnection);

请求已收到,但 html 表单的帖子内容类型显示为“application/x-www-form-urlencoded”,而 cURL 帖子内容类型为“multipart/form-data;边界=------------b9f916145e7d51d3'。

在表单中idEMA0 都显示为参数,而在cURL 帖子中id 显示为参数,而EMA0 显示为多部分值。

我是否正确地向 cURL 提供了标头?

我的 cURL 代码还有其他错误吗?

谢谢

【问题讨论】:

  • 看看stackoverflow.com/questions/5224790/…,看看http_build_query()是否有帮助。
  • CURLOPT_POST 将创建 application/x-www-form-urlencoded 请求。如果您将Array 传递给CURLOPT_POSTFIELDS,它会将请求更改为multipart/form-data,因此您应该使用http_build_query(['EMA0' =&gt; 'deleteme@gmail.com']) 也许...
  • 如果您正在设置标题(此处不需要),您还必须包含要设置的标题的 name - 即Content-Type: application/x-www-form-urlencoded['Content-Type' =&gt; 'application/x-www-form-urlencoded'].

标签: php curl post


【解决方案1】:

基于 Curl documentation 关于CURLOPT_POSTFIELDS

此参数可以作为 urlencoded 字符串传递,例如 'para1=val1&para2=val2&...' 或以字段名称为键的数组 和字段数据作为值。如果 value 是一个数组,则 Content-Type 标头 将设置为 multipart/form-data。

因此,您应该将帖子字段作为字符串传递(可能通过使用 http_build_query 函数)以具有 application/x-www-form-urlencoded 内容类型。 p>

因此不需要设置标题,只需:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['EMA0'=>1]));

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 2013-02-14
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多