PHP file_get_contents not working php.ini, SELinux, systemd, Apache and network services dependencie problem

Scroll this

If you can’t access network from php script running under Apache (e.g. fetch network resource with file_get_contents, cUrl, SoapClient, etc …), there are at least three problems that needs to be checked and fixed.

  1. php.ini settings
  2. SELinux settings
  3. Apache and network service dependencie problem

Test script:

 

php.ini settings

If test script outputs something like this:

check current setting of the allow_url_fopen and the correct location of the php.ini .

phpinfo() output:

Result:

Check for allow_url_fopen:

Set it to On:

Find allow_url_fopen in php.ini file and set it to On:

Note: Leave allow_url_include set to Off.

Restart apache server

CentOS:

Ubuntu:

Check to see if the problem is fixed.

SELinux settings

SELinux stands for Security Enhanced Linux is implementation of MAC (Mandatory Access Control) mechanism which gives one more layer of security after the standard DAC (Discretionary Access Control). By default network connection from httpd (Apache) is disabled. To learn more about SELinux check Red Hat documentation.

First check is SELinux enabled:

If enabled, you should get something like this:

Probably script will not output any errors. Apache error log will not be updated neither. Check SELinux log file:

$ sudo less /var/log/audit/audit.log

For errors like this:

Please not httpd and denied. πŸ™‚

 

Check those SELinux boolean flags: httpd_can_network_connect, httpd_unified :

If off, set it to on. Execute:

Flag -P makes the new setting permanent.

To be sure, reboot.

Apache and network service dependencies problem

If test script is still not working and giving error like this:

Try restarting Apache.

CentOS:

Ubuntu:

If the script is now working – you haveΒ Apache and network service dependencies problem. When the systems boots processes are started asynchronous and Apache is started before network service is fully up and running. NSSΒ  lookup (Name Server Switch which also includes DNS – Domain Name Server lookup) is fully configured after the Apache has started – so Apache doesn’t know how to resolve the domain. This is why it works after Apache is restarted manually. Follow this steps to correctly configure services dependencies.

Execute:

Edit config files to make sure that Apache is started after the network services and also after the MySQL – because when I need Apache I also need to have MySQL up and running.

Edit mysqld.service:

Change Requires and After to:

Edit httpd.service:

Change Requires and After to:

Execute:

And reboot to test.

After reboot execute:

To see service execution chain:

httpd has started after both mysqld and networking.

 

References

Submit a comment