PHP-based cURL Quick Start 2

Source: Internet
Author: User
PHP-based cURL Quick Start 2? When a GET request is initiated using the POST method, data can be transmitted to a URL through the querystring method. For example, when searching in google, the search key is part of the query string for the URL: http://www.google.com PHP-based cURL Quick Start 2

?

Use the POST method to send data

When a GET request is initiated, data can be transmitted to a URL through the query string. For example, when searching in google, the search key is part of the query string of the URL:

Http://www.google.com/search? Q = nettuts

In this case, you may not need cURL to simulate it. You can get the same result by throwing this URL to "file_get_contents.

However, some HTML forms are submitted using the POST method. When such a form is submitted, the data is sent through the HTTP request body instead of the query string. For example, when using the CodeIgniter Forum form, no matter what keyword you enter, it is always POST to the following page:

Http://codeigniter.com/forums/do_search/

You can use PHP scripts to simulate such URL requests. First, create a new file that accepts and displays POST data. we name it post_output.php:

print_r($_POST);
?

Next, write a PHP script to execute the cURL request:

Reference content is as follows:

$ Url = "http: // localhost/post_output.php"; $ post_data = array ("foo" => "bar", "query" => "Nettuts ", "action" => "Submit"); $ ch = curl_init (); curl_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); // we are posting data! Curl_setopt ($ ch, CURLOPT_POST, 1); // add the post variable to curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data); $ output = curl_exec ($ ch ); curl_close ($ ch); echo $ output;
?


After the code is executed, the following results are returned:



This script sends a POST request to post_output.php. The $ _ POST variable on this page is returned. we captured this output using cURL.

File Upload

The uploaded file is very similar to the previous POST. Because all file upload forms are submitted through the POST method.

First, create a page for receiving files, named upload_output.php:

Print_r ($ _ FILES );

The following is a script for executing a file Upload task:

Reference content is as follows:

$ Url = "http: // localhost/upload_output.php"; $ post_data = array ("foo" => "bar ", // address of the local file to be uploaded: "upload" => "@ C:/wamp/www/test.zip"); $ ch = curl_init (); curl_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ ch, CURLOPT_POST, 1); curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data ); $ output = curl_exec ($ ch); curl_close ($ ch); echo $ output;
?


If you need to upload a file, you only need to pass the file path like a post variable, but remember to add the @ symbol before it. Execute this script and you will get the following output:


CURL batch processing (multi cURL)

CURL also has an advanced feature, handle ). This feature allows you to open multiple URL connections simultaneously or asynchronously.

The following is the sample code from php.net:

Reference content is as follows:
// Create two cURL Resources $ scheme = curl_init (); $ ch2 = curl_init (); // specify the URL and the appropriate parameter curl_setopt ($ scheme, CURLOPT_URL, "http://lxr.php.net/"); curl_setopt ($ scheme, CURLOPT_HEADER, 0); curl_setopt ($ ch2, CURLOPT_URL, "http://www.php.net/"); curl_setopt ($ ch2, CURLOPT_HEADER, 0 ); // Create a cURL batch processing handle $ mh = curl_multi_init (); // add the first two resource handles curl_multi_add_handle ($ mh, $ handle); curl_multi_add_handle ($ mh, $ ch2 ); // predefine a state variable $ active = null; // execute batch do { $ Mrc = curl_multi_exec ($ mh, $ active);} while ($ mrc = CURLM_CALL_MULTI_PERFORM); while ($ active & $ mrc = CURLM_ OK) {if (curl_multi_select ($ mh )! =-1) {do {$ mrc = curl_multi_exec ($ mh, $ active);} while ($ mrc = CURLM_CALL_MULTI_PERFORM );}} // close each handle curl_multi_remove_handle ($ mh, $ handle); curl_multi_remove_handle ($ mh, $ ch2); curl_multi_close ($ mh );

?


Here, you need to open multiple cURL handles and assign them to a batch processing handle. Then you just need to wait for it to be executed in a while loop.

There are two main loops in this example. The first do-while loop repeatedly calls curl_multi_exec (). This function is non-blocking, but will be executed as little as possible. It returns a status value. as long as the value is equal to the constant CURLM_CALL_MULTI_PERFORM, it indicates that there is still some urgent work to be done (for example, sending the http header information of the corresponding URL ). That is to say, we need to call this function continuously until the return value changes.

The next while loop continues only when the $ active variable is true. This variable was previously passed to curl_multi_exec () as the second parameter, which indicates that as long as there is any active connection in the batch handle. Next, we call curl_multi_select (), which is "blocked" before an active connection (for example, server response reception) occurs. After this function is successfully executed, we will go to another do-while loop and continue the next URL.

Let's take a look at how to use the feature:

WordPress connection checker

Imagine that you have a blog with a large number of articles that contain a large number of external website links. After a period of time, due to such reasons, a considerable number of these links are invalid. Either it is being harmonious, or the whole site is being attacked by Kung Fu...

Next we will create a script to analyze all these links, find websites/webpages that cannot be opened or 404, and generate a report.

Please note that the following is not a truly available WordPress plug-in. it is just a script with independent functions. it is only for demonstration. thank you.

Okay. let's get started. First, read all these links from the database:

Reference content is as follows:

// CONFIG $ db_host = 'localhost'; $ db_user = 'root'; $ db_pass = ''; $ db_name = 'wordpress'; $ excluded_domains = array ('localhost ', 'www .mydomain.com '); $ max_connections = 10; // initialize some variables $ url_list = array (); $ working_urls = array (); $ dead_urls = array (); $ not_found_urls = array (); $ active = null; // Connect to MySQLif (! Mysql_connect ($ db_host, $ db_user, $ db_pass) {die ('could not connect: '. mysql_error ();} if (! Mysql_select_db ($ db_name) {die ('could not select db :'. mysql_error ());} // find all articles with links $ q = "SELECT post_content FROM wp_postsWHERE post_content LIKE '% href = %' AND post_status = 'Publish 'AND post_type = 'post '"; $ r = mysql_query ($ q) or die (mysql_error (); while ($ d = mysql_fetch_assoc ($ r) {// if (preg_match_all ("! Href = \"(.*?) \"! ", $ D ['post _ content'], $ matches) {foreach ($ matches [1] as $ url) {// exclude some domains $ tmp = parse_url ($ url); if (in_array ($ tmp ['host'], $ excluded_domains) {continue ;} // store the url $ url_list [] = $ url ;}}// remove the duplicate link $ url_list = array_values (array_unique ($ url_list); if (! $ Url_list) {die ('No URL to check ');}

?



We first configure the database, a series of domain names to be excluded ($ excluded_domains), and the maximum number of concurrent connections ($ max_connections ). Then, connect to the database, obtain the articles and links, and collect them into an array ($ url_list ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.