Search code examples
phpcurlphp-curl

Cant echo anything after cURL in PHP


I have a curl that works fine. The file where the cURL is placed is a PHP file, executed by .ajax

I am echoing an $apikey at the end of the PHP file, without the cURL script. it prints correctly.

However, as soon as I put the cURL the $apikey stops printing the

$ch = curl_init("https://url");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer $apikey",
"Content-Type: application/json; charset=utf-8",
"Content-Length: " . strlen($data_string)
));

$json = curl_exec($ch);
curl_close($ch); //close the connection

echo $apikey;

if I remove the curl_init line the $apikey is printed correctly.

I was thinking that somehow the cURL result was blocking anything executing after that, but realized that also $json is not printing if I try.

I have tried using also curl_setopt($ch, CURLOPT_VERBOSE, false); but no difference. Couldn't find anything helpful here either.

Any idea of what might be the problem?

UPDATE The Ajax piece

$.ajax({
 url: "curl.php",
 method: "POST",
 data: {
    date: date,
    time: time,
    account: account,
    userid: userid
 },
 success: function(response) {
    console.log(response);
    alert(response);    
 }
});

Solution

  • From the comments / chat it would appear the root cause of the issue was that your AJAX call was never really working because a form was submitting at the same time and causing a page refresh. So removing this form submit will cause the button simply to fire the AJAX request and nothing else. Then everything works as intended. cURL is not at fault.