Curl in PHP returns null on AWS EC2 instance

2019-09-19 09:14发布

I have AWS EC2 , Apache server setup. All website pages are working except for two places whereever I sued CURL. Following pointers as per this issue search online, which are working as expected:

CURL is showing up in phpinfo(). CURL command is accessible and running accross. Apache2 does have CURL installed. curl command from CLI is working fine. (curl http://localhost and curl www.google.com) both are working.

When I ran following function, url when run in browser $url, returns data as expected. But when I run from PHP, none of the echo commands ever returned a values. Further, values seem to be null.

function get_patients(){ $hostname = file_get_contents('http://169.254.169.254/latest/meta-data/public-hostname'); $url = $hostname.'/folder1/app1.php?all';

//echo $url;

///$url .= urlencode($query);//.'&key='.$key;

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

//echo $curl;

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT , 400);
curl_setopt($curl, CURLOPT_TIMEOUT, 400);

$data = curl_exec($curl);

curl_close($curl);

//decoding request

$result = json_decode($data, true);

//print_r( $data);

return $result;
}

This is the first function, based on which most of APIs are dependent on. This above php file is in var/www/html/folder1. when I access the main API that I am trying to access in browser, $hostname.'/folder1/app1.php?all', does return data as hosted on a local apache server and even remote domain host server as well. Its just not working with AWS EC2.

2条回答
The star\"
2楼-- · 2019-09-19 09:34

I answered a similar curl problem yesterday where i could replicate/debug. Your code is a bit generic and not knowing the remote server address i can suggest you debug your curl request.

See GET Request works with python 'requests' library, but does not work with curl

you need to check if curl returns any errors and debug just like the below

if(curl_exec($handle) === false)
{
    echo 'Curl error: ' . curl_error($handle);
}
else
{
    echo 'Char encoding ' . mb_detect_encoding($flight_model_data) . ' <br/><br/>';

    echo 'Operation Completed without any errors : <br/>' . $flight_model_data . " ENDED\n\n <br/><br/>";


    echo "<br/>Curl info : " . json_encode(curl_getinfo ($handle) );
}
查看更多
小情绪 Triste *
3楼-- · 2019-09-19 09:34

Thanks ton for reply. Upon continuous troubleshooting I got this fixed. Needed a change in configuration to be modified in php.ini in apache server configuration, just make sure settings and versions are same in both PHP5 as well as Apache2 folders on server. Also PHP5 MUST have PHP5-libcurl installed, which was already there on my server. Thank you everyone for swift response.

查看更多
登录 后发表回答