简体   繁体   中英

How to solve CURL request error "Could not resolve host: ..." PHP?

I'm facing this very odd error. I can't send a cURL request anymore after changing nothing. Out of the sudden I'm getting:

'Could not resolve host: hostname'

I know there are like a 1000 instances of this question on stackoverflow but I have tried all the suggested answers/comments in them for the past 5 hours and nothing seems to work. This is my code for the request:

<?php

class APIService
{
    private $host;
    private $key;

    function __construct($host, $key)
    {
        $this->host = $host;
        $this->key = $key;
    }

    function curlRequest($config)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('api:'.$this->key));
        curl_setopt($ch, CURLOPT_URL, $this->host.$config);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $curlSession = curl_exec($ch);

        return $this->decodeJSON($curlSession);
    }

    function getSomeList()
    {
        return $this->curlRequest('/folder/list');
    }

    private function decodeJSON($someList)
    {
        return json_decode($someList, true);
    }
}

The host is local and using docker ps I can see that is running. Everything worked fine a few days ago and I made absloutly no changes to it or to any component that may have an effect on it but it doesn't work out of the sudden. Has anyone has any ideas why this is happening and how I could fix it?

I've had this problem before. I see in the chat that you said you had a backend and a frontend that you're putting on the same network and are using Docker. I think the problem is occuring because something went wrong with the virtual netwrok between your front and backend. Try the following:

1- Make sure both the front and backend's containers are up.

2- Ensure that they're in the same netwrok using the following commands:

  • Make a network docker network create some-network-name-or-the-name-you-already-had
  • Add the backend to the network docker network connect some-network-name-or-the-name-you-already-had your-backend-webserver-name (if you don't know the name of your backend webserver use docker ps to view it.
  • Add the frontend to the network docker network connect some-network-name-or-the-name-you-already-had your-frontend-webserver-name .

Now I'm unsure of this but, whenever the container of the frontend or the backend stops, you have (after starting the container using docker-compose up -d ) each time to add it to the network. There might be a way around this, but I'm not aware of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM