《PHP學(xué)習(xí):php使用curl實(shí)現(xiàn)簡(jiǎn)單模擬提交表單功能》要點(diǎn):
本文介紹了PHP學(xué)習(xí):php使用curl實(shí)現(xiàn)簡(jiǎn)單模擬提交表單功能,希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
PHP編程php 使用curl 進(jìn)行簡(jiǎn)單模擬提交表單,供大家參考,具體內(nèi)容如下
PHP編程
//初始化curl
$ch = curl_init();
$url = 'xxx';
$option = [
CURLOPT_URL => $url,
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => 1,
];
curl_setopt_array($ch, $option);
$output = curl_exec($ch);
preg_match_all('/Set-Cookie: (.*);/i', $output, $str); //正則匹配
//如果有token的話(huà)就獲取token
preg_match('/token = \"(.*)\"/i', $output, $token);
if (empty($str)) {
return false;
}
$cook = $str[1];
$cookie = implode(';', $cook);
$up_url = 'xxx';
$post_data = [
'name' => 'test_',
'tel' => '18819271234',
'email' => 'qqhahadfdfads@163.com',
'message' => 'this is my message;',
'_token' => $token[1],
];
$options = [
CURLOPT_URL => $up_url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36",
CURLOPT_COOKIESESSION => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_COOKIE => $cookie
];
curl_setopt_array($ch, $options);
$res = curl_exec($ch);
// $info = curl_getinfo($ch);
if ($res === FALSE) {
p('curl Error: ' . curl_error($ch));
}
curl_close($ch);
p($res);
PHP編程取自基于laravel開(kāi)發(fā)的一個(gè)網(wǎng)站, laravel中表單中有一個(gè)csrf_token 的. 所以就得獲取token, 還有帶上cookie
PHP編程這里注意的是, 不能同時(shí)初始化兩個(gè)curl, 否則token或者cookie會(huì)發(fā)生變化, 如果你需要初始化兩個(gè)curl的話(huà), 可以使用CURLOPT_COOKIEJAR設(shè)置. [詳情看手冊(cè)]
PHP編程然后運(yùn)行下: binggo
PHP編程
PHP編程使用curl時(shí), 比較重要的就是一個(gè)cookie的應(yīng)用, 翻了下手冊(cè), 設(shè)置cookie的就有四個(gè)...CURLOPT_COOKIESESSION、CURLOPT_COOKIE、CURLOPT_COOKIEFILE、CURLOPT_COOKIEJAR
PHP編程以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持維易PHP.
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/801.html