码迷,mamicode.com
首页 > Web开发 > 详细

curl 模拟get和post请求

时间:2015-02-12 12:27:08      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

首先,模拟get请求:

curlget.php

<?php 
$url='http://localhost/lianxi/curl/post.php?name=HZD';
$ch = curl_init();// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
$data=curl_exec($ch);
curl_close($ch);
$data=json_decode($data,TRUE);
var_dump($data);
?>
输出结果:

array (size=1)
  ‘name‘ => string ‘HZD‘ (length=3)


模拟post请求:

curlpost.php

<?php 
$curlPost=array(
	'name' => 'hzd',
	'school' => 'HS'
);
$urlpost='http://localhost/lianxi/curl/post.php';
$ch = curl_init();//初始化curl
curl_setopt($ch,CURLOPT_URL,$urlpost);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
$res1=json_decode($data, TRUE);
var_dump($res1);
?>
输出结果:

array (size=2)
  ‘name‘ => string ‘hzd‘ (length=3)
  ‘school‘ => string ‘HS‘ (length=2)


请求文件post.php

<?php 
$respdata=array();
if ($_POST) {
	$respdata['name']=$_POST['name'];
	$respdata['school']=$_POST['school'];
	echo json_encode($respdata);exit();
}
if ($_GET) {
	$respdata['name']=$_GET['name'];
	echo json_encode($respdata);exit();
}
$respdata['success']=0;
echo json_encode($respdata);exit();
?>




curl 模拟get和post请求

标签:

原文地址:http://blog.csdn.net/huang_zhidong/article/details/43760655

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!