Using php -a
$url = "https://getcomposer.org/versions";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
echo curl_exec($ch);
It working fine, returns a JSON string from the URL. Now, continuing in the php -a terminal interaction:
echo file_get_contents($url);
… After a long wait, say: “PHP Warning: file_get_contents(…): Failed to open stream: Connection timed out in php shell code”.
Same error when using all headers:
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set("auto_detect_line_endings","0");
ini_set("allow_url_fopen", "1");
ini_set("allow_url_include", "0");
ini_set("user_agent", "Mozilla/5.0");
echo file_get_contents($url);
PS: I need file_get_contents for WordPress, Composer, etc. this question is about “why file_get_contents not working”.
My env
php -v
PHP 8.0.30 (cli) (built: May 20 2025 13:31:19) ( NTS gcc x86_64 )
cat /etc/oracle-release
Oracle Linux Server release 9.6