PHP Soap - Could not connect to host - php

I have looked at other solutions for this but can't find a similar issue:
This bit of code works ok:
$wsdlUrl = "https://pilot.prove-uru.co.uk/URUws/uru10a.asmx?wsdl";
$client = new soapclient($wsdlUrl);
print_r($client->__getFunctions());
However when I try to make a method call:
$params = array("AddressLookupUK" => array("address" => array("Postcode" => "NE20 9RF"),
'AccountName' => "xxxx",
'Password' => "xxxx"));
$result = $client->AddressLookupUK($params);
I get the error message "SoapFault exception: [HTTP] Could not connect to host". If I change the method call to
$result = $client->FalseMethod($params);
I get back "Function ("FalseMethod") is not a valid method for this service" which shows it is connecting as expected. Does anybody have any pointers I can try?
Thanks

Here is the code I used, hope it helps someone:
$wsdlUrl = "address.wsdl";
$client = new soapclient($wsdlUrl);
$params = array('address' => array('Postcode' => $postcode, 'BuildingNo' => $buildingNo),
'AccountName' => 'XXXX',
'Password' => 'XXXX');
$result = $client->AddressLookupUK($params);
$echoText = '';
if (is_null($result->AddressLookupUKResult))
{
//tell the user nothing was returned
}
else
{
//checks to see if the result set contains only one item
if (is_array($result->AddressLookupUKResult->URUAddressFixed))
{
foreach($result->AddressLookupUKResult->URUAddressFixed as $item)
{
//use code like $item->BuildingNo to access the data
}
}
else
{
//if there was there was more than one then access using something like
$result->AddressLookupUKResult->URUAddressFixed->BuildingNo
}
}
Richard

At the WSDL you see the endpoint deinition:
<wsdl:service name="URU10a">
<wsdl:port name="URU10aSoap" binding="tns:URU10aSoap">
<soap:address location="https://pilot.prove-uru.co.uk:8443/URUws/uru10a.asmx"/>
</wsdl:port>
<wsdl:port name="URU10aSoap12" binding="tns:URU10aSoap12">
<soap12:address location="https://pilot.prove-uru.co.uk:8443/URUws/uru10a.asmx"/>
</wsdl:port>
</wsdl:service>
I think, you have problems connecting the 8443 port. In my restricted network, the service works neither.
EDIT
Ok, I tried to connect using the standard SSL port by changing the WSDL. I have saved the WSDL from https://pilot.prove-uru.co.uk/URUws/uru10a.asmx?wsdl to my hard drive, removed the port numbers from the endpoint definitions and tried to connect using soapUI. Hooray, I got a response.
So maybe they moved the service from 8443 to 443 w/o updating the WSDL. Or it runs under both ports but you (and me) cannot connect the 8443 because of limitations of our local networks. Anyway I think you should contact the provider of this service and clarify this point instead of using a patched version of their WSDL.

The "Function ("FalseMethod") is not a valid method for this service" error is only due to the WSDL check. PHP successfully downloaded the WSDL, but can't access the Webservices in it.
You have to debug the Soap Call with trace set to 1:
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
echo "Response:\n" . $client->__getLastResponse() . "\n";
Also, have a look at the URL's sets in the Wsdl.

I accepted DerVO's answer as his pointers helped me resolve the issue. The port number was not totally causing the issue but I feel may have been contributing to it in some way.
When loading the WSDL in soap UI it was displaying the simple and complex object types without issue, but within PHP this caused it to fall over i.e. the WSDL defined a set of "
Richard

Related

Always getting response as Invalid Session Token in soap client php

I have php version 7.1 in my localhost. I have made changes in my php.ini file to run SOAP from my localhost.
I need to generate primary and secondary session token by passing login id and password to SOAP client API.
Once session token is authenticated it will return some rate chart. My code is generating session tokens. But when I am passing that token key to the next method in SOAP Client api its always giving me an error like "Invalid Session Token" or "Invalid Authentication". However the same tokens are working well in SOAP UI exe. I mean I have installed SOAP UI exe and by using wsdl "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl" and using method "Login" and "LookupRate" its working everything fine. The way i need that.
But whenever i am using that tokens in php localhost its always giving me an authentication error by SOAP Client.
I am sharing my code below.
$wsdl = "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl";
$client = new SoapClient($wsdl, array('trace' => true));
$params = array('loginOperation'=>array('loginId'=>'ryder_cnx1','password'=>'ryder1','thirdPartyId'=>'dl'));
$client->Login($params);
$data = $client->__getLastResponse();
$p = xml_parser_create();
xml_parse_into_struct($p, $data, $vals, $index);
xml_parser_free($p);
$token = [];
foreach ($vals as $key => $value) {
foreach ($value as $key1 => $value1) {
if($key1 == "value")
$token[] = $value1;
}
}
echo "Primary Token = ".$token[0];
echo "<br> Secondary Token = ".$token[1];
//echo "<br> Expiry Date = ".$token[2];
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
$namespace = 'http://www.tcore.com/TcoreTypes.xsd'; // I am not sure about this namespace. Whether its correct or not.
$header = new SoapHeader($namespace,'sessionHeader',$params_session,true);
$client->__setSoapHeaders($header);
$params_data = array('lookupRateOperations'=> array(
'equipment'=>'Vans',
'origin'=>array('postalCode'=>array('country'=>'US','code'=>'30004')),
'destination'=>array('postalCode'=>array('country'=>'US','code'=>'10001'))
));
try{
$result = $client->LookupRate($params_data);
print_r($result);
}catch (SoapFault $exception){
//or any other handling you like
print_r(get_class($exception));
enter code hereprint_r($exception);
}
if anybody have any idea, please share it with me.
Awaiting any response.
Thanks a lot in advance :)
I know this is very old, and most likely the OP figured it out. But in case anyone else comes along, I was able to get it working with two slight changes.
First,
$namespace = 'http://www.tcore.com/TcoreTypes.xsd';
Should be
$namespace = 'http://www.tcore.com/TcoreHeaders.xsd';
Second,
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
should be
$params_session = array(
"sessionToken"=> array(
"primary"=>base64_decode($token[0]),
"secondary"=>base64_decode($token[1])
)
);
The rest of my code is similar enough that if the above changes are made, it should work. I would also refrain from posting real usernames and passwords, btw.

php soapclient returns null but getPreviousResults has proper results

I've ran into trouble with SOAP, I've never had this issue before and can't find any information on line that helps me solve it.
The following code
$wsdl = "path/to/my/wsdl";
$client = new SoapClient($wsdl, array('trace' => true));
//$$textinput is passed in and is a very large string with rows in <item></item> tags
$soapInput = new SoapVar($textinput, XSD_ANYXML);
$res = $client->dataprofilingservice(array("contents" => $soapInput));
$response = $client->__getLastResponse();
var_dump($res);//outputs null
var_dump($response);//provides the proper response as I would expect.
I've tried passing params into the SoapClient constructor to define soap version but that didnt' help. I've also tried it with the trace param set to false and not present which as expected made $response null but $res was still null. I've tried the code on both a linux and windows install running Apache.
The function definition in the WSDL is (xxxx is for security reasons)
<portType name="xxxxServiceSoap">
<operation name="dataprofilingservice">
<input message="tns:dataprofilingserviceSoapIn"/>
<output message="tns:dataprofilingserviceSoapOut"/>
</operation>
</portType>
I have it working using the __getLastResponse() but its annoying me it will not work properly.
I've put together a small testing script, does anyone see any issues here. Do I need a structure for the return type?
//very simplifed dataset that would normally be
//read in from a CSV file of about 1mb
$soapInput = getSoapInput("asdf,qwer\r\nzzxvc,ewrwe\r\n23424,2113");
$wsdl = "path to wsdl";
try {
$client = new SoapClient($wsdl,array('trace' => true,'exceptions' => true));
} catch (SoapFault $fault) {
$error = 1;
var_dump($fault);
}
try {
$res = $client->dataprofilingservice(array("contents" => $soapInput));
$response = $client->__getLastResponse();
echo htmlentities($client->__getLastRequest());//proper request echoed
echo '<hr>';
var_dump($res);//null
echo "<hr>";
echo(htmlentities($response));//proper response echoed
} catch (SoapFault $fault) {
$error = 1;
var_dump($fault);
}
function getSoapInput($input){
$rows = array();
$userInputs = explode("\r\n", $input);
$userInputs = array_filter($userInputs);
//
$inputTemplate = " <contents>%s</contents>";
$rowTemplate = "<Item>%s</Item>";
//
$soapString = "";
foreach ($userInputs as $row) {
// sanitize
$row = htmlspecialchars(addslashes($row));
$xmlStr = sprintf($rowTemplate, $row);
$rows[] = $xmlStr;
}
$textinput = sprintf($inputTemplate, implode(PHP_EOL, $rows));
$soapInput = new SoapVar($textinput, XSD_ANYXML);
return $soapInput;
}
Ok after much digging it is related to relative namespaces, it appears that PHP doesn't handle them well within the WSDL or the SOAP Envelope. So since I don't have control of the SOAP Server I will continue to get the response via __getLastResponse();.
Hopefully this will save some people some time it was hard to find.
You are mixing things here. __getLastResponse() returns the bare XML string response from the server if you make use of the 'trace' => true option. That is for debugging only.
So regardless whether 'trace' => true or not, the method which you would like to call originally returns the same and that is totally normal. Setting tracing to on won't change the behaviour, it just offers an additional feature, the return value for __getLastResponse().
As the SoapClient does not throw any exception I'd say that your call is going okay and NULL is a valid return value.
You might want to provide the actual XML string and/or the WSDL defintion so that one could inspect if that's the case or not.

Why cant php work with WCF 4.0 asp website with a WCF service work?

Ok my .net 4.0 client works fine. People using java all have no issues. But when it comes to php our php developer cant get anything to work.
Now keep in mind i did not create a Wcflibray project, i created a regular asp 4.0 website and then added a WCF Service so i do not have a app.config, i have a web.config.
We have went down to the bare essentials of creating two methods
string HelloWorld()
{
return "Hello!";
}
and
string HellowTomorrow(string sret)
{
return sret;
}
In debug mode i will see him enter my method but only with null. If i packet sniff with wireshark, he is not passing the paramater envelope.
I have googled endlessly but all examples are from a WCF service project, not a website that has added a WCF Service too it. (rememember, everyone else is having no problems, java, .net 2.0, etc)
Here is his php 5.3
error_reporting(E_ALL);
ini_set('display_errors','On');
$client = new SoapClient("http://99-mxl9461k9f:6062/DynamicWCFService.svc?wsdl", array('soap_version' => SOAP_1_1));
$client->soap_defencoding = 'UTF-8';
//$args = array('john');
$args = array('param1'=>'john');
$webService = $client->__soapCall('HelloTomorrow',$args);
//$webService = $client->HelloTomorrow($args);
var_dumpp($webService);
?>
While working with WCF service .net as Server and PHP-soap as client you need to follow guideline strictly. The documentation of PHP-soap is not enough to debug and not that clear either. PHP nusoap is little better on documentation but still not enough on example and not a great choice for the beginners. There are a few examples for nusoap but most of them don’t work.
I would suggest following debug checklist:
Check the binding in your web.config file. It has to be “basicHttpBinding” for PHP
PHP, $client->__soapCall() function sends all arguments as an array so if your web-service function require input parameters as an array then arguments has to be in an extra array. Example#3 is given below to clear.
If required then pass “array('soap_version' => SOAP_1_1)” or “array('soap_version' => SOAP_1_2)” to SoapClient() object to explicitly declare soap version.
Always try declaring “array( "trace" => 1 )” to SoapClient Object to read the Request & Response strings.
Use “__getLastResponse();” function to read Response String.
Use “__getLastRequest();” function to read Request String.
IMPORTANT:If you are getting NULL return for any value passed as
parameter then check your .cs(.net) file that look like this:
[ServiceContract]
public interface IDynamicWCFService
{
[OperationContract]
string HelloYesterday(string test);
}
The variable name passes here, have to match with when you call it in PHP. I am taking it as “test” for my examples below.
Example #1: using php-soap with single parameter for HelloYesterday function
<?php
$url="http://99-mxl9461k9f:6062/DynamicWCFService.svc?WSDL";
$client = new SoapClient($url, array( "trace" => 1 ));
$result = $client->HelloYesterday(array('test' => 'this is a string'));
var_dump($result);
$respXML = $client->__getLastResponse();
$requXML = $client->__getLastRequest();
echo "Request: <br>";
var_dump($requXML);
echo "Response: <br>";
var_dump($respXML);
?>
Example #2 : using nusoap with single parameter for HelloYesterday function
<?php
require_once('../lib/nusoap.php');
$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
$url="http://99-mxl9461k9f:6062/DynamicWCFService.svc?WSDL";
$client = new nusoap_client($url, 'wsdl', $proxyhost, $proxyport, $proxyusername, $proxypassword); $client->soap_defencoding = 'UTF-8'; // this is only if you get error of soap encoding mismatch.
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
// Doc/lit parameters get wrapped
$param = array('test' => ' This is a string for nusoap');
$result = $client->call('HelloYesterday', array('parameters' => $param), '', '', false, true);
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
?>
One more example… passing array as a parameter or pass mixed type parameter then check the following example:
Example #3: passing mixed type parameter including array parameter to Soap function.
Example of .net operation file
[ServiceContract]
public interface IDynamicWCFService
{
[OperationContract]
string[] HelloYesterday (string[] testA, string testB, int testC );
}
PHP code
<?php
$url="http://99-mxl9461k9f:6062/DynamicWCFService.svc?WSDL";
$client = new SoapClient($url, array( "trace" => 1 ));
$params = array(
"testA" => array(0=>"Value1",1=>"Value2",2=>"Value3"),
"testB" => “this is string abc”,
"testC" =>123
); // consider the first parameter is an array, and other parameters are string & int type.
$result = $client->GetData($params);
var_dump($result);
$respXML = $client->__getLastResponse();
$requXML = $client->__getLastRequest();
echo "Request: <br>";
var_dump($requXML);
echo "Response: <br>";
var_dump($respXML);
?>
Hope the above examples will help.
Since you're passing the wsdl location into the SoapClient constructor, you should be able to call $client->HelloTomorrow($args). There seem to be a few typos, though, can you verify that they are all correct in your actual code? In your web service code, you name the function HellowTomorrow but you're calling HelloTomorrow in your PHP code. Also, the parameter is named sret in your web service, but it's being passed as param1 in the $args associative array. Does it work calling HelloWorld() which doesn't expect any parameters?
Update:
See NuSOAP and content type
Try using the built-in PHP SoapClient instead of the NuSOAP version. PHP's SoapClient looks like it defaults to UTF-8, where NuSOAP seems to be hard-coded to ISO-8859-1

How do I use php to hit a web service I created using gSoap and C++?

I have created the gSOAP Calculator Service example found at: http://www.genivia.com/Products/gsoap/demos/index.html
I have my web service running as a deamon on my Solaris box.
Now I'm trying to use a php page to hit this new web service. I have been looking at http://www.php.net/manual/en/class.soapclient.php, and have tried to make an example, but have had no luck. Can someone please point me to an example of doing this? or show me the code for doing it?
I have spent two days looking at web sites and trying different things and am running out of time on my project. Thank you so much for your help.
fyi: I have my apache server set to port 7000.
<?php
function customError($errno, $errstr)
{
echo "<b>Error: </b> [$errno] $errstr";
}
set_error_handler("customError");
define("SOAP_ENCODED", 1);
define("SOAP_RPC", 1);
$options = array(
'compression'=>true,
'exceptions'=>false,
'trace'=>true,
'use' => SOAP_ENCODED,
'style'=> SOAP_RPC,
'location'=> "http://localhost:7000",
'uri' => "urn:calc"
);
echo "1";
$client = #new SoapClient(null, $options);
echo "2";
$args = array(2, 3);
$ret = $client->__soapCall("add", $args);
echo "3";
if (is_soap_fault($ret))
{
echo 'fault : ';
var_dump($client->__getLastRequest());
var_dump($client->__getLastRequestHeaders());
}
else
{
echo 'success : ';
print '__'.$ret.'__';
}
$client->ns__allAllowed();
?>
The web page does not return any errors.
Michael
At the top of the script:
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
Some things to check:
Include Unicode Signature (BOM) is off in your editor
No white space after ?> (You should just remove it)
Run the script in cli php /path/myscript.php
In the tutorial you mentioned written that Calc web service generates WSDL. WSDL is a file that describes all methods and types of web service. Keeping this in mind you can create SOAP client in PHP:
$client = new SoapClient('http://www.mysite.com/calc.wsdl',
array('trace' => true, 'exceptions' => true));
Then you can call any method provided by Web service:
try {
$client = new SoapClient('http://www.mysite.com/calc.wsdl',
array('trace' => true, 'exceptions' => true));
$result = $client->methodName($param1, $param2);
} catch (SoapFault $e) {
var_dump($e);
}
var_dump($result);
If some error will occur you'll catch it in try/catch block.

Help using SOAP for login

I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website.
My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things.
The national organization sent me this information:
Fields to collect on a form
mausername
mapassword
Static variables
componenttype Value: Chapter
components Value: NM
authusername Value: NMChap
authpassword Value: USA
authpagealias Value: Login
The webservice is located here:
https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL
The following fields will be returned:
Email, FirstName, LastName, LoggedIn, Phone_Release, UserName
If LoggedIn returns “true,” the member has been authenticated as a member of the component.
This has been implemented and tested here: http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm
Based on this information and reading the SOAP documentation, this is what I came up with:
$apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL';
$post_data['mausername'] = '107150';
$post_data['mapassword'] = 'barnes';
$post_data['componenttype'] = 'Chapter';
$post_data['components'] = 'NM';
$post_data['authusername'] = 'NMChap';
$post_data['authpassword'] = 'USA';
$post_data['authpagealias'] = 'Login';
$options = array('trace' => 1, 'exceptions' => 0);
$options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth';
try
{
$client = new soapclient($apta_server, $options);
}
catch (Exception $e)
{
}
$client->debug_flag = 1;
try
{
$result = $client->__soapCall('MemberAuth', array($post_data));
echo '<h1>Soap Result</h1><pre>';
print_r($result);
echo '</pre>';
}
catch (SoapFault $fault)
{
echo '<h1>Soap Fault</h1><pre>';
print_r($fault);
echo '</pre>';
}
echo '<pre>getFunctions<br>';
print_r($client->__getFunctions());
echo '</pre>';
echo '<pre>getTypes<br>';
print_r($client->__getTypes());
echo '</pre>';
echo '<pre>getLastResponseHeaders<br>';
print_r($client->__getLastResponseHeaders());
echo '</pre>';
echo '<pre>getLastResponse<br>';
print_r($client->__getLastResponse());
echo '</pre>';
When I print out the result of the __soapCall(), I get a message of: "looks like we got no XML document."
I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: http://rc19.info/test_login.php
First, you have the $options['location'] wrong. Try the location of the actual web service:
$options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc';
Second, though not necessary, you don't have to call $client->__call("MemberAuth"). You can do $client->MemberAuth() and pass the parameters in like so:
$result = $client->MemberAuth($post_data['mausername'],$post_data['mapassword'],$post_data['componenttype'],$post_data['components'],$post_data['authusername'],$post_data['authpassword'],$post_data['authpagealias']);
You've got a superfluous array in there (you could see that with $client->__lastRequest(), so change:
$result = $client->__soapCall('MemberAuth', array($post_data));
To:
$result = $client->__soapCall('MemberAuth', $post_data);
After that, I get either an 'could not connect to host' (if I follow the port of the WSDL, https://aptaweb.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc), or a redirect (302) to the website with a bunch of cookies set if I choose yours (https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth). Use a stream_context with $context = stream_context_create(array('http'=>array('max_redirects'=>1))); and $client->__getLastRequestHeaders(); to see the redirect in action.
Curiously enough, Bob's solution of https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc works, but is in no way indicated by the wsdl itself as far as I can tell.

Categories