php cURL to localhost returns permission denied on

2020-03-31 05:43发布

问题:

I'm getting a permission denied error when trying to make a cURL request with the php cURL library to localhost on port 4321. This will hopefully be really easy or obvious for someone who's run into this before.

I'm able to make the identical cURL request from another system on the local area network to the production server. For example, if on another system on the local area network I make a request using the function below where $host='http://192.168.1.100:4321' then everything works exactly like it should. If I run on the system itself where $host='http://localhost:4321' or $host='http://127.0.0.1:4321' or $host='::1:4321' then I get a cURL error of "Permission Denied"

The function I wrote for my very simple request is:

function makeRequest($host,$data){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $host);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = json_decode(curl_exec($ch),true);
    if(!empty(curl_error($ch))){
        $result = print_r(curl_error($ch).' - '.$host);
    }
    curl_close($ch);
    return $result;
}

The system is a centos 7 server. Running firewall-cmd --list-all shows my open ports

ports: 443/tcp 80/tcp 4321/tcp

If you have some idea, or need me to check a setting don't hesitate to ask.

EDIT The hosts file looks like

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

EDIT2

When I use commandline curl against the same port everything comes back alight.

 /]$ curl -v localhost:4321
* About to connect() to localhost port 4321 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 4321 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:4321
> Accept: */*
>
< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Cache-Control: no-cache, no-store, must-revalidate
< Content-Length: 774....

回答1:

I found the answer to the problem at: Getting permission denied while Posting xml using Curl?

The problem is SELinux and the solution is to run:

sudo setsebool httpd_can_network_connect 1

It doesn't make sense to me that I could use the php cURL library to access every other website in the world, but not localhost on a different port, while I was able to access the localhost from command line cURL.