Apache无法使用curl发出传出的HTTP请求

问题描述:

请考虑以下系统配置:

  • Fedora 27
  • 已启用SELinux
  • Apache/2.4.33
  • PHP 7.1.17

以及下面的代码段,用于向 Sphere-Engine编译器API发出http请求:

And the below code snippet that is used to issue an http request to Sphere-Engine Compilers API:

$ch = curl_init('http://xxxxxxxx.compilers.sphere-engine.com/api/v4/test?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_TIMEOUT, 3.0);
$x = curl_exec($ch);
print_r($x);

当我运行以下CLI时,上面的脚本可以完全正常工作:

The above script works completely fine when I run the following CLI:

php script.php

然后我得到了预期的输出.

And I get the intended output.

但是,当我尝试通过Web浏览器运行它时,会产生:

However, when I try to run it through the web browser it produces:

CURLE_COULDNT_CONNECT(7)无法将connect()连接到主机或代理.

CURLE_COULDNT_CONNECT (7) Failed to connect() to host or proxy.

我发现了很多建议,例如添加

I have found many suggestions such as adding

curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

这不是我真正的解决方案.关闭SELinux,我将这样做.

Which wasn't really a solution for me. Turning off SELinux which I will not do.

注意:当我发布该URL并提供预期的输出时,URL本身也可以正常工作.

Note: The URL itself is working fine when I issue it and gives me the intended output too.

有什么建议吗?预先感谢.

Any suggestions? Thanks in advance.

尝试执行以下操作以查看SELinux是否将使Web服务器连接到网络:

Try this to see if SELinux will let the web server connect to the network:

getsebool httpd_can_network_connect

getsebool httpd_can_network_connect

如果没有,请允许

setsebool -P httpd_can_network_connect上

setsebool -P httpd_can_network_connect on

https://access.redhat.com/documentation/zh-CN/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/sect-managing_confined_services-the_apache_http_server-booleans