i have a strange problem with Curl in php.
I make a POST request on an API with postman. I have an answer. I had generated the php code with Postman ( show below ).
But with php, no response. ( that work good with another POST request ).
/Applications/MAMP/htdocs/*******/functions.php:108:string '' (length=0)
Do you have any idea ?
function get_id($immat){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://****.******.fr/*****.do",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 100,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "recherche=******&undefined=",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
"Origin: https://*********.fr",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
"X-Requested-With: XMLHttpRequest",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
var_dump($response);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
var_dump($response);
}
}
my best guess is that you're encoding CURLOPT_POSTFIELDS wrong. do you remember to encode every @
as %40
? do you remember to encode every space to %20
? do you remember to encode every &
as %26
? i guess the answer is no. make use of either urlencode() or http_build_query() (in addition to making sure everything is encoded correctly, the code usually ends up being much prettier too if ported properly to http_build_query())
nitpicking:
don't set the User-Agent
header manually, set CURLOPT_USERAGENT instead (setting the header manually won't play well with CURLOPT_FOLLOWLOCATION, and it's easy to forget to set it on subsequent requests... just as a rule of thumb, use CURLOPT_USERAGENT instead.)
don't use CURLOPT_CUSTOMREQUEST for POST requests, set CURLOPT_POST=>1
- CURLOPT_CUSTOMREQUEST is dangerous because it's not automatically cleared (unlike CURLOPT_POST) and must be manually set to NULL after you're done using it, and when programmers forget to clean CURLOPT_CUSTOMREQUEST, bugs often occur (like subsequent requests using the wrong request type)
when using application/x-www-form-urlencoded
or multipart/form-data
-formats specifically, don't set the Content-Type
header manually, let curl set the header automatically, so remove this "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"
(for the first, libcurl has automated testsuites running to ensure that there are no typos in the header, unlike your own codebase, and for the latter format you may mess up the boundary header)
"Accept: */*"
is the default libcurl header anyway, so you can remove it if you want to, it makes no difference (and could make the typos argument here too)