Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL not working sometimes and gives empty result

Tags:

php

curl

php-curl

I used cURL to get data from another website. Sometimes it shows data and sometimes empty result

Here is my Code


    function get_data($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        $agent=$_SERVER["HTTP_USER_AGENT"];
        curl_setopt($ch,CURLOPT_USERAGENT, $agent); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);

        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    $returned_content = get_data('www.example.com');
    echo $returned_content;

like image 771
Vignesh Avatar asked Jun 05 '15 12:06

Vignesh


People also ask

What does it mean if cURL returns nothing?

This means no HTTP headers or content, simply a closed TCP connection with no HTTP payload is transmitted. curl: (52) Empty reply from the server is a server related issue. However, this happens when libcurl did not receive any response from the server even after it has sent off its request.

Why cURL is not working?

Cause #1 – cURL is not enabled cURL is supported by your hosting company/plan but not enabled: If cURL is supported by you hosting company but it is not enabled by default, then often you simply just need to login to your hosting dashboard, navigate to the relevant section and enable it.

How do you check cURL is enabled or not?

Create phpinfo. php file and save. phpinfo; ?> Then go to http://domainname/phpinfo.php to check whether CURL is enabled or not.

How do you catch errors in cURL?

If you want to fetch the error message, make sure you fetch it before you close the current cURL session or the error message will be reset to an empty string. This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400.


2 Answers

Possibly you call too many connections from your curl_init to one Ip Address, So the server blocks the connection and causes the on/off errors.

like image 156
Developer Avatar answered Sep 29 '22 14:09

Developer


Not receiving any content back could be due to one or more out of many different reasons and you need to figure out which.

  1. Use curl_error($ch) in your code after the transfer has been performed to see if curl has told you about a problem.

  2. Investigate the response headers. A HTTP transfer can be successful and not return any error but might only respond with HTTP headers and no body at all. The HTTP headers may then contain clues as to why. Perhaps it is a redirect you should follow, perhaps it requires HTTP authentication or perhaps the server indicates a temporary server glitch.

like image 44
Daniel Stenberg Avatar answered Sep 29 '22 14:09

Daniel Stenberg