PHP soap issues - php

Drupal 7-soap
This is the error which iam getting in error log and when iam trying to print the
test.wsdl file
SoapFault: looks like we got no XML document in SoapClient->__call()
I have no clue what is the error
My project environment
PHP : 5.4.11
MySQL : 5.5.27 Apache : 2.2.3
OS : CentOS 5.8
code information
function ai_server() {
ini_set('soap.wsdl_cache_ttl', 0);
$server = new SoapServer(file_create_url(variable_get('app_integration_wsdl')), array("trace" => 1, "exceptions" => 0));
$server->addFunction('getData');
$server->addFunction('getId');
$server->addFunction('getInfo');
$server->addFunction('getrightsInfo');
$server->addFunction('updateInfo');
$server->addFunction('resetAppHistory');
//$server->addFunction('resetAppId');
$server->handle();
}
soap client
function ai_sync_test() {
ini_set('soap.wsdl_cache_ttl', 0);
//
// ---------------------------------------------------------------- basic tests
//
// is settings file accessible
$settings_file = variable_get('app_integration_settings');
require_once($settings_file);
$settings_output = is_readable($settings_file) ? 'Ok! Settings file is readable.' : 'Error! Not readable or accessible.';
// is wsdl file accessible
$wsdl_file = variable_get('app_integration_wsdl');
$wsdl_output = is_readable($wsdl_file) ? 'Ok! WSDL file is readable. ' . l('Open it. ', $wsdl_file, array('attributes' => array('target' => '_blank'))) : 'Error! Not readable or accessible. ';
$wsdl_output .= 'You need to define domain name in it into this sections (at the bottom of app_integration.wsdl file): ';
$wsdl_output .= htmlentities('<soap:address location="http://YOUR_DOMAIN_HERE/app_integration/server"/>');
// methods, which integration service is provide
$client = new SoapClient($wsdl_file, array("trace" => 1, "exceptions" => 0));
$methods = $client->__getFunctions();
$methods_output = '';
foreach ($methods as $method) {
$methods_output .= '<li>' . $method . '</li>';
}

2 possible reasons -
You are echoing something in the code, or whitespace characters are getting printed or trailing new line character.
The server SOAP file in php has encode utf8 with BOM, causing apache send back the BOM mark (3 bytes) before the xml response. Encode your php file soap server with utf8 WITH OUT BOM mark.
function strip_bom($str){
return preg_replace( '/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/', "", $str );
}

Related

How set ApplicationDefaultCredentials in Google Translate api php?

I'm trying to set Google Translation API on my server.
But code returns error "Could not construct ApplicationDefaultCredentials"
$translationClient = new Google\Cloud\Translate\V3\TranslationServiceClient();
putenv('GOOGLE_APPLICATION_CREDENTIALS="/path/to/credetials.json"');
$content = ['one', 'two', 'three'];
$targetLanguage = 'es';
$response = $translationClient->translateText(
$content,
$targetLanguage,
TranslationServiceClient::locationName('[ProjectID]', 'global')
);
$res = '';
foreach ($response->getTranslations() as $key => $translation) {
$separator = $key === 2
? '!'
: ', ';
$res .= $translation->getTranslatedText() . $separator;
}
} catch(\Exception $e) {
$res = $e->getMessage();
}
die(json_encode($res));
I've already spend a lot of time to setting it but with no result.
Please, help me
You can pass the credentials in a config variable and then initialize the client.
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;
/** Uncomment and populate these variables in your code */
$config = ['credentials' => 'key.json'];
$text = "The text to translate.";
$targetLanguage = "ja";
$translate = new TranslateClient($config);
$result = $translate->translate($text, [
"target" => $targetLanguage,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");
?>
Source language: en
Translation: 翻訳するテキスト
Php putenv https://www.php.net/manual/en/function.putenv.php
Andrey this worked for me on Windows 10 Pro. Wampserver 3.2.0. Php 7.4.4. It definitely has a problem with Windows backslashes. Forwardslashes and avoiding double quotes and single quotes together has helped to bump the compiler along.
$file = trim("C:/users/boss/onedrive/desktop/google.json",'"');
putenv("GOOGLE_APPLICATION_CREDENTIALS=$file");

phpleague flysystem read and write to large file on server

I am using flysystem with IRON IO queue and I am attempting to run a DB query that will be taking ~1.8 million records and while doing 5000 at at time. Here is the error message I am receiving with file sizes of 50+ MB:
PHP Fatal error: Allowed memory size of ########## bytes exhausted
Here are the steps I would like to take:
1) Get the data
2) Turn it into a CSV appropriate string (i.e. implode(',', $dataArray) . "\r\n")
3) Get the file from the server (in this case S3)
4) Read that files' contents and append this new string to it and re-write that content to the S3 file
Here is a brief run down of the code I have:
public function fire($job, $data)
{
// First set the headers and write the initial file to server
$this->filesystem->write($this->filename, implode(',', $this->setHeaders($parameters)) . "\r\n", [
'visibility' => 'public',
'mimetype' => 'text/csv',
]);
// Loop to get new sets of data
$offset = 0;
while ($this->exportResult) {
$this->exportResult = $this->getData($parameters, $offset);
if ($this->exportResult) {
$this->writeToFile($this->exportResult);
$offset += 5000;
}
}
}
private function writeToFile($contentToBeAdded = '')
{
$content = $this->filesystem->read($this->filename);
// Append new data
$content .= $contentToBeAdded;
$this->filesystem->update($this->filename, $content, [
'visibility' => 'public'
]);
}
I'm assuming this is NOT the most efficient? I am going off of these docs:
PHPLeague Flysystem
If anyone can point me in a more appropriate direction, that would be awesome!
Flysystem supports read/write/update stream
Please check latest API https://flysystem.thephpleague.com/api/
$stream = fopen('/path/to/database.backup', 'r+');
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream);
// Using write you can also directly set the visibility
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream, [
'visibility' => AdapterInterface::VISIBILITY_PRIVATE
]);
if (is_resource($stream)) {
fclose($stream);
}
// Or update a file with stream contents
$filesystem->updateStream('backups/'.strftime('%G-%m-%d').'.backup', $stream);
// Retrieve a read-stream
$stream = $filesystem->readStream('something/is/here.ext');
$contents = stream_get_contents($stream);
fclose($stream);
// Create or overwrite using a stream.
$putStream = tmpfile();
fwrite($putStream, $contents);
rewind($putStream);
$filesystem->putStream('somewhere/here.txt', $putStream);
if (is_resource($putStream)) {
fclose($putStream);
}
If you are working with S3, I would use the AWS SDK for PHP directly to solve this particular problem. Appending to a file is actually very easy using the SDK's S3 streamwrapper, and doesn't force you to read the entire file into memory.
$s3 = \Aws\S3\S3Client::factory($clientConfig);
$s3->registerStreamWrapper();
$appendHandle = fopen("s3://{$bucket}/{$key}", 'a');
fwrite($appendHandle, $data);
fclose($appendHandle);

To download asmx list files and use them as wsdl files + sharepoint

I am trying to retrieve the data from a list in share-point 2007 through a web-service written in php as:
<?php
//Authentication details
$authParams = array('login' => 'username', 'password' => 'password' , "authentication" => SOAP_AUTHENTICATION_DIGEST);
/* A string that contains either the display name or the GUID for the list.
* It is recommended that you use the GUID, which must be surrounded by curly
* braces ({}).
*/
$listName = "Testlist";
$rowLimit = '150';
/* Local path to the Lists.asmx WSDL file (localhost). You must first download
* it manually from your SharePoint site (which should be available at
* yoursharepointsite.com/subsite/_vti_bin/Lists.asmx?WSDL)
*/
$wsdl = "http://localhost/phpsp/Lists.wsdl";
//Creating the SOAP client and initializing the GetListItems method parameters
$soapClient = new SoapClient($wsdl, $authParams);
$params = array('listName' => $listName, 'rowLimit' => $rowLimit);
//Calling the GetListItems Web Service
$rawXMLresponse = null;
try{
$rawXMLresponse = $soapClient->GetListItems($params)->GetListItemsResult->any;
}
catch(SoapFault $fault){
echo 'Fault code: '.$fault->faultcode;
echo 'Fault string: '.$fault->faultstring;
}
echo '<pre>' . $rawXMLresponse . '</pre>';
..
..
?>
I have lists created in share-point and in the url, the lists display show '.asmx' extension. How can i manually download the lists and use them as '.wsdl' as done in this sample code.
I searched for the same over the net and people tell it can be obtained at:
sharepoint.url/subsite/_vti_bin/Lists.asmx?WSDL
But, i was not able to get the .wsdl files.
Please take this wsdl file from http://sharepointserver:port/_vti_bin/Lists.asmx?wsdl
and save the file as listswsdl.wsdl to your php server in phpsp/listswsdl.wsdl
Lastly, modify this line:
$wsdl = "http://localhost/phpsp/listswsdl.wsdl";

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.

Categories