This article mainly introduces how PHP uses CURL to simulate logon to websites with verification codes, which can help readers better understand and apply CURL operations, you can refer to a lot of simulated login programs on the internet. most of them run through the service program apache. after obtaining the verification code, they are displayed on the webpage, and then fill it in and POST it out, this may seem friendly, but since simulated logon does not necessarily take a short time to complete the tasks after logon, it is subject to the maximum execution time limit of php, in addition, some operations may have insufficient permissions.
Token verification code, and then carry the verification code to log on. The code is as follows:
/*** Simulate logon * // Initialization variable $ cookie_file = "tmp. cookie"; $ login_url =" http://xxx.com/logon.php "; $ Verify_code_url =" http://xxx.com/verifyCode.php "; Echo" obtaining COOKIE... \ n "; $ curlj = curl_init (); $ timeout = 5; curl_setopt ($ curl, CURLOPT_URL, $ login_url); curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ($ curl, CURLOPT_CONNECTTIMEOUT, $ timeout); curl_setopt ($ curl, CURLOPT_COOKIEJAR, $ cookie_file); // Obtain the COOKIE and store $ contents = curl_exec ($ curl ); curl_close ($ curl); echo "the COOKIE is obtained. the verification code is being obtained... \ n "; // Retrieve the verification code $ curl = curl_init (); curl_setopt ($ curl, CURLOPT_URL, $ Verify_code_url); curl_setopt ($ curl, CURLOPT_COOKIEFILE, $ cookie_file); curl_setopt ($ curl, CURLOPT_HEADER, 0); curl_setopt ($ curl, expires, 1 ); $ img = curl_exec ($ curl); curl_close ($ curl); $ fp = fopen ("verifyCode.jpg", "w"); fwrite ($ fp, $ img ); fclose ($ fp); echo "the verification code is obtained and completed. it is waiting for sleep. please enter the verification code in code.txt for 20 seconds and save it"; // stop running for 20 seconds sleep (20); echo "sleep complete, start to get the verification code... \ n "; $ code = file_get_contents (" code.txt "); echo" verification code retrieved successfully: $ Code \ n "; echo" preparing to simulate logon... \ n "; $ post =" username = maben & pwd = hahahaha & verifycode = $ code "; $ curl = curl_init (); curl_setopt ($ curl, CURLOPT_URL, $ url ); curl_setopt ($ curl, CURLOPT_HEADER, false); curl_setopt ($ curl, expires, 1); curl_setopt ($ curl, CURLOPT_POSTFIELDS, $ post); curl_setopt ($ curl, CURLOPT_COOKIEFILE, $ cookie_file); $ result = curl_exec ($ curl); curl_close ($ curl); // Determine if (s) based on the data on the website obtained from the packet capture. Ubstr_count ($ result, "logon succeeded") {echo "logon succeeded \ n" ;}else {echo "logon failed \ n"; exit ;}// OK, start with what you want to do .....