Students who are not familiar with CURL, please go to: http://www.BkJia.com/kf/201208/147091.html
When making a GET request, data can be passed to a URL via a "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
You may not need cURL to simulate in this case. Throwing this URL to "file_get_contents()" will get the same result.
However, some HTML forms are submitted using the POST method. When this 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 keywords you enter, you will always be POSTed to the following page:
http://codeigniter.com/forums/do_search/
You can use PHP script to simulate this URL request. First, create a new file that can accept and display POST data. We name it post_output.php:
print_r($_POST);
Next, write a PHP script to perform cURL requests:
$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
to the post variable
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
After executing the code you should get the following results:
This script sends a POST request to post_output.php, the $_POST variable of this page and returns it. We use cURL to capture this output.
File upload
Uploading files is very similar to the previous POST. Because all file upload forms are submitted through the POST method.
First create a new page for receiving files, named upload_output.php:
print_r($_FILES);
The following is the script that actually performs the file upload task:
$url = "http://localhost/upload_output.php";
$post_data = array (
"foo" => "bar",
//The 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, just pass the file path like a post variable, but remember to add the @ symbol in front. Executing this script should result in the following output: