欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php模拟远程登录示例代码

程序员文章站 2022-05-04 15:25:29
...
  1. !extension_loaded('curl') && die('the curl extension is not loaded.');
  2. $baseurl = 'http://127.0.0.1';//根地址
  3. $login_url = $baseurl .'/login.php?act=login';//登录页地址
  4. $get_url = $baseurl .'/index.php'; //需要采集的页面
  5. $post_fields = array();
  6. //以下两项需要修改
  7. $post_fields['name'] = 'admin';
  8. $post_fields['pass'] = '123456';
  9. //获取表单formhash
  10. $ch = curl_init($login_url);
  11. curl_setopt($ch, curlopt_header, 0);
  12. curl_setopt($ch, curlopt_returntransfer, 1);
  13. $contents = curl_exec($ch);
  14. curl_close($ch);
  15. //post数据,获取cookie
  16. $cookie_file = dirname(__file__) . '/cookie.txt';
  17. $ch = curl_init($login_url);
  18. curl_setopt($ch, curlopt_header, 0);
  19. curl_setopt($ch, curlopt_returntransfer, 1);
  20. curl_setopt($ch, curlopt_post, 1);
  21. curl_setopt($ch, curlopt_postfields, $post_fields);
  22. curl_setopt($ch, curlopt_cookiejar, $cookie_file);
  23. curl_exec($ch);
  24. curl_close($ch);
  25. //使用以上获取的cookie登录后才能查看的页面内容
  26. $ch = curl_init($get_url);
  27. curl_setopt($ch, curlopt_header, 0);
  28. curl_setopt($ch, curlopt_returntransfer, 0);
  29. curl_setopt($ch, curlopt_cookiefile, $cookie_file);
  30. $mycontents = curl_exec($ch);
  31. curl_close($ch);
  32. var_dump($mycontents);
复制代码