curl 模拟POST方法 发送数据

用POST方法发送数据
当发起GET请求时,数据可以通过“查询字串”(query string)传递给一个URL。例如,在google中搜索时,搜索关键即为URL的查询字串的一部分:
http://www.google.com/search?q=nettuts
这种情况下你可能并不需要cURL来模拟。把这个URL丢给“file_get_contents()”就能得到相同结果。 
不过有一些HTML表单是用POST方法提交的。这种表单提交时,数据是通过 HTTP请求体(request body) 发送,而不是查询字串。例如,当使用CodeIgniter论坛的表单,无论你输入什么关键字,总是被POST到如下页面:
http://codeigniter.com/forums/do_search/
你可以用PHP脚本来模拟这种URL请求。首先,新建一个可以接受并显示POST数据的文件,我们给它命名为post_output.php:
print_r($_POST);
接下来,写一段PHP脚本来执行cURL请求:

以下为引用的内容:
$url = "http://localhost/post_output.php";
$post_data = array (
    "foo" => "bar",
    "query" => "Nettuts",
    "action" => "Submit"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // 时候将获取数据返回
// 我们在POST数据哦!
curl_setopt($ch, CURLOPT_POST, 1); //设置为POST传输
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //post过去数据
$output = curl_exec($ch);
if($output === false){  //判断错误
 echo curl_error($ch);
}

$info = curl_getinfo($ch);  //能够在cURL执行后获取这一请求的有关信息
curl_close($ch);
echo $output;
执行代码后应该会得到以下结果:
这段脚本发送一个POST请求给 post_output.php ,这个页面 $_POST 变量并返回,我们利用cURL捕捉了这个输出。

你可能感兴趣的:(curl 模拟POST方法 发送数据)