分享

!!!!! php 使用curl模拟登录discuz以及模拟发帖 | SimonLeung's Blo...

 看见就非常 2012-09-26

php的curl真的是相当好用,网上一搜索相关文章都是关于curl模拟登陆的,很少人提供模拟discuz发贴的源码。

本着共享的原则,我把自己测试成功的发帖代码贴出来。不足的地方,希望大家指正。

 
01 <div><?php
02 $discuz_url 'http://127.0.0.1/discuz/';//论坛地址
03 $login_url $discuz_url .'logging.php?action=login';//登录页地址
04  
05 $post_fields array();
06 //以下两项不需要修改
07 $post_fields['loginfield'] = 'username';
08 $post_fields['loginsubmit'] = 'true';
09 //用户名和密码,必须填写
10 $post_fields['username'] = 'tianxin';
11 $post_fields['password'] = '111111';
12 //安全提问
13 $post_fields['questionid'] = 0;
14 $post_fields['answer'] = '';
15 //@todo验证码
16 $post_fields['seccodeverify'] = '';
17  
18 //获取表单FORMHASH
19 $ch = curl_init($login_url);
20 curl_setopt($ch, CURLOPT_HEADER, 0);
21 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
22 $contents = curl_exec($ch);
23 curl_close($ch);
24 preg_match('/<input\s*type="hidden"\s*name="formhash"\s*value="(.*?)"\s*\/>/i'$contents$matches);
25 if(!empty($matches)) {
26  $formhash $matches[1];
27 else {
28  die('Not found the forumhash.');
29 }
30  
31 //POST数据,获取COOKIE,cookie文件放在网站的temp目录下
32 $cookie_file = tempnam('./temp','cookie');
33  
34 $ch = curl_init($login_url);
35 curl_setopt($ch, CURLOPT_HEADER, 0);
36 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
37 curl_setopt($ch, CURLOPT_POST, 1);
38 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
39 curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
40 curl_exec($ch);
41 curl_close($ch);
42  
43 //取到了关键的cookie文件就可以带着cookie文件去模拟发帖,fid为论坛的栏目ID
44 $send_url $discuz_url."post.php?action=newthread&fid=2";
45  
46 $ch = curl_init($send_url);
47 curl_setopt($ch, CURLOPT_HEADER, 0);
48 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
49 curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
50 $contents = curl_exec($ch);
51 curl_close($ch);
52  
53 //这里的hash码和登陆窗口的hash码的正则不太一样,这里的hidden多了一个id属性
54 preg_match('/<input\s*type="hidden"\s*name="formhash"\s*id="formhash"\s*value="(.*?)"\s*\/>/i'$contents$matches);
55 if(!empty($matches)) {
56  $formhash $matches[1];
57 else {
58  die('Not found the forumhash.');
59 }
60  
61 $post_data array();
62 //帖子标题
63 $post_data['subject'] = 'test2';
64 //帖子内容
65 $post_data['message'] = 'test2';
66 $post_data['topicsubmit'] = "yes";
67 $post_data['extra'] = '';
68 //帖子标签
69 $post_data['tags'] = 'test';
70 //帖子的hash码,这个非常关键!假如缺少这个hash码,discuz会警告你来路的页面不正确
71 $post_data['formhash']=$formhash;
72  
73 $ch = curl_init($send_url);
74 curl_setopt($ch, CURLOPT_REFERER, $send_url);       //伪装REFERER
75 curl_setopt($ch, CURLOPT_HEADER, 0);
76 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
77 curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
78 curl_setopt($ch, CURLOPT_POST, 1);
79 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
80 $contents = curl_exec($ch);
81 curl_close($ch);
82  
83 //清理cookie文件
84 unlink($cookie_file);
85  
86 ?></div>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约