Home >Backend Development >PHP Tutorial >Using CURL to simulate login and obtain data instances in PHP_PHP tutorial
cURL is a powerful PHP library. Using PHP's cURL library can simply and effectively crawl web pages and collect content. Set cookies to simulate logging in to web pages. Curl provides a wealth of functions. Developers can learn from the PHP manual Get more information about cURL. This article takes simulated login to open source China (oschina) as an example to share with you the use of cURL.
PHP's curl() is relatively efficient in crawling web pages and supports multi-threading, while file_get_contents() is slightly less efficient. Of course, you need to enable the curl extension when using curl.
Code practice
Let’s look at the login code first:
The function login_post() first initializes curl_init(), and then uses curl_setopt() to set relevant option information, including the URL address to be submitted, the saved cookie file, post data (user name and password, etc.), whether to return information, etc. Wait, then curl_exec executes curl, and finally curl_close() releases the resources. Note that PHP's own http_build_query() can convert arrays into connected strings.
Next, if the login is successful, we need to obtain the page information after the login is successful.
The function get_content() also initializes curl first, then sets relevant options, executes curl, and releases resources. Among them, we set CURLOPT_RETURNTRANSFER to 1 to automatically return information, and CURLOPT_COOKIEFILE can read the cookie information saved when logging in, and finally return the page content.
Our ultimate goal is to obtain the information after simulated login, which is useful information that can only be obtained after successful normal login. Next, we take logging into the mobile version of Open Source China as an example to see how to capture the information after successful login.
After running the above code, we will see that the avatar image of the logged in user is finally obtained.
Usage summary:
1. Initialize curl;
2. Use curl_setopt to set the target url and other options;
3. curl_exec, execute curl;
4. After execution, close curl;
5. Output data.