How to delete the return of curl_init php?

Asked

Viewed 491 times

1

This same function I put in another question for another reason, in this question I want to delete the text that $result returns:

...    
$fields = http_build_query($data);
$post = curl_init();

$url = $url . '?' . $fields;
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, 1);
curl_setopt($post, CURLOPT_RETURNTRANSFER, false);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);

$result = curl_exec($post);

curl_close($post);

It turns out that the REST on the server where I do not have direct access, always returns a message (string) beyond true and false, I needed to delete this message because it disturbs me in the construction of the html I need to show the user...

I tried curl_setopt($post, CURLOPT_RETURNTRANSFER, false);

But it didn’t work, I’m starting to use this curl_init now

What I need is simply to know if $result is true or false

1 answer

2


Use the curl_setopt($post, CURLOPT_RETURNTRANSFER, 1) so that the result of the request is not shown or curl_setopt($ch, CURLOPT_NOBODY, 1) if the body of the answer is insignificant.

To find out if the request was successful or not, you can add the curl_setopt($ch, CURLOPT_FAILONERROR, 1) so that the $result be it false if HTTP Code is >= 400. However, HTTP Code is 300 it will not follow the request, add the CURLOPT_FOLLOWLOCATION if need be.

To then compare make a $result !== false:

$fields = http_build_query($data);
$post = curl_init();

$url = $url . '?' . $fields;
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, 1);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);

// Acrescentado:
curl_setopt($post, CURLOPT_FAILONERROR, 1)
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1)
curl_setopt($post, CURLOPT_NOBODY, 1)

$result = curl_exec($post);
$info = curl_getinfo($post);
curl_close($post);

if($result !== false){
   echo 'Erro com código de ' . $info['http_code'];
}else{ 
   echo 'Requisição bem sucedida';
}

I’m ignoring possible security issues and haven’t tested the code.

  • 1

    It worked out, thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.