Kuldeep Singh
Kuldeep Singh

Reputation: 59

Duplicate data stored when using cURL

I am trying to post data using cURL to my web services to store data into database there, but it's storing the same data two times, instead of one. I applied condition there and it's working but i can not find the reason behind that behavior.

        $postedArray['login_credentials'] = $this->login_data;
        $postedArray['post_data'] = $this->arrPostData;

        $str = http_build_query($postedArray);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        curl_setopt($ch, CURLOPT_URL, $this->requestUrl);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 999);
        curl_setopt($ch, CURLOPT_TIMEOUT, 999);
        if (curl_exec($ch) === false) {
            echo 'Curl error: ' . curl_error($ch);
            return false;
        }
        $response = curl_exec($ch);
        $response = json_decode($response, true);

        curl_close($ch);
        return $response;

Upvotes: 0

Views: 1108

Answers (2)

Sagar
Sagar

Reputation: 647

use curl_exec($ch) only once, code should look like this:

// code goes here

$response = curl_exec($ch);
if ($response === false) 
{
echo 'Curl error: ' . curl_error($ch);
return false;
}
else
{
$json_response = json_decode($response, true);
}
curl_close($ch);
return $json_response;

Upvotes: 0

Masiorama
Masiorama

Reputation: 1117

Because you are actually calling curl_exec 2 times:

if (curl_exec($ch) === false) {
        echo 'Curl error: ' . curl_error($ch);
        return false;
}
$response = curl_exec($ch);

The first time while evaluating the response inside the if, and then again after the if. One should be dropped.

Upvotes: 2

Related Questions