Soap is not working in PHP - php

I am using SoapClient but I am not able to get the result. I get this error:
The server was unable to process the request due to an internal error.
For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
or from the configuration behavior) on the server in order to send the
exception information back to the client, or turn on tracing as per
the Microsoft .NET Framework 3.0 SDK documentation and inspect the
server trace logs.
<?php
$silverpop = new SoapClient($my_url, array('trace' => 1));
/*$client = new stdClass();
$client->LoginID = 'mylogin-id';
$client->LicenceKey = 'mylicense-key';*/
$clientobj = (object) array("LoginID" => "mylogin-id", "LicenceKey" => "mylicense-key");
try {
//$var = $silverpop->__soapCall("GetServicesforPincode",array('P_Pincode'=>'110014','P_ClientObject'=>$clientobj));
//$var = $silverpop->GetServicesforPincode('110014',$clientobj);
$var = $silverpop -> __soapCall("GetServicesforPincode", array('110014', $clientobj));
} catch (SoapFault $exception) {
echo $exception -> getMessage();
}
echo '<pre>';
print_r($var);
?>
What am I doing wrong?

Either you have send your data not according to the specifications or your SoapServer is not working. I think the first one as Soap isn't always as clear as it should. As it looks like the error message is actually generated by the SoapServer, I recommend checking the schema for allowed parameters/calls and their format. If that's all correct, check if you are missing headers etc.
If all of the above is correct, fix your SoapServer. If you haven't gotten access to it, poke the owner.

try{
$client = new SoapClient($my_url,array('trace' => 1));
$object = new stdClass();
$object->LoginID = 'mylogin-id';
$object->LicenceKey = 'mylicense-key';
$xml = simplexml_load_string($client->GetServicesforPincode($object));
$json = json_encode($xml);
print_r($json);
}
catch (SoapFault $exception) { echo $exception; }

Related

file_get_contents(url... when the url server is down

I run a bunch of servers that I monitor on a minutely basis from another server. The relevant bit of code goes like this
$ctx = stream_context_create(array('http'=>array('timeout'=>10)));
try
{
$mei = file_get_contents("https://url/status.php?key=shhh",false,$ctx);
} catch(Exception $e)
{
trigger_error($e->getMessage());
$mei = null;
}
I started providing a stream context when I realized that if one of the monitored servers is down the whole setup stops working and returns a 504, Bad Gateway, error.
Everything good so far. What puzzles me is this - for some reason the 10s timeout is triggering an error message in my Nginx log file but I am unable to catch the exception in my code above. I should mention that this is NOT and error_reporting issue. I checked my error_reporting settings and, for good measure, tried with error_reporting(E_ALL) right at the top.
I could always just stick in an # prior to file_get_contents and everything would be fine but this puzzles me - either I need to stop working and spot my mistake here or else there is another issue at work.
In PHP (>=7) it would be better to catch \Throwable type, because it's the base class for both Error and Exception.
$ctx = stream_context_create(array('http'=>array('timeout'=>10)));
try
{
$mei = file_get_contents("https://url/status.php?key=shhh",false,$ctx);
}
catch(\Throwable $e)
{
trigger_error($e->getMessage());
$mei = null;
}
Use Guzzle or curl to verify the availability of the server prior your request the it's file_get_contents.
can be prettier but you get the point:
$server = 'https://url/status.php?key=shhh';
$client = new GuzzleHttp\Client();
$res = $client->request('GET', $server);
if ($res->getStatusCode() == 200) {
$ctx = stream_context_create(array('http' => array('timeout' => 10)));
try {
$mei = file_get_contents($server, false, $ctx);
} catch (Exception $e) {
trigger_error($e->getMessage());
$mei = null;
}
}

SOAP Request from PHP is not working

I have a web service available # http://www.xxxxx/zzzzzzzz/service.asmx and I am trying to send a SOAP request for method - some_function with both the parameters but still not able to get the connection through.
This is my code:
<?php
$param = array('cedula'=>'XXXX','contrasena'=>'YYYYYY');
$client = new SoapClient("http://www.xxxxx/zzzzzzzz/service.asmx?wsdl");
$result = $client->__soapCall('some_function', $param);
print $result;
?>
Error that I'm getting is:
Fatal error: Uncaught SoapFault exception: [soap:Server] Server was unable to process request. ---> Object reference not set to an instance of an object. in /home/zzzz/XXXXXXXXXX.com/uni/index.php:6 Stack trace: #0 /home/zzzz/XXXXXXXXXX.com/uni/index.php(6): SoapClient->__soapCall('some_function' , Array) #1 {main} thrown in /home/zzzz/XXXXXXXXXX.com/uni/index.php on line 6
Please suggest the corrections. Many thanks in advance :)
Thanks #dootzky & #lulco. I have solved this. Code below works perfectly fine for me:
<?php
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
$wsdl_path = "http://www.xxxxxxx/zzzzzzzzzz/service.asmx?WSDL";
$login_id = 'XXXX';
$password = 'YYYYYY';
$client = new SoapClient($wsdl_path, array('trace' => 1));
try {
echo "<pre>\n";
$result = $client->SOME_FUNCTION(array("request" => array("cedula" => $login_id, "contrasena" => $password)))
print_r($result);
echo "\n";
}
catch (SoapFault $exception) {
echo $exception;
}
?>
I think you are very close to getting this code to work. I would also give credit to this answer on StackOverflow, looks very similar to what you are asking:
"Object reference not set to an instance of an object" error connecting to SOAP server from PHP
So maybe you should just shoot the method directly, like so:
$client->SOME_FUNCTION(array("request" => array('cedula'=>'XXXX','contrasena'=>'YYYYYY'));
Hope that helps! :)
I think it could be problem in wsdl for service SOME_FUNCTION.
Here is the list of services:
http://www.xxxxxx/zzzzzzzzzz/service.asmx
All of them work, but SOME_FUNCTION doesn't. Go to url http://www.xxxxxx/zzzzzzzzzz/service.asmx?op=SOME_FUNCTION and try to set parameters and click Invoke. It will not work and throw exception "Object reference not set to an instance of an object.".
Then try another service, it will work and return some result.
Example for OTHER_FUNCTION service works:
$param = array('estatus'=>'XXXX');
$client = new SoapClient("http://www.xxxxxx/zzzzzzzzzz/service.asmx?wsdl");
$result = $client->__soapCall('OTHER_FUNCTION', $param);
print_r($result);

WSO2AS Soapcall of service returns null

I'm developing a web-app, which needs data from a database.
For the communication with the db I use WSO2AS.
I made a database and linked that to the data service created, when i test the service in the admin panel of WSO2, I get the data needed from the database.
The data service I created is called TestService.
Now I want to have the same response in my php template as well, using this code.
<?php
try {
$client = new SoapClient('http://192.168.178.12:9763/services/TestService?wsdl');
$result = $client->__soapCall('greet');
printf("Result = %s\r\n", $result->return);
} catch (Exception $e) {
printf("Message = %s\r\n",$e->__toString());
}
?>
But this gives NULL, when I try to dump the $result.
When I try to execute an example WSO2 created, I do get the right result. While the soapcall code is the same, only the service name is different.
<?php
try {
$client = new SoapClient('http://192.168.178.12:9763/services/HelloService?wsdl');
$result = $client->__soapCall('greet', array(array('name' => 'Sam')));
printf("Result = %s\r\n", $result->return);
} catch (Exception $e) {
printf("Message = %s\r\n",$e->__toString());
}
?>
This code returns "Hello Sam !!!".
So I wonder what I did wrong, I personally think I made a mistake in implementing the service itself, but can't find it.
If any more information is needed feel free to ask, hope someone can help me with this.
Thanks in advance!
Apparently you need to have arguments in your soapcall.
After calling this __soapCall('greet', array());
It gave the proper response.

PHP Soap Client and .NET Web Service

Hi everyone Im trying to consume a .NET with PHP using SoapClient but I got the following issue when my php client send the request, the .NET WS doesnt get the request xml on the right format heres my code i hope some one help me, thanks ind advice
class login {
public $User;
public $Password;
}
$logr = new login;
$logr->User = 'user';
$logr->Password = 'pass';
try {
$client = new soapclient ("http://..../Service.asmx?WSDL", array('classmap' => array('LoginRequest' => 'login'),));
print_r($logr);
$client -> Login ($logr);
}
catch (Exception $e) {
echo "Error!<br />";
echo $e -> getMessage ();
}
when i test my .net webserver on a .net application i send this, and it works well
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2011/XMLScheme">
<soap:Body>
<Login
xmlns="http://tempuri.org">
<LoginRequest>
<User>user</User>
<Password>pass</Password>
</LoginRequest>
</Login
</soap:Body>
</soap:Envelope>
but when i test it on php i get this, and this error Server was unable to process request. ---> Object reference not set to an instance of an object.
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope"
xmlns:ns1="http://tempuri.org"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<SOAP-ENV:Body>
<Login
xmlns="http://tempuri.com"
xso:type="ns1:LoginRequest">
<User>user</User>
<Password>pass</Password>
</Login>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
class LoginRequest {
public $User;
public $Password;
public function __construct($usr, $pwd) {
$this->User = $usr;
$this->Password = $pwd;
}
}
$login = new LoginRequest('user', 'password');
$client = new SoapClient('http://..../services.asmx?wsdl');
$client->login($login); // try 1
$client->login(array('LoginRequest' => $login)); //try 2
To use a .Net web service, using the NetBeans IDE, add a 'service' and point to the .net web service (make sure to put ?WSDL at the end), and then drag and drop from the 'service's ' toolbox to a php file and it writes the code for you :)
Works great too.
[I can't say what's wrong with your code though]
I recently ran into this issue as well when helping a customer consume our .Net web service so I thought I would share in case anyone else came across this in the future.
Thanks to adudly for providing guidance that helped shed light on the issue. You have to provide a name for the parameter in the array, and note that the name is case sensitive.
Working Code
try {
$wsdl_url = 'http://<mywebserver>/LeadWs.svc?wsdl';
$client = new SOAPClient($wsdl_url);
$params = array(
'lead' => ""
);
$return = $client->Insert2($params);
print_r($return);
} catch (Exception $e) {
echo "Exception occurred: " . $e;
}
My failed attempts used a capital 'L' for Lead. This is apparently the only thing in the WSDLs/XSDs that is lowercase by default. If you do a careful search through the WSDLs/XSDs you will see the exact names of any parameters your method expects. Once you get those right, SoapClient handles the rest of the XML encoding.
My final Code looked like this:
try {
$wsdl_url = 'http://<mywebserver>/LeadWs.svc?wsdl';
$client = new SOAPClient($wsdl_url);
$lead = new Lead(); // Could just be an array as well
// but I created a class to help the user
$lead->FirstName = "Tester";
$lead->LastName = "Test";
$lead->ZipCode = "00000";
$lead->NumberOfTVs = 2;
$params = array('lead' => $lead);
$return = $client->Insert2($params);
print_r($return);
} catch (Exception $e) {
echo "Exception occurred: " . $e;
}
Hope that helps someone in the future.
You can use SoapHeader and setSoapHeaders here

PHP SOAP error catching

I'm getting desperate, all I want is simple error handling when the PHP SOAP Web Service is down to echo an error message login service down. Please help me!
At the moment it's still displaying the error (along with warnings...):
Fatal error: SOAP-ERROR: Parsing WSDL
Here is the script:
<?php
session_start();
$login="0000000000000nhfidsj"; //It is like this for testing, It will be changed to a GET
$username = substr($login,0,13); //as password is always 13 char long
//(the validation is done int he javascript)
$password = substr($login,13);
try
{
ini_set('default_socket_timeout', 5); //So time out is 5 seconds
$client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl"); //locally hosted
$array = $client->login(array('username'=>$username,
'password'=>$password));
$result = $array->return;
}catch(SoapFault $client){
$result = "0";
}
if($result == "true")//as this would be what the ws returns if login success
{
$_SESSION['user'] = $login;
echo "00";
}
else
{
echo "01 error: login failed";
}
?>
UPDATE July 2018
If you don't care about getting the SoapFault details and just want to catch any errors coming from the SoapClient you can catch "Throwable" in PHP 7+. The original problem was that SoapClient can "Fatal Error" before it throws a SoapFault so by catching both errors and exceptions with Throwable you will have very simple error handling e.g.
try{
soap connection...
}catch(Throwable $e){
echo 'sorry... our service is down';
}
If you need to catch the SoapFault specifically, try the original answer which should allow you to suppress the fatal error that prevents the SoapFault being thrown
Original answer relevant for older PHP versions
SOAP can fatal error calling the native php functions internally which prevents the SoapFaults being thrown so we need to log and suppress those native errors.
First you need to turn on exceptions handling:
try {
$client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl",array(
'exceptions' => true,
));
} catch ( SoapFault $e ) { // Do NOT try and catch "Exception" here
echo 'sorry... our service is down';
}
AND THEN you also need to silently suppress any "PHP errors" that originate from SOAP using a custom error handler:
set_error_handler('handlePhpErrors');
function handlePhpErrors($errno, $errmsg, $filename, $linenum, $vars) {
if (stristr($errmsg, "SoapClient::SoapClient")) {
error_log($errmsg); // silently log error
return; // skip error handling
}
}
You will then find it now instead trips a SoapFault exception with the correct message "Soap error: SOAP-ERROR: Parsing WSDL: Couldn't load from '...'" and so you end up back in your catch statement able to handle the error more effectively.
Fatal error: SOAP-ERROR: Parsing WSDL Means the WSDL is wrong and maybe missing? so it's not related to soap. And you cannot handle FATAL ERROR with a try catch. See this link : http://ru2.php.net/set_error_handler#35622
What do you get when you try to access http://192.168.0.142:8080/services/Logon?wsdl in your browser?
You can check if the WSDL is present like this
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
/* You don't have a WSDL Service is down. exit the function */
}
curl_close($handle);
/* Do your stuff with SOAP here. */
Unfortunately SOAP throws a fatal error when the service is down / unreachable rather than returning a SoapFault object.
That being said, you can set it to throw an exception. You probably omitted the part where you're setting the exceptions soap_client option to false
$client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl",array(
'exceptions' => false, // change to true so it will throw an exception
));
Catch the exception when service is down:
try {
$client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl",array(
'exceptions' => true,
));
}
catch ( Exception $e )
{
echo 'sorry... our service is down';
}
Perhaps a better alternative:
set_error_handler('my_error_handler');
set_exception_handler('my_exception_handler');
function my_exception_handler($e) {
exit('Error, something went terribly wrong: '.$e);
}
function my_error_handler($no,$str,$file,$line) {
$e = new ErrorException($str,$no,0,$file,$line);
my_exception_handler($e);
}
Where you can adjust error messages in the mentioned functions.
I use it to return a message in the same situation you do, as it can occur at any time.
Say you send a soap message after the initial login, and that response never arrives or arrives only partially, this way you can return a message without any script paths, names and linenumbers.
In such cases I do not return $e at all, instead I just output something like: 'Something went wrong, please try it again (later).'
I ended up handling it this way:
libxml_use_internal_errors(true);
$sxe = simplexml_load_string(file_get_contents($url));
if (!$sxe) {
return [
'error' => true,
'info' => 'WSDL does not return valid xml',
];
}
libxml_use_internal_errors(false);
Do your soap call after this check.
Everything turned out to be much more trivial - when using namespaces, be sure to specify the root ns!
Those catch (SoapFailt $fault) - is wrong, right way catch (\SoapFault $fault)
SoapFault doesn't extends Exception, catch the especific type works:
try {
$client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl",array(
'exceptions' => true,
));
}
catch ( SoapFault $e )
{
echo 'sorry... our service is down';
}

Categories