用PHP发布并获得结果

时间:2012-03-01 15:28:16

标签: php post libcurl

在PHP页面中,我正在尝试将一些数据发布到另一个PHP页面并获取数据。

以下是我目前的情况:

<?php 
// Initialize cURL session
$ch = curl_init('postpage.php');

// Set some options on the session
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('field1' => 'Andrew'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute post
$result = curl_exec($ch);

var_dump($result);

// Close the session
curl_close($ch);
?>

并在postpage.php中:

<?php
echo 'Receipt of post request. field1:'.$_POST["field1"];
?>

所有var_dump给我的是:

string(0) "" 

为什么我没有收回文本?

谢谢!

2 个答案:

答案 0 :(得分:6)

从您的php脚本执行的curl不知道当前环境,也就是说,您不能使用相对URL。您提供给curl_init的网址必须是绝对的(即包括http://)

答案 1 :(得分:2)

如果这确实是您正在进行的实际初始化,则错误可能在curl_init()的参数中,该参数需要完全限定的URL。

此外,您可能希望使用一些错误诊断。失败时curl_exec会返回FALSE。可以使用curl_error()确定原因:

$ch = curl_init( ... );
// ... some curl_setopt()
$result = curl_exec($ch);

if ($result === FALSE)
{
    die("cURL error: " . curl_error($ch));
}