38

Sometimes fail to call the web service.

This problem happens all the time.

What could be the problem?

Error:
    SoapFault exception: [HTTP] Could not connect to host in 
    0 [internal function]: SoapClient->__doRequest('<?xml version="...', http://.', '', 1, 0)
ujava
  • 1,846
  • 5
  • 20
  • 24
  • 2
    Could be a network connection issue, especially perhaps that the service is not available. Try building fault-tolerance into your application - perhaps an auto-retry up to 3 times total? – zanlok Nov 30 '10 at 21:32
  • Another reason could be a failing SSL certificate verification (e.g. selfsigned certificates). It is possible to allow selfsigned certs, see http://stackoverflow.com/a/39242417/1119601 – stollr Aug 31 '16 at 06:37
  • 1
    Yes I was getting the same issue and I managed to work by disabling ssl on local: `'stream_context'=> stream_context_create(array('ssl'=> array('verify_peer'=>false,'verify_peer_name'=>false)))` – Parminder Singh Nov 10 '19 at 13:22

27 Answers27

33

The problem was solved.The problem is the cache

ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
ujava
  • 1,846
  • 5
  • 20
  • 24
  • 10
    seems the "Could not connect to host" is not related to Cache. – Raptor Sep 27 '12 at 03:19
  • 12
    Presumably this is the same as: $client = new SoapClient($url, array('cache_wsdl' => WSDL_CACHE_NONE)); –  Aug 17 '14 at 00:35
  • 8
    Common, in my country we call it *"throwing the baby with bath's water"*. There's an issue with the cache, maybe, but disabling he cache in case of SOAP wsdl is an heavy step. It means retrieving and parsing a big XML file each time you use your PHP class. Cannot believe this is the top voted answer... – regilero Oct 28 '16 at 07:19
  • 1
    This error message is too generic: https://bugs.php.net/bug.php?id=68782 error can come from timeouts, proxy, cache interactions https://bugs.php.net/bug.php?id=69783 check answers below but please do not upvote this one. – regilero Oct 28 '16 at 07:54
  • [Bug 69783](https://bugs.php.net/bug.php?id=69783) causes the WSDL cache to fail when a proxy is configured. Until this bug is fixed, the the WSDL cache needs to be disabled. –  Apr 10 '17 at 13:01
27

I am adding my comment for completeness, as the solutions listed here did not help me. On PHP 5.6, SoapClient makes the first call to the specified WSDL URL in SoapClient::SoapClient and after connecting to it and receiving the result, it tries to connect to the WSDL specified in the result in:

<soap:address location="http://"/>

And the call fails with error Could not connect to host if the WSDL is different than the one you specified in SoapClient::SoapClient and is unreachable (my case was SoapUI using http://host.local/).

The behaviour in PHP 5.4 is different and it always uses the WSDL in SoapClient::SoapClient.

VolenD
  • 3,592
  • 18
  • 23
  • While my error message was the same (could not connect to host), simply downgrading to a previous version of php (5.6 > 5.3) allowed the script to run as previous. – Terry Kernan Sep 15 '15 at 00:07
  • 11
    You can tweak this behaviour using [`SoapClient::__setLocation()`](http://php.net/manual/en/soapclient.setlocation.php)`. – geomagas Apr 14 '16 at 07:47
  • 1
    user3584460 and @geomagas Thanks guys, you saved me, i was going crazy over this – Nevercom May 06 '17 at 18:19
  • Was my case as well. What made it even funnier was that the "location" URL returned in WSDL was changing based on which server the loadbalancer has forwarded my request to - sometimes it was ok, sometimes not. Forcing location to the correct URL solved the issue for me. – Maciej Zgadzaj Nov 14 '17 at 15:17
18

The host is either down or very slow to respond. If it's slow to respond, you can try increasing the timeout via the connection_timeout option or via the default_socket_timeout setting and see if that reduces the failures.

http://www.php.net/manual/en/soapclient.soapclient.php

http://www.php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout

You can also include error handling as zanlok pointed out to retry a few times. If you have users actually waiting on these SOAP calls then you'll want to queue them up and process them in the background and notify the user when they're finished.

Rob Olmos
  • 2,372
  • 15
  • 24
  • 1
    I found that if `connection_timeout` wasn't set (>= 1) in my `SoapClient` options, I would encounter `could not connect to host`. Once this option was set, problem solved. – Greg K Oct 01 '14 at 14:46
  • @GregK That's odd. The connect_timeout I believe is supposed to default to the default_socket_timeout value (default 60 seconds) if it's not explicitly set. – Rob Olmos Oct 22 '14 at 08:01
  • Yes, I thought so but I have `default_socket_timeout` set and it had no effect. There is a long standing bug in PHP where `default_socket_timeout` does not apply to SSL connections as well (for the `SoapClient` anyway). – Greg K Oct 22 '14 at 11:53
  • @GregK Could you provide a link to this long standing bug? – marcovtwout Jun 24 '20 at 14:19
  • 1
    @marcovtwout After 6 years?! Looks like it was patched just days after my comment in PHP 5.5.18: https://bugs.php.net/bug.php?id=41631 – Greg K Jun 25 '20 at 16:50
17

A misconfigured service leaves the default namespace with tempuri.org

This means the connection to the wsdl will work, but the function call will fail.

Stacktrace:

SoapClient->__doRequest('http://example.com...', 'http://tempuri.org....', 2, 0)

To remediate this, you must explicitly set the location using __setLocation()

$this->soapClient = new \SoapClient(WS_URL);
$this->soapClient->__setLocation(WS_URL);
MediaFormat
  • 339
  • 3
  • 10
10

This work for me

$opts = array(
  'ssl' => array('verify_peer' => false, 'verify_peer_name' => false)
);

if (!isset($this->soap_client)) {
  $this->soap_client = new SoapClient($this->WSDL, array(
    'soap_version'   => $this->soap_version,
    'location'       => $this->URL,
    'trace'          => 1,
    'exceptions'     => 0,
    'stream_context' => stream_context_create($opts)
  ));
8

there is a soap config section in your php.ini file, which control the wsdl access cache, may be shown as:

[soap] 
; Enables or disables WSDL caching feature. 
soap.wsdl_cache_enabled=1 ; 
Sets the directory name where SOAP extension will put cache files. 
soap.wsdl_cache_dir="/tmp" 
; (time to live) Sets the number of second while cached file will be used ; instead of original one.  
soap.wsdl_cache_ttl=86400

if wsdl file cache is enabled, it may cause this problem when changing wsdl URI in php code. in this example, you can just delete file start with wsdl- under /tmp directory. or you just set soap.wsdl_cache_enabled=0; and soap.wsdl_cache_ttl=0; PHP will fetch the wsdl file every-time you visit the page.

Emil
  • 7,220
  • 17
  • 76
  • 135
curzduff
  • 91
  • 1
  • 2
6

In our case, it was a Ciphers negotiation problem. We were getting this error randomly. We solved our problem by forcing a Cipher like this:

$soapClient = new SoapClient ('http://example.com/soap.asmx?wsdl',
    array (
        "stream_context" => stream_context_create (
            array (
                'ssl' => array (
                    'ciphers'=>'AES256-SHA'
                )
            )
        )
    )
);

Looks like PHP wasn't negotiating the same Ciphers at each service call.

atiruz
  • 2,782
  • 27
  • 36
MaxP
  • 325
  • 5
  • 10
  • After upgrading from PHP 7.2 to 7.3 we had Soap errors when calling WorldPay/Envoy. Setting this Cipher in our `SoapClient` options fixed our issue. – Tom Sep 25 '19 at 12:31
  • How did you know that? Brute-force configuration? Did you see it in any source link reference? – Zelkovar Jan 28 '20 at 07:29
5

In my case it worked after the connection to the wsdl, use the function __setLocation() to define the location again because the call fails with the error:

Could not connect to the host

This happens if the WSDL is different to the one specified in SoapClient::SoapClient.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
4

I hit this issue myself and after much digging I eventually found this bug for ubuntu:

https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/965371

specifically

https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/965371/comments/62

openssl s_client -connect site.tld:443 failed however openssl s_client -tls1 -connect site.tld:443 gave success. In my particular case part of the output included New, TLSv1/SSLv3, Cipher is RC4-MD5 so I set the php context ssl/cipher value appropriately.

3

It seems the error SoapFault exception: Could not connect to host can be caused be several different things. In my cased it wasn't caused by proxy, firewall or DNS (I actually had a SOAP connection from the same machine working using nusoap without any special setup).

Finally I found that it was caused by an invalid pem file which I referenced in the local_cert option in my SoapClient contructor.

Solution: When I removed the certificate chain from the pem file, so it only contained certificate and private key, the SOAP calls started going through.

Jacob
  • 974
  • 1
  • 12
  • 21
  • This worked in my case. Which is funny, because the old cert had worked with the chain. (It was a certificate renewal). Thanks Jacob. – dmgig Oct 06 '16 at 14:15
  • @Jacob What was the command you used to generate the PEM file? – denormalizer Jan 10 '18 at 05:00
  • I don't remember exactly how I generated a `pem` file but I do remember that I just opened a normal text editor and removed the part that referenced the certificate chain while leaving the other part untouched. – Jacob Jan 15 '18 at 10:20
3

For me it was a certificate problem. Following worked for me

$context = stream_context_create([
    'ssl' => [
        // set some SSL/TLS specific options
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    ]
]);

$client  = new SoapClient(null, [
    'location' => 'https://...',
    'uri' => '...', 
    'stream_context' => $context
]);
Jean Fiedler
  • 141
  • 9
  • Don't forget: arrays must be defined with `array( key => val )` syntax [prior to PHP version 5.4](https://www.php.net/manual/en/migration54.new-features.php). I copy/pasted this into a PHP 5.2 app and was met with syntax errors until changing to the old array syntax. – Eric Seastrand Dec 02 '19 at 15:52
  • Your example showed me something I missed in another answer. Thanks for the good example code! – Tim Morton Jul 21 '22 at 13:32
2

In my case service address in wsdl is wrong.

My wsdl url is.

https://myweb.com:4460/xxx_webservices/services/ABC.ABC?wsdl

But service address in that xml result is.

<soap:address location="http://myweb.com:8080/xxx_webservices/services/ABC.ABC/"/>

I just save that xml to local file and change service address to.

<soap:address location="https://myweb.com:4460/xxx_webservices/services/ABC.ABC/"/>

Good luck.

Panusit
  • 21
  • 2
2

I finally found the reason,its becuse of the library can't find a CA bundle on your system. PHP >= v5.6 automatically sets verify_peer to true by default. However, not all systems have a known CA bundle on disk .

You can try one of these procedures:

1.If you have a CA file on your system, set openssl.cafile or curl.cainfo in your php.ini to the path of your CA file.

2.Manually specify your SSL CA file location

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);  
curl_setopt($cHandler, CURLOPT_CAINFO, $path-of-your-ca-file);

3.disabled verify_peer

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
Tianya Lan
  • 21
  • 1
2

For those who struggled the same as me with laravel artisan console command that makes a lot of requests to same wsdl of external soap server and then after some time fails with Could not connect to host error.

The problem was because I was creating new SoapClient instance each time before request was made. Do not do that. Create it once and make each request from the same client.

Hope it helps.

Nick Synev
  • 389
  • 4
  • 11
1

If you have a firewall on your server, make sure to open the port used by SOAP.

In my case, I had to open the port 1664.

iptables -t filter -A INPUT -p tcp --dport 1664 -j ACCEPT
iptables -t filter -A OUTPUT -p tcp --dport 1664 -j ACCEPT
Nicolas BADIA
  • 5,612
  • 7
  • 43
  • 46
  • For me problem also was with port. SOAP server used port that was disabled for connections. – Eugene Fidelin Aug 24 '12 at 13:43
  • 1
    how to find out which port SOAP is trying to use ? – mf_ Jan 18 '14 at 20:39
  • @ujava got it solved the exact same error after finding this thread, searched for `$rcmail_config['soap_url'] = ` was confgured improperly, correcting the server+port+https(in my case) did it – mf_ Jan 19 '14 at 00:08
1

if ujava's solution can't help you,you can try to use try/catch to catch this fatal,this works fine on me.

try{
    $res = $client->__call('LineStopQueryJson',array('Parameters' => $params));
}catch(SoapFault $e){
    print_r($client);
}
pan7an
  • 21
  • 2
1

With me, this problem in base Address in app.config of WCF service: When I've used:

<baseAddresses><add baseAddress="http://127.0.0.1:9022/Service/GatewayService"/> </baseAddresses>

it's ok if use .net to connect with public ip or domain.

But when use PHP's SoapClient to connect to "http://[online ip]:9022/Service/GatewayService", it's throw exception "Coulod not connect to host"

I've changed baseAddress to [online ip]:9022 and everything's ok.

Nesaver
  • 21
  • 2
1

For me it was a DNS issue. My VPS's nameservers crapped out, so I switched to Google's by editing my /etc/resolv.conf to be: nameserver 8.8.8.8 nameserver 8.8.4.4

1

Another possible reason for this error is when you are creating and keeping too many connections open.

SoapClient sends the HTTP Header Connection: Keep-Alive by default (through the constructor option keep_alive). But if you create a new SoapClient instance for every call in your queue, this will create and keep-open a new connection everytime. If the calls are executed fast enough, you will eventually run into a limit of 1000 open connections or so and this results in SoapFault: Could not connect to host.

So make sure you create the SoapClient once and reuse it for subsequent calls.

marcovtwout
  • 5,230
  • 4
  • 36
  • 45
0

I had a bad php.ini configuration. Verify the path and the certificate validity...

[openssl]
openssl.cafile = "C:/good/phpath/ca-bundle.crt"

Because my new \SoapClient($wsdl) was https !

François Breton
  • 1,158
  • 14
  • 24
0

Just to help other people who encounter this error, the url in <soap:address location="https://some.url"/> had an invalid certificate and caused the error.

Cas van Noort
  • 255
  • 3
  • 9
0

For me, this was a problem in the httpd service (Fedora 24). A simple restart did the trick:

sudo service httpd restart
hlscalon
  • 7,304
  • 4
  • 33
  • 40
0

If the connection is through SSL, could be a problem of server instead of client (it is my case).

In PHP versions greater than 5.6 and 7, is important to check the CipherSuite used in server certificate. There is a full list of ciphers allowed by this versions and a full list of ciphers that do not in this web link: https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Ciphersuite

If the cipher used is not allowed (it is a deprecated algorithm), SoapClient receives "Could not connect to host" and there is no more trace about it.

The cipher used can be checked by clients like SoapUI in the section of "SSL Info", for example.

There is no thread forum treating about this in internet.

Check this out, too: http://php.net/manual/en/migration56.openssl.php

Zelkovar
  • 119
  • 1
  • 5
0

In my case the host requires TLS 1.2 so needed to enforce using the crypto_method ssl param.

$client = new SoapClient($wsdl,
    array(
           'location' => $location,
           'keep_alive' => false,
           "stream_context" => stream_context_create([
                'ssl' => [
                    'crypto_method' =>  STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
                ]
            ]),
           'trace' => 1, // used for debug
        )
    );
Andrew Rendall
  • 149
  • 1
  • 3
0

In my case, disabled SELINUX allow PHP to call my WebService. I run PHP in FPM with Apache2

SELinux status :

# sestatus

Disable SELinux :

setenforce 0

Enable SELinux :

# setenforce 1

Permanent disable :

edit this file /etc/selinux/config
Alex
  • 1
-1

Version check helped me OpenSSL. OpenSSL_1_0_1f not supported TSLv.1_2 ! Check version and compatibility with TSLv.1_2 on github openssl/openssl . And regenerate your certificate with new openssl

openssl pkcs12 -in path.p12 -out newfile.pem

P.S I don’t know what they were minus, but this solution will really help.

-8

That most likely refers to a connection issue. It could be either that your internet connection was down, or the web service you are trying to use was down. I suggest using this service to see if the web service is online or not: http://downforeveryoneorjustme.com/

Ali
  • 261,656
  • 265
  • 575
  • 769
  • 3
    If my internet connection was down, how could I post anything on web, how could I get response from a remote server to my local wamp or to the SOAPUI tool. – Srikanth V M Feb 23 '12 at 17:55