Do not know about CURL, please move: http://www.bkjia.com/kf/201208/147091.html
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:
$ 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
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:
$ 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: