phpcurllocalhost

PHP - curl localhost connection refused


Explanation

I made a simple REST api in Java (GET).


Expected

To have PHP curl work on the localhost

Actual

For some reason PHP curl on IPv4 works, but localhost does not work


PHP curl output error


Code

$url = 'http://localhost:8080/api/user';
$curl = curl_init($url);
echo json_decode(curl_exec($curl));

I have tried (from the top of my head, no specific order)

curl_setopt ($curl, CURLOPT_PORT , 8080);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

Solution

  • For those ones who are using Docker, Vargant and so on.

    You got Failed to connect to localhost port 8080: Connection refused error, because you are trying to connect to localhost:8080 from inside virtual machine (eq. Docker), this host isn't available inside the Docker container, so you should add a proxy that can reach a port from the out.

    To fix this issue add the next line of code after your curl_init():

    curl_setopt($ch, CURLOPT_PROXY, $_SERVER['SERVER_ADDR'] . ':' .  $_SERVER['SERVER_PORT']);
    

    Here is a full example:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $APIUrl);
    
    if ($_SERVER['HTTP_HOST'] == 'localhost:8080') {
        // Proxy for Docker
        curl_setopt($ch, CURLOPT_PROXY, $_SERVER['SERVER_ADDR'] . ':' .  $_SERVER['SERVER_PORT']);
    }
    
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        $error = curl_error($ch);
    }
    
    curl_close($ch);