How to send parameters via the URL to PHP from Flex HttpService - php

Forgive me if this has already been answered/ is extremely basic/ the question is worded incorrectly, I am very new to this and struggling.
Basically I have back end PHP which generates XML, the flash builder then inherits the data. Where I'm stuck is understanding how the flash builder can send a parameter to the PHP through an HttpService e.g
This is what it currently interprets:
http://..../file.php?action=getitems
What I would like the flash builder to send is
&class=fruit (<- the class would be dependant on what is selected from the drop down in the application)
to overall create this string
http://..../file.php?action=getitems&class=fruit
Thank you and apologies if this is nonsense. I'm using Flash Builder 4.

This is actually rather simple in Flex...
var service : HTTPService = new HTTPService();
service.url = "http://localhost/getData.php";
service.method = "POST";
var parameters:Object = new Object();
parameters["action"] = "getitems";
parameters["class"] = "fruit";
service.send(parameters);
... done!

Overall I would use the push method instead of passing a variable, lessens the chance of getting hacked from the middle.
My AS3 Code for the http call:
public function someRequest() : void
{
var service : HTTPService = new HTTPService();
service.url = "http://localhost/getData.php";
service.useProxy = false;
service.method = "POST";
service.contentType = "application/xml"; // Pass XML data.
service.request = "<ID>somevalue</ID>"; // The XML data.
service.resultFormat = "xml"; // Recieve XML data.
service.addEventListener(ResultEvent.RESULT, createFields);
service.addEventListener(FaultEvent.FAULT, handleFault);
service.send();
}
private function createFields(event : ResultEvent) : void
{
var result : String = event.result.toString();
returnData = XML(result);
}
private function handleFault(event : FaultEvent) : void
{
var faultstring : String = event.fault.faultString;
Alert.show(faultstring);
}
As you see toward the middle, there is an XML space for entering a variable. I use this approach to pass data back and forth from the PHP to the AS3.
The PHP is:
<?php
define("DATABASE_SERVER", "localhost");
define("DATABASE_USERNAME", "root");
define("DATABASE_PASSWORD", "**");
define("DATABASE_NAME", "dbName");
//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
$Query = "SELECT * from data WHERE employeeID = '" . ($_POST['ID']) . "'";
$Result = mysql_query($Query);
$Return = "<data>";
while ($User = mysql_fetch_object($Result))
{
$Return .= "<user><userid>" . $User->userid . "</userid><username>" . $User->username . "</username><emailaddress>" . $User->emailaddress . "</emailaddress></user>";
}
$Return .= "</data>";
mysql_free_result($Result);
print ($Return)
?>
Hope that helps you on your way.

I generally handle this through [POST] instead of [GET]
In your actionscript function:
private function sendRequest():void {
var obj:Object = new Object();
obj.action="getitems";
obj.class="fruit";
myService.send(obj);
Your httpService
<s:HTTPService id='myService' url='urlToYourPHP' method='POST' result='yourResultHandler' fault='yourFaultHandler' resultFormat='XML'/>
As powelljf3 said, POST is more secure then GET though it can still be gotten to.

Related

How to show return values fom a PHP XML-RPC call?

I can't seem to find any code to display returned values from the call.
I am running the xml-lib from the software vendor at the following link
https://support.sippysoft.com/support/solutions/articles/3000013653-xml-rpc-api-sign-up-html-page-fresh-version-
<?php
include 'xmlrpc/xmlrpc.inc';
function listAccounts()
{
//$params = array(new xmlrpcval(array("i_account"=> new xmlrpcval('14719', "string")), 'struct'));
$msg = new xmlrpcmsg('listAccounts');
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('https://DOMAINHERE/xmlapi/xmlapi');
$cli->setSSLVerifyPeer(false);
$cli->setSSLVerifyHost(false);
$cli->setCredentials('USERNAME', 'PASSWORD', CURLAUTH_DIGEST);
$r = $cli->send($msg, 20);
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
print_r ($r->faultString());
return false;
}
else
{
return $r->value();
// I need something here to write returned values to normal PHP variable
}
}
Ok thanks to the comment from halfer.
I managed to get the issue and digging through the code in the library I found a function that does the trick.
Thanks a million for your pointer it really helped.
I am new to php and xml and the learning curve is quite tall but thanks.
for someone else reference maybe in the future here is the corrected code with the last 2 lines that does the magic for me.
<?php
include 'xmlrpc/xmlrpc.inc';
// $params = array(new xmlrpcval(array("offset"=> new xmlrpcval("1", "int")
// ,"i_customer"=> new xmlrpcval("321", "int")
// ), 'struct'));
$params = array(new xmlrpcval(array("i_customer"=> new xmlrpcval("321", "int")
), 'struct'));
$msg = new xmlrpcmsg('listAccounts', $params);
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('DOMAIN');
$cli->setSSLVerifyPeer(false);
$cli->setdebug(0);
$r = $cli->send($msg, 20); /* 20 seconds timeout */
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
echo $r->faultString();
}
// now lets decode the xml response..
$values=php_xmlrpc_decode($r->value());
var_dump ($values['accounts'][0][username]);
?>

EWS CreateAttachment API call not working

I'm currently facing some problems with the CreateAttachment API call in EWS 2010. We are using PHP 5.5 with curl 7.49.1.
We are currently using the following little script to test this issue:
$ewswrapper = new EWSWrapper($host, $user, $pass);
try {
// See examples:
//
// http://jamesarmes.com/php-ews/doc/0.1/examples/contact-set-update-photo.html
// https://github.com/jamesiarmes/php-ews/blob/master/examples/contact/set-photo.php
$picture = base64_decode(" ... some valid base64 image ... ");
$attachment = new EWSType_FileAttachmentType();
$attachment->IsContactPhoto = true;
$attachment->Content = $picture;
$attachment->Name = "ContactPicture.jpg";
$attachment->ContentType = "image/png";
// Create the attachment request
$attRequest = new EWSType_CreateAttachmentType();
$attRequest->ParentItemId = new EWSType_ItemIdType();
$attRequest->ParentItemId->Id = " ... some ItemId of a contact ... ";
$attRequest->ParentItemId->ChangeKey = " ... some ChangeKey of the contact ... ";
$attRequest->Attachments = new EWSType_NonEmptyArrayOfAttachmentsType();
$attRequest->Attachments->FileAttachment = [];
$attRequest->Attachments->FileAttachment[] = $attachment;
$ewswrapper->service->CreateAttachment($attRequest);
} catch (Exception $e) {
var_dump($e->getMessage());
}
The returned status code of the response is 100. As far as we can tell, the response is empty. Dumping the request before sending it shows us a valid xml output that should theoretically work. We have checked both the official Microsoft documentation at https://msdn.microsoft.com/en-us/library/office/aa565931(v=exchg.140).aspx and the API examples at http://jamesarmes.com/php-ews/doc/0.1/examples/contact-set-update-photo.html.
Other requests to the API work perfectly. We can create, update, query and delete just fine, it seems to be this request specifically which fails.
We would highly appreciate any pointers into the right direction! Thanks in advance! If more information is needed regarding the code, infrastructure, etc, please ask!

Cannot instantiate a Note object using Evernote API in PHP

I am trying to develop a script (using the PHP example app as a basis) that will post a note to Evernote based on GET values.
When I insert this to the end of functions.php's listNotebooks()
$note_obj = new Note(array(
'contents' => $note_contents,
'title' => $title
));
It throws a 500 error. (In my code, $title & $note_contents are defined earlier. I have spent a lot of time trying to find proper documentation for the PHP API but it just seems non-existent. Any information on this topic would be greatly appreciated
Update: I did not realize the API was using PHP Namespaces: This fixed the issue:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
My code to add a note still does not work but I'll post it here once I figure it out.
These classes need to be imported:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
This will define our new note:
$noteAttr = new NoteAttributes();
$noteAttr->sourceURL = "http://www.example.com";
$note = new Note();
$note->guid = null;
$note->title = "My Title";
$note->content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd"><en-note>My Content</en-note>';
$note->contentHash = null;
$note->contentLength = null;
$note->created = time()*1000;
$note->updated = time()*1000;
$note->deleted = null;
$note->active = null;
$note->updateSequenceNum = null;
$note->notebookGuid = null;
$note->tagGuids = null;
$note->resources = null;
$note->attributes = $noteAttr;
$note->tagNames = null;
addNote($note);
This function will add a new note:
function addNote($newnote) {
global $noteRet;
if (empty($noteRet)) {
define("noteStoreHost", "sandbox.evernote.com");
define("noteStorePort", "80");
define("noteStoreProto", "https");
define("noteStoreUrl", "edam/note/");
$noteStoreTrans = new THttpClient(noteStoreHost, noteStorePort, noteStoreUrl . $_SESSION['shardId'], noteStoreProto);
$noteStoreProt = new TBinaryProtocol($noteStoreTrans);
$noteStore = new NoteStoreClient($noteStoreProt, $noteStoreProt);
$noteRet = $noteStore->createNote($_SESSION['accessToken'], $newnote);
return $noteRet;
}
}

PHP+SoapClient exceptions and headers? (UPS Rating)

I'm trying to use PHP and SoapClient to utilize the UPS Ratings web service. I found a nice tool called WSDLInterpreter to create a starting point library for creating the service requests, but regardless what I try I keep getting the same (non-descriptive) error:
EXCEPTION=SoapFault::__set_state(array(
'message' => 'An exception has been raised as a result of client data.',
'string' => '',
'code' => 0,
Um ok, what the hell does this mean?
Unlike some of the other web service tools I have implemented, the UPS Soap wants a security block put into the header. I tried doing raw associative array data but I wasn't sure 100% if I was injecting the header part correctly.
Using the WSDLInterpreter, it pulls out a RateService class with a ProcessRate method that excepts it's own (instance) datastructure for the RateRequest and UPSSecurity portions, but all of the above generates that same error.
Here's a sample of the code that I'm using that calls classes defined by the interpreter:
require_once "Shipping/UPS/RateService.php"; // WSDLInterpreter class library
class Query
{
// constants removed for stackoverflow that define (proprietary) security items
private $_upss;
private $_shpr;
// use Interpreter code's RateRequest class to send with ProcessRate
public function soapRateRequest(RateRequest $req, UPSSecurity $upss = null)
{
$res = false;
if (!isset($upss)) {
$upss = $this->__getUPSS();
}
echo "SECURITY:\n" . var_export($upss, 1) . "\n";
$upsrs = new RateService(self::UPS_WSDL);
try {
$res = $upsrs->ProcessRate($req, $upss);
} catch (SoapFault $exception) {
echo 'EXCEPTION=' . var_export($exception, 1) . "\n";
}
return $res;
}
// create a soap data structure to send to web service from shipment
public function getRequestSoap(Shipment $shpmnt)
{
$qs = new RateRequest();
// pickup information
$qs->PickupType->Code = '01';
$qs->Shipment->Shipper = $this->__getAcctInfo();
// Ship To address
$qs->Shipment->ShipTo->Address->AddressLine = $this->__getAddressArray($shpmnt->destAddress->address1, $shpmnt->destAddress->address2);
$qs->Shipment->ShipTo->Address->City = $shpmnt->destAddress->city;
$qs->Shipment->ShipTo->Address->StateProvinceCode = $shpmnt->destAddress->state;
$qs->Shipment->ShipTo->Address->PostalCode = $shpmnt->destAddress->zip;
$qs->Shipment->ShipTo->Address->CountryCode = $shpmnt->destAddress->country;
$qs->Shipment->ShipTo->Name = $shpmnt->destAddress->name;
// Ship From address
$qs->Shipment->ShipFrom->Address->AddressLine = $this->__getAddressArray($shpmnt->origAddress->address1, $shpmnt->origAddress->address2);
$qs->Shipment->ShipFrom->Address->City = $shpmnt->origAddress->city;
$qs->Shipment->ShipFrom->Address->StateProvinceCode = $shpmnt->origAddress->state;
$qs->Shipment->ShipFrom->Address->PostalCode = $shpmnt->origAddress->zip;
$qs->Shipment->ShipFrom->Address->CountryCode = $shpmnt->origAddress->country;
$qs->Shipment->ShipFrom->Name = $shpmnt->origAddress->name;
// Service type
// TODO cycle through available services
$qs->Shipment->Service->Code = "03";
$qs->Shipment->Service->Description = "UPS Ground";
// Package information
$pkg = new PackageType();
$pkg->PackagingType->Code = "02";
$pkg->PackagingType->Description = "Package/customer supplied";
// dimensions
$pkg->Dimensions->UnitOfMeasurement->Code = $shpmnt->dimensions->dimensionsUnit;
$pkg->Dimensions->Length = $shpmnt->dimensions->length;
$pkg->Dimensions->Width = $shpmnt->dimensions->width;
$pkg->Dimensions->Height = $shpmnt->dimensions->height;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageServiceOptions->DeclaredValue->MonetaryValue = $shpmnt->dimensions->value;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageWeight->UnitOfMeasurement = $this->__getWeightUnit($shpmnt->dimensions->weightUnit);
$pkg->PackageWeight->Weight = $shpmnt->dimensions->weight;
$qs->Shipment->Package = $pkg;
$qs->CustomerClassification->Code = 123456;
$qs->CustomerClassification->Description = "test_rate_request";
return $qs;
}
// fill out and return a UPSSecurity data structure
private function __getUPSS()
{
if (!isset($this->_upss)) {
$unmt = new UsernameToken();
$unmt->Username = self::UPSS_USERNAME;
$unmt->Password = self::UPSS_PASSWORD;
$sat = new ServiceAccessToken();
$sat->AccessLicenseNumber = self::UPSS_ACCESS_LICENSE_NUMBER;
$upss = new UPSSecurity();
$upss->UsernameToken = $unmt;
$upss->ServiceAccessToken = $sat;
$this->_upss = $upss;
}
return $this->_upss;
}
// get our shipper/account info (some items blanked for stackoverflow)
private function __getAcctInfo()
{
if (!isset($this->_shpr)) {
$shpr = new ShipperType();
$shpr->Address->AddressLine = array(
"CONTACT",
"STREET ADDRESS"
);
$shpr->Address->City = "CITY";
$shpr->Address->StateProvinceCode = "MI";
$shpr->Address->PostalCode = "ZIPCODE";
$shpr->Address->CountryCode = "US";
$shpr = new ShipperType();
$shpr->Name = "COMPANY NAME";
$shpr->ShipperNumber = self::UPS_ACCOUNT_NUMBER;
$shpr->Address = $addr;
$this->_shpr = $shpr;
}
return $this->_shpr;
}
private function __getAddressArray($adr1, $adr2 = null)
{
if (isset($adr2) && $adr2 !== '') {
return array($adr1, $adr2);
} else {
return array($adr1);
}
}
}
It doesn't even seem to be getting to the point of sending anything over the Soap so I am assuming it is dying as a result of something not matching the WSDL info. (keep in mind, I've tried sending just a properly seeded array of key/value details to a manually created SoapClient using the same WSDL file with the same error resulting)
It would just be nice to get an error to let me know what about the 'client data' is a problem. This PHP soap implementation isn't impressing me!
I know this answer is probably way too late, but I'll provide some feedback anyway. In order to make a custom SOAP Header you'll have to override the SoapHeader class.
/*
* Auth Class to extend SOAP Header for WSSE Security
* Usage:
* $header = new upsAuthHeader($user, $password);
* $client = new SoapClient('{...}', array("trace" => 1, "exception" => 0));
* $client->__setSoapHeaders(array($header));
*/
class upsAuthHeader extends SoapHeader
{
...
function __construct($user, $password)
{
// Using SoapVar to set the attributes has proven nearly impossible; no WSDL.
// It might be accomplished with a combined SoapVar and stdClass() approach.
// Security Header - as a combined XSD_ANYXML SoapVar
// This method is much easier to define all of the custom SoapVars with attributes.
$security = '<ns2:Security xmlns:ns2="'.$this->wsse.'">'. // soapenv:mustUnderstand="1"
'<ns2:UsernameToken ns3:Id="UsernameToken-49" xmlns:ns3="'.$this->wsu.'">'.
'<ns2:Username>'.$user.'</ns2:Username>'.
'<ns2:Password Type="'.$this->password_type.'">'.htmlspecialchars($password).'</ns2:Password>'.
'</ns2:UsernameToken>'.
'</ns2:Security>';
$security_sv = new SoapVar($security, XSD_ANYXML);
parent::__construct($this->wsse, 'Security', $security_sv, false);
}
}
Then call the upsAuthHeader() before the soap call.
$client = new SoapClient($this->your_ups_wsdl,
array('trace' => true,
'exceptions' => true,
'soap_version' => SOAP_1_1
)
);
// Auth Header - Security Header
$header = new upsAuthHeader($user, $password);
// Set Header
$client->__setSoapHeaders(array($header));

Array contents not being passed fully from php client to a .NET web service

I want to pass an image as a byte array from php to a .NET web serice.
The php client is as follows:
<?php
class Image{
public $ImgIn = array();
}
$file = file_get_contents('chathura.jpg');
$ImgIn = str_split($file);
foreach ($ImgIn as $key=>$val) { $ImgIn[$key] = ord($val); }
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage(new Image());
echo $result->PutImageResult;
//print_r($ImgIn);
?>
Here is the web method in ASP.NET web service:
[WebMethod]
public string PutImage(byte[] ImgIn)
{
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgIn);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("imageTest", System.Drawing.Imaging.ImageFormat.Jpeg);
return "test";
}
When I run this the image content is correctly read to ImgIm array in php client. (In this instance the image had 16992 elements.) However when the array is passed to the web service method it contains only 5 elements (the first 5 elements of the image)
Can I know what is the reason for the loss of data ? How can I avoid it ?
Thanks
file_get_contents returns the file contents as string which is not useful for binary files such as images. Try this:
$handle = fopen("chathura.jpg", "r");
$contents = fread($handle, filesize("chathura.jpg"));
fclose($handle);
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($contents);
Guys, it seems that it is not going to be any use to try and pass data as a byte array as PHP anyway converts it to a string when sending. This conversion seems to introduce control characters to the string, making it only send a part of the byte array. I got this to work by sending a base64 encoded string and decoding inside the server.
My client side code:
<?php
class Image{
public $ImgIn = '';
}
//ini_set("memory_limit","20M");
$imageData = file_get_contents('chathura.jpg');
$encodedData = base64_encode($imageData);
$Img = new Image();
$Img->ImgIn = $encodedData;
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($Img);
echo($result->PutImageResult);
?>
ASP .NET web service code:
[WebMethod]
public string PutImage(String ImgIn)
{
byte[] ImgInBytes = Convert.FromBase64String(ImgIn);
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgInBytes);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("C:\\imageTest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
return "success";
}

Categories