search
HomeBackend DevelopmentPHP TutorialPHP CURL simulated login to SINA Weibo


There is a need at work recently. I need to obtain the data of http://weibo.com/at/weibo, which is @myself's data. There is no interface and can only be obtained by grabbing the page. Here is some code From: http://summerbluet.com/704


  1. /**
  2. * Used to simulate Sina Weibo login! by CJ ( http://www.summerbluet.com )
  3. */
  4. /**Define project path*/
  5. define('PROJECT_ROOT_PATH' , dirname(__FILE__));
  6. define('COOKIE_PATH' , PROJECT_ROOT_PATH );
  7. // Universal timestamp
  8. define('TIMESTAMP', time());
  9. // Can be turned on when a problem occurs. For debugging, a LOG file will be created under the current folder
  10. define('DEBUG', false);
  11. /**Sina account used for simulated login*/
  12. $username = "";
  13. $password = "";
  14. /* Fire Up */
  15. $weiboLogin = new weiboLogin( $username, $password );
  16. exit($weiboLogin->showTestPage( 'http://weibo.com/at/comment' ));
  17. class weiboLogin {
  18. private $cookiefile;
  19. private $username;
  20. private $password;
  21. function __construct ( $username, $password )
  22. {
  23. ( $username =='' || $password=='' ) && exit( "Please fill in the username and password" );
  24. $this->cookiefile = COOKIE_PATH.' /cookie_sina_'.substr(base64_encode($username), 0, 10);
  25. $this->username = $username;
  26. $this->password = $password;
  27. }
  28. /**
  29. * CURL request
  30. * @param String $url request address
  31. * @param Array $data request data
  32. * /
  33. function curlRequest($url, $data = false)
  34. {
  35. $ch = curl_init();
  36. $option = array(
  37. CURLOPT_URL => $url,
  38. CURLOPT_HEADER => 0,
  39. CURLOPT_HTTPHEADER => array('Accept-Language: zh-cn','Connection: Keep-Alive','Cache-Control: no-cache'),
  40. CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1",
  41. CURLOPT_FOLLOWLOCATION => TRUE,
  42. CURLOPT_MAXREDIRS => 4,
  43. CURLOPT_RETURNTRANSFER => TRUE,
  44. CURLOPT_COOKIEJAR => $ this->cookiefile,
  45. CURLOPT_COOKIEFILE => option);
  46. $response = curl_exec($ch);
  47. if (curl_errno($ch) > 0) {
  48. exit("CURL ERROR:$url " . curl_error($ch));
  49. }
  50. curl_close( $ch);
  51. return $response;
  52. }
  53. /**@desc CURL simulates Sina login*/
  54. function doSinaLogin()
  55. {
  56. // Step 1: Get tickit
  57. $preLoginData = $this->curlRequest('http: //login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=' .
  58. base64_encode($this->username) . '&client=ssologin.js(v1.3.16)') ;
  59. preg_match('/sinaSSOController.preloginCallBack((.*))/', $preLoginData, $preArr);
  60. $jsonArr = json_decode($preArr[1], true);
  61. $this->debug(' debug_1_Tickit', $preArr[1]);
  62. if (is_array($jsonArr)) {
  63. // Step 2: Do Certification
  64. $postArr = array( 'entry' => 'weibo',
  65. 'gateway' = > 1,
  66. 'from' => '',
  67. 'vsnval' => '',
  68. 'savestate' => 7,
  69. 'useticket' => 1,
  70. 'ssosimplelogin' => 1 ,
  71. 'su' => base64_encode(urlencode($this->username)),
  72. 'service' => 'miniblog',
  73. 'servertime' => $jsonArr['servertime'],
  74. 'nonce ' => $jsonArr['nonce'],
  75. 'pwencode' => 'wsse',
  76. 'sp' => sha1(sha1(sha1($this->password)) . $jsonArr['servertime '] . $jsonArr['nonce']),
  77. 'encoding' => 'UTF-8',
  78. 'url' => 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent .sinaSSOController.feedBackUrlCallBack',
  79. 'returntype' => 'META');
  80. $loginData = $this->curlRequest('http://login.sina.com.cn/sso/login.php?client =ssologin.js(v1.3.19)', $postArr);
  81. $this->debug('debug_2_Certification_raw', $loginData);
  82. // Step 3: SSOLoginState
  83. if ($loginData) {
  84. $ matches = $loginResultArr =array();
  85. preg_match('/replace('(.*?)')/', $loginData, $matchs);
  86. $this->debug('debug_3_Certification_result', $matchs[ 1]);
  87. $loginResult = $this->curlRequest( $matchs[1] );
  88. preg_match('/feedBackUrlCallBack((.*?))/', $loginResult, $loginResultArr);
  89. $userInfo = json_decode($loginResultArr[1],true);
  90. $this->debug('debug_4_UserInfo', $loginResultArr[1]);
  91. } else {
  92. exit('Login sina fail.');
  93. }
  94. } else {
  95. exit('Server tickit fail');
  96. }
  97. }
  98. /**Test login situation, call reference*/
  99. function showTestPage( $url ) {
  100. $file_holder = $this->curlRequest( $url );
  101. // If not logged in, try again after logging in
  102. $isLogin = strpos( $file_holder, 'class="user_name"');
  103. if ( !$isLogin ){
  104. unset($file_holder);
  105. $this->doSinaLogin();
  106. $file_holder = $this->curlRequest( $url );
  107. }
  108. return $file_holder ;
  109. }
  110. /**debug*/
  111. function debug( $file_name, $data ) {
  112. if ( DEBUG ) {
  113. file_put_contents( $file_name.'.txt' , $data );
  114. }
  115. }
  116. }
Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function