本文主要是介绍curl 模拟get和post请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先,模拟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)
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)
<?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请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!