简体   繁体   中英

CURLOPT_RETURNTRANSFER on working on localhost but not working on live server in php

$user_access ='example';
$user_key = 'examplekey';
$payload = json_encode($arr);
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'example.com/api/users/2');
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($payload)));
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $payload );
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERPWD, $user_access . ":" . $user_key);  
if (curl_exec($curl_handle) === FALSE) {
    die("Curl Failed: " . curl_error($curl_handle));
} else {
    return curl_exec($curl_handle);
};

When I remove the curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); then it is working on both local as well as live server. I do not need the return automatically curl_exec value so that I am using curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);

I unable to identify the issue. Please help me

If you checked that you use a likely environment (eg PHP-Version, curl_exec not blocked on live server which is the case for some hosters) locally and on your live server than it is most probably that the remote server (the API-Server) is in fact responding differently. This can be that it has access-levels based on ip-address or other things.

In general consider:

  • You are executing curl_exec() twice: First to check if it's return is FALSE and then again if it was not. Instead store the return value in a variable
  • Try setting curl_setopt($curl_handle, CURLOPT_VERBOSE, true); so you get more information about potential errors
  • Using a HTTP-Request Library that handles those things for you, like Guzzle wich brings also good error-handling. After installing it:
$httpClient = new GuzzleHttp\Client();
$response = $client->request('PUT', 'https://example.com/api/users/2', [
    'auth' => [$user_access, $user_pass],
    'json' => $arr
]);

return $response->getBody();

will handle everything for you.

You should be comparing and handling like below;

$Result = curl_exec($curl_handle);
if($Result === false)die("Curl Failed: " . curl_error($curl_handle)); // Just an error display interceptor
return $Result; // Always return the appropriate response

It is certain in your code that you are trying to wrap this in a function, and this function should always return something. Here we are returning the $Result no matter cURL succeeded or failed, you make an explicit check with the caller to see if your cURL method worked ($cURLFunctionReturnValue === false) and code like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM