Fixing file_get_contents() Not Working in PHP-CLI (while cURL Works)

📝 Introduction

Sometimes developers face a strange issue:

  • curl_init() works fine in PHP-CLI

  • file_get_contents("http://...") fails

This happens because file_get_contents() relies on PHP stream wrappers, which require the directive allow_url_fopen to be enabled. On many servers, especially in CLI mode, this setting is disabled for security.

🔍 Why cURL Works but file_get_contents() Fails

  • cURL → uses its own HTTP library → works regardless of allow_url_fopen.

  • file_get_contents() → depends on fopen wrappers → needs allow_url_fopen = On.

If disabled, you’ll see errors like:

    	failed to open stream: HTTP wrapper is disabled in the server configuration
    

🛠 Step 1: Check Which php.ini is Used by CLI

Run this command:

    	php --ini
    

It will show something like:

    	Loaded Configuration File: /etc/php/8.1/cli/php.ini
    

👉 This is the php.ini you must edit (different from Apache or PHP-FPM).

🛠 Step 2: Enable allow_url_fopen in php.ini

Open the CLI php.ini file:

    	sudo nano /etc/php/8.1/cli/php.ini
    

Find this line:

    	allow_url_fopen = Off
    

Change it to:

    	allow_url_fopen = On
    

Save and exit.

🛠 Step 3: Restart Services (if needed)

  • For CLI scripts → no restart needed, changes apply instantly.

  • For Apache (mod_php):

                sudo nano /etc/php/8.1/apache2/php.ini
                sudo systemctl restart apache2
    		
  • For Nginx + PHP-FPM:
                sudo nano /etc/php/8.1/fpm/php.ini
                sudo systemctl restart php8.1-fpm
    		

🛠 Step 4: Verify the Setting

Run:

		php -r 'echo ini_get("allow_url_fopen");'
	

If successful, you’ll see:

		1
	

Or check:

		php -i | grep allow_url_fopen
	

✅ Troubleshooting Checklist

  • Did you edit the CLI php.ini?

  • Did you check for overrides in /etc/php/<version>/cli/conf.d/?

  • Did you restart Apache/FPM if needed?

  • Did you confirm with php -r 'ini_get("allow_url_fopen");'?

  • Are you sure you’re running the correct PHP version (which php)?

If file_get_contents() fails in CLI but cURL works, it’s almost always because allow_url_fopen is disabled in CLI’s php.ini.

👉 Quick Fix:

  1. Run php --ini

  2. Edit CLI php.ini → allow_url_fopen = On

  3. Save & test with php -r 'file_get_contents("http://example.com");'

Now your CLI PHP will fetch remote URLs just like cURL. 🚀

Previous Article

How to Embed Google Maps in WordPress Contact Form

Next Article

How to Increase Web Server Speed in PHP: A Complete Guide

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨