有时候在做一些模拟登录的时候需要用到php的curl 来进行模拟,记录一下用到的几个例子
post 请求例子
function loginWithTokenReturn($loginurl){
$fields_string='{"name":"username951","password":"password","version":false}';
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $loginurl);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$res = curl_exec($ch);
$loginArr = json_decode($res,true);
if($loginArr['status'] == 6000){
$token = $loginArr['data']['token'] ;
}else{
$token='faed7e282abe0d9344608c1680b23e9210edc6ab4f73daba7b1dd9dbbdbfeec8cd5ccda22c61f74c2dc633d9c0b68f28';
}
return $token;
}
get请求例子
function getAffiliateLink($dataurl,$token){
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'x-api-token:'.$token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_URL, $dataurl);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
var_dump($output);
return $output;
}
$token = loginWithTokenReturn($loginurl);
getAffiliateLink($dataurl,$token);
转载请注明:创富者 » php 如何发生post 和get请求?记录几个demo