Chinaunix

标题: 使用curl 模拟登录 discuz 程序 [打印本页]

作者: 到处流浪的猫    时间: 2009-07-14 01:51
标题: 使用curl 模拟登录 discuz 程序
  1. <?php   
  2. /**   
  3. * Curl 模拟登录 discuz 程序   
  4. * 尚未实现开启验证码的的论坛登录功能   
  5. * @author lvyaozu([url]http://www.lvyaozu.com[/url])   
  6. */   
  7.    
  8. !extension_loaded('curl') && die('The curl extension is not loaded.');   
  9.    
  10. $discuz_url = 'http://localhost/discuz7';//论坛地址   
  11. $login_url = $discuz_url .'/logging.php?action=login';//登录页地址   
  12. $get_url = $discuz_url .'/my.php?item=threads'; //我的帖子   
  13.    
  14. $post_fields = array();   
  15. //以下两项不需要修改   
  16. $post_fields['loginfield'] = 'username';   
  17. $post_fields['loginsubmit'] = 'true';   
  18. //用户名和密码,必须填写   
  19. $post_fields['username'] = 'admin';   
  20. $post_fields['password'] = '123456';   
  21. //安全提问   
  22. $post_fields['questionid'] = 0;   
  23. $post_fields['answer'] = '';   
  24. //@todo验证码   
  25. $post_fields['seccodeverify'] = '';   
  26.    
  27. //获取表单FORMHASH   
  28. $ch = curl_init($login_url);   
  29. curl_setopt($ch, CURLOPT_HEADER, 0);   
  30. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
  31. $contents = curl_exec($ch);   
  32. curl_close($ch);   
  33. preg_match('/<input\s*type="hidden"\s*name="formhash"\s*value="(.*?)"\s*\/>/i', $contents, $matches);   
  34. if(!empty($matches)) {   
  35.     $formhash = $matches[1];   
  36. } else {   
  37.     die('Not found the forumhash.');   
  38. }   
  39.    
  40. //POST数据,获取COOKIE   
  41. $cookie_file = dirname(__FILE__) . '/cookie.txt';   
  42. //$cookie_file = tempnam('/tmp');   
  43. $ch = curl_init($login_url);   
  44. curl_setopt($ch, CURLOPT_HEADER, 0);   
  45. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
  46. curl_setopt($ch, CURLOPT_POST, 1);   
  47. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);   
  48. curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);   
  49. curl_exec($ch);   
  50. curl_close($ch);   
  51.    
  52. //带着上面得到的COOKIE获取需要登录后才能查看的页面内容   
  53. $ch = curl_init($get_url);   
  54. curl_setopt($ch, CURLOPT_HEADER, 0);   
  55. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);   
  56. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);   
  57. $contents = curl_exec($ch);   
  58. curl_close($ch);   
  59.    
  60. var_dump($contents);   
  61. ?>  
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2