php curl實現模擬登陸,並獲取登陸頁的資訊。
<?php
/**
* --------------------------------
* Curl模擬登陸操作
* --------------------------------
* @author Corwien
* @version 2017-01
* --------------------------------
*/
//模擬登入
function login_post($url, $cookie, $post) {
$curl = curl_init();//初始化curl模組
curl_setopt($curl, CURLOPT_URL, $url);//登入提交的地址
curl_setopt($curl, CURLOPT_HEADER, 0);//是否顯示頭資訊
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);//是否自動顯示返回的資訊
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie); //設定Cookie資訊儲存在指定的檔案中
curl_setopt($curl, CURLOPT_POST, 1);//post方式提交
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));//要提交的資訊
curl_exec($curl);//執行cURL
curl_close($curl);//關閉cURL資源,並且釋放系統資源
}
// 登入成功後獲取資料
function get_content($url, $cookie) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 也可以copy cookie用curl_setopt($curl, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); //讀取cookie
$rs = curl_exec($ch); //執行cURL抓取頁面內容
curl_close($ch);
return $rs;
}
// 登入成功後模擬發帖
function post_thread($url, $cookie, $post)
{
$curl = curl_init();//初始化curl模組
curl_setopt($curl, CURLOPT_URL, $url);//登入提交的地址
curl_setopt($curl, CURLOPT_HEADER, 0);//是否顯示頭資訊
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);//是否自動顯示返回的資訊
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie); //讀取cookie
curl_setopt($curl, CURLOPT_POST, 1);//post方式提交
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));//要提交的資訊
curl_exec($curl);//執行cURL
curl_close($curl);//關閉cURL資源,並且釋放系統資源
}
//設定post的資料
$post = array (
`user_id` => `123456@qq.com`,
`password` => `123456`,
`goto_page` => `http://m.app.cn/index.php`,
`act` => `login`,
`t` => time(),
);
//登入地址
$url = "http://m.app.cn/account/login.php";
//設定cookie儲存路徑
$cookie = dirname(__FILE__) . `/cookie_curl.txt`;
//登入後要獲取資訊的地址
$url2 = "http://m.app.cn/user/wap/my_index.php";
// 1.模擬登入
login_post($url, $cookie, $post);
// 2.獲取登入頁的資訊
// $content = get_content($url2, $cookie);
//匹配頁面資訊
// $preg = "/<td class=`portrait`>(.*)</td>/i";
// preg_match_all($preg, $content, $arr);
// $str = $arr[1][0];
//輸出內容
// echo $content;
// 3.模擬發帖
$thread_info = array(
`action` => `pub`,
`title` => `Test curl`,
`content` => `Hello, world.`,
`t` => time(),
);
$pub_thread_url = `http://m.app.cn/thread/api/pub_thread.php`;
$ret = post_thread($pub_thread_url, $cookie, $thread_info);
print_r($ret);
//刪除cookie檔案
@ unlink($cookie);
?>