Phpcurl sends a post request. in many tasks, we may need to send a post request, but we do not need or do not want to use the interface form method. in this case, we can use the curl in php to simulate form submission.
First encapsulate a curl method
Private function curlExec ($ options) {$ ch = curl_init (); curl_setopt_array ($ ch, $ options); // return json string $ result = curl_exec ($ ch ); // check for any errors. if (curl_errno ($ ch) {$ error = "curl exec error! ". Curl_error ($ ch); $ result = array ("code" => "1005", "info" => $ error);} curl_close ($ ch ); return $ result ;}
Then there is a problem with parameter settings. the official documentation is a bit difficult to understand at the beginning. now I will describe it in detail:
For curl_setopt (), passing an array to CURLOPT_POST will encode the data in multipart/form-data mode, however, passing a URL-encoded string will encode the data in the form of application/x-www-form-urlencoded.
First, it is passed into $ post as an array, and CURLOPT_POST is not used in the configuration.
CURLOPT_POST=1
This parameter converts the multipart/form-data type to the application/x-www-form-urlencoded format,
The following example transmits a post request in the multipart/form-data format:
$post = array ('imagefile' => '@' . $uploadFilePath, 'configfile' => $data );$url = $this->cfg['baseUrl'].'/upload';$options = array ( CURLOPT_URL => $url, CURLOPT_POSTFIELDS => $post, CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_TIMEOUT => 28, CURLOPT_CONNECTTIMEOUT => $this::MAX_CONNECTION_TIME);
The URL-encoded method is to concatenate strings to pass the parameters.
If the post request is passed using application/x-www-form-urlencoded, you need to concatenate the parameters with strings, but not arrays.
If you are not at ease, set CURLOPT_POST = 1 under CURLOPT_POSTFIELDS = $ post,
Ensure that CONTENT_TYPE is always set to application/x-www-form-urlencoded.
Example:
$post = 'ids=123&name=aa';$url = 'http://localhost/Test/test.php';$options = array ( CURLOPT_URL => $url, CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_POSTFIELDS => $post, CURLOPT_POST=> 1, CURLOPT_TIMEOUT => 28, CURLOPT_CONNECTTIMEOUT => $this::MAX_CONNECTION_TIME,);
Another solution is to write head information by yourself,
For example
$options = array ( ... CURLOPT_HTTPHEADER= array('Content-Type: application/x-www-form-urlencoded'),);
If you need other headers, you can add them by yourself.