使用curl和php发送POST数据

4

你好。

我在亚马逊EC2上运行Fedora Core 8。我安装了httpd、php5和libcurl以及其他一些东西。看起来一切都很好,但后来我意识到我的php脚本中curl没有发送POST数据。然而,在命令行中相同的请求却可以工作。我还在本地机器(Win XP)和另一台远程机器(Ubuntu)上运行了相同的php脚本,它们运行良好,POST数据被发送了,但在FC8上却没有。它需要特殊配置吗?是否有防火墙问题?

以下是PHP代码:

error_reporting(E_ALL);
$ch = curl_init("http://foller.me/tmp/postdump.php");
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "something=somewhere");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);

$response = curl_exec($ch);

echo $response;
curl_close($ch); 

这是相应的curl命令:
curl -d "something=somethingelse" http://foller.me/tmp/postdump.php

我在apache error_log中找到了相应的条目,以下是我的翻译:
* About to connect() to foller.me port 80 (#0)
*   Trying 75.101.138.148... * connected
* Connected to foller.me (75.101.138.148) port 80 (#0)
> GET /tmp/postdump.php HTTP/1.1
Host: foller.me
Accept: */*

< HTTP/1.1 200 OK
< Date: Tue, 07 Jul 2009 10:32:18 GMT
< Server: Apache/2.2.9 (Fedora)
< X-Powered-By: PHP/5.2.6
< Content-Length: 31
< Connection: close
< Content-Type: text/html; charset=UTF-8
< 
* Closing connection #0

POST数据没有被发送,看到了吗?有什么想法吗?
谢谢大家提前帮忙。 ~ K.
3个回答

8

看起来这将请求从POST变为GET:

curl_setopt($ch, CURLOPT_NOBODY, 0);

删除那一行代码,它就能正常工作。

CURLOPT_NOBODY

非零参数告诉库在输出中不包含正文部分。这仅适用于具有单独标头和正文部分的协议。


我已经找了4个小时了。哈哈!非常感谢你 =) - kovshenin

1

虽然我不是这个领域的专家,但我有自己的工作代码,其工作方式略有不同。也许这可以帮助到您。

// Open the cURL session
    $curlSession = curl_init();

    // Set the URL
    curl_setopt ($curlSession, CURLOPT_URL, $url);

它首先执行curl_init(),然后设置URL,稍后...

$rawresponse = curl_exec($curlSession);

我不确定,但或许在设置 URL 之后会有所不同……?


感谢你的尝试,David,但不幸的是它并没有改变什么。虽然它在我另外两台机器上可以工作,但在我想要的地方却不能,呵呵。 - kovshenin
是的,我刚刚读了手册,我之前的回答真是垃圾!抱歉,我无法提供帮助。 - Dave Archer
curl_setopt($curlSession, CURLOPT_POST, 1)怎么样?可以代替'true'。这又是我从自己的复制粘贴代码中猜测的。 - Dave Archer
不,那应该没关系。 - kovshenin

0

我也看到了这篇文章,其中建议将帖子字段作为数组而不是字符串发送


那我也无能为力了,再次抱歉。 - Dave Archer
没问题,我已经找了大约4个小时的答案;)感谢你的努力。 - kovshenin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接