Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - curl localhost connection refused

Explanation

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

  • Postman works (both localhost and IPv4)

  • curl from command line works (both localhost and IPv4)

  • External request from a different city works (IPv4)


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

  • Failed to connect to localhost port 8080: Connection refused

  • curl error: 7


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);
like image 258
Jsh0s Avatar asked Jun 05 '26 23:06

Jsh0s


2 Answers

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);
like image 187
Serhii Popov Avatar answered Jun 07 '26 11:06

Serhii Popov


I'm not sure if this counts as an answer but I just restarted the linux VM and now its working...

like image 33
Jsh0s Avatar answered Jun 07 '26 13:06

Jsh0s