php curl模擬登錄discuz並模擬發帖的實現方法

php curl好用,這個沒得說,jquery中文網以前提供的文章多是curl模擬登陸或僞造IP的,比如下面這幾篇:
php中通過curl smtp發送郵件的例子
有關php的curl_setopt函數相關應用及介紹
PHP中用CURL僞造IP來源的方法
php使用curl僞造IP來源的代碼
php模擬登錄qq郵箱(curl命令詳解)
curl命令模擬表單上傳文件

今天,爲大家介紹一個php curl模擬discuz發貼的代碼。


<?php
//link:http://www.jquerycn.cn
$discuz_url = 'http://127.0.0.1/discuz/';//論壇地址
$login_url = $discuz_url .'logging.php?action=login';//登錄頁地址

$post_fields = array();
//以下兩項不需要修改
$post_fields['loginfield'] = 'username';
$post_fields['loginsubmit'] = 'true';
//用戶名和密碼,必須填寫
$post_fields['username'] = 'tianxin';
$post_fields['password'] = '111111';
//安全提問
//link: http://www.jquerycn.cn
$post_fields['questionid'] = 0;
$post_fields['answer'] = '';
//@todo驗證碼
$post_fields['seccodeverify'] = '';

//獲取表單FORMHASH
$ch = curl_init($login_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
preg_match('/<input\s*type="hidden"\s*name="formhash"\s*value="(.*?)"\s*\/>/i', $contents, $matches);
if(!empty($matches)) {
    $formhash = $matches[1];
} else {
    die('Not found the forumhash.');
}

//POST數據,獲取COOKIE,cookie文件放在網站的temp目錄下
$cookie_file = tempnam('./temp','cookie');

$ch = curl_init($login_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_exec($ch);
curl_close($ch);

//取到了關鍵的cookie文件就可以帶着cookie文件去模擬發帖,fid爲論壇的欄目ID
$send_url = $discuz_url."post.php?action=newthread&fid=2";

$ch = curl_init($send_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
$contents = curl_exec($ch);
curl_close($ch);

//這裏的hash碼和登陸窗口的hash碼的正則不太一樣,這裏的hidden多了一個id屬性
preg_match('/<input\s*type="hidden"\s*name="formhash"\s*id="formhash"\s*value="(.*?)"\s*\/>/i', $contents, $matches);
if(!empty($matches)) {
    $formhash = $matches[1];
} else {
    die('Not found the forumhash.');
}

$post_data = array();
//帖子標題
$post_data['subject'] = 'test2';
//帖子內容
$post_data['message'] = 'test2';
$post_data['topicsubmit'] = "yes";
$post_data['extra'] = '';
//帖子標籤
$post_data['tags'] = 'test';
//帖子的hash碼,這個非常關鍵!假如缺少這個hash碼,discuz會警告你來路的頁面不正確
$post_data['formhash']=$formhash;

$ch = curl_init($send_url);
curl_setopt($ch, CURLOPT_REFERER, $send_url);       //僞裝REFERER
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$contents = curl_exec($ch);
curl_close($ch);

//清理cookie文件
unlink($cookie_file);
?>


發佈了4 篇原創文章 · 獲贊 50 · 訪問量 61萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章