i have a problem passing ByteArray from flash (as3) to amfphp to save an image.
With old version of amfphp, all worked in the past… now, with new version i have many problem.
I'm using version 2.0.1 and the first problem is that i have to do this, for access to my info:
function SaveAsJPEG($json)
{
$string = json_encode($json);
$obj = json_decode($string);
$compressed = $obj->{'compressed'};
}
in the past i wrote only:
function SaveAsJPEG($json)
{
$compressed = $json['compressed'];
}
Anyway… now i can take all data (if i use " $json['compressed']" i receive an error) but i can't receive my ByteArray data.
From flash i write this:
var tempObj:Object = new Object();
tempObj["jpgStream "]= createBitStream(myBitmmapData); // return ByteArray
tempObj["compressed"] = false;
tempObj["dir"] = linkToSave;
tempObj["name"] = this.imageName;
So.. in my php class i receive all correct info, except "jpgStream" that seems "null".
Do you have any idea?
I think you get 'null' because of json_encode/decode. Try using
$data = (array) $json;
$compressed = $data['compressed'];
This may help http://www.silexlabs.org/amfphp/documentation/data-types/
Related
I'm trying to Verifying that requests originate from Office for the web by using proof keys
I have read this resource many times but still do not know how to implement it in PHP.
I tried the code below it didn't seem to solve the problem, I do not know what to do next.
Can someone give me a suggestion?
$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(base64_decode($modulus), 256);
$exponent = new Math_BigInteger(base64_decode($exponent), 256);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey();
$publicKey = $rsa->getPublicKey();
I understand that verifying WOPI proof key is quite complicated to implement while extracting programming logic from their explanation in the document is challenging.
Unfortunately, I'm not a PHP developer. However, I'd like to share my production C# code in case it could help.
private async Task<bool> ValidateWopiProof(HttpContext context)
{
// Make sure the request has the correct headers
if (!context.Request.Headers.ContainsKey(WopiRequestHeader.PROOF) ||
!context.Request.Headers.ContainsKey(WopiRequestHeader.TIME_STAMP))
return false;
// TimestampOlderThan20Min
var timeStamp = long.Parse(context.Request.Headers[WopiRequestHeader.TIME_STAMP].ToString());
var timeStampDateTime = new DateTime(timeStamp, DateTimeKind.Utc);
if ((DateTime.UtcNow - timeStampDateTime).TotalMinutes > 20)
return false;
// Set the requested proof values
var requestProof = context.Request.Headers[WopiRequestHeader.PROOF];
var requestProofOld = String.Empty;
if (context.Request.Headers.ContainsKey(WopiRequestHeader.PROOF_OLD))
requestProofOld = context.Request.Headers[WopiRequestHeader.PROOF_OLD];
// Get the WOPI proof info from Wopi discovery
var wopiProofPublicKey = await _wopiDiscovery.GetWopiProof();
// Encode the values into bytes
var accessTokenBytes = Encoding.UTF8.GetBytes(context.Request.Query["access_token"].ToString());
var hostUrl = GetAbsolouteUrl(context);
var hostUrlBytes = Encoding.UTF8.GetBytes(hostUrl.ToUpperInvariant());
var timeStampBytes = BitConverter.GetBytes(Convert.ToInt64(context.Request.Headers[WopiRequestHeader.TIME_STAMP])).Reverse().ToArray();
// Build expected proof
List<byte> expected = new List<byte>(
4 + accessTokenBytes.Length +
4 + hostUrlBytes.Length +
4 + timeStampBytes.Length);
// Add the values to the expected variable
expected.AddRange(BitConverter.GetBytes(accessTokenBytes.Length).Reverse().ToArray());
expected.AddRange(accessTokenBytes);
expected.AddRange(BitConverter.GetBytes(hostUrlBytes.Length).Reverse().ToArray());
expected.AddRange(hostUrlBytes);
expected.AddRange(BitConverter.GetBytes(timeStampBytes.Length).Reverse().ToArray());
expected.AddRange(timeStampBytes);
byte[] expectedBytes = expected.ToArray();
return (VerifyProofKeys(expectedBytes, requestProof, wopiProofPublicKey.Value) ||
VerifyProofKeys(expectedBytes, requestProofOld, wopiProofPublicKey.Value) ||
VerifyProofKeys(expectedBytes, requestProof, wopiProofPublicKey.OldValue));
}
private string GetAbsolouteUrl(HttpContext context)
{
var url = $"{_wopiUrlService.ApiAddress.TrimEnd('/')}{context.Request.Path}{context.Request.QueryString}";
return url.Replace(":44300", "").Replace(":443", "");
}
private bool VerifyProofKeys(byte[] expectedProof, string proofFromRequest, string discoPublicKey)
{
using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider())
{
try
{
rsaProvider.ImportCspBlob(Convert.FromBase64String(discoPublicKey));
return rsaProvider.VerifyData(expectedProof, "SHA256", Convert.FromBase64String(proofFromRequest));
}
catch (FormatException)
{
return false;
}
catch (CryptographicException)
{
return false;
}
}
}
This implementation follows the document spec. For the method _wopiDiscovery.GetWopiProof(), I just get proof-key section from Wopi Discovery.
.
#Rachanee is your solution working? I have the same code but validation is failing.
You can find a WOPI Proof Validator in PHP, in this package: https://github.com/Champs-Libres/wopi-lib/
This package is a helper for integrating WOPI protocol in PHP applications.
It contains a WOPI Proof Validator service that you can use out of the box.
I am trying to fetch some data from server using json in my flutter app. This is the function I am using.
List<String> userFriendList = ["No Friends"];
Future<http.Response> _fetchSampleData() {
return http.get('//link/to/server/fetcher/test_fetcher.php');
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
userLvl = data["lvl"].toString();
userName = data["name"];
userFriendList = List();
userFriendList = data["friendlist"];
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print('Failed to load data from server');
}
}
I get the usrLvl and userName right. But for userFriendList, I get the following error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
Code on the server end (test_fetcher.php) :
<?php
$myObj->name = "JohnDoe";
$myObj->lvl = 24;
$friends = array("KumarVishant", "DadaMuni", "BabuBhatt", "BesuraGayak", "BabluKaneria", "MorrisAbhishek", "GoodLuckBaba", "ViratKohli", "LeanderPaes");
$myObj->friendlist = $friends;
header('Content-Type: application/json');
$myJSON = json_encode($myObj);
echo $myJSON;
?>
This is a cast error: List<dynamic> != List<String>
You can convert / cast your list in several ways.
I advise you to use this library to simplify your json / Dart object conversion
: https://pub.dev/packages/json_serializable
json_serializable will generate the conversion methods (fromJson and toJson) and take care of everything.
It's easier and safer than doing it manually.
Just what the error says. The userFriendList is of type List you have it as List.
List<String> userFriendList = ["No Friends"];
Should be
List<dynamic> userFriendList = [];
Or a different list entirely if this doesn't work for you.
The error explains it. The fetched data from the server api is decoded to type List<dynamic> and you declared userFriendList to be of type List<String>. What you need to do is change the type of userFriendList from
List<String> userFriendList = ["No Friends"];
to:
List<dynamic> userFriendList = [];
I'm trying to retrieve a result from a guzzle json post using simple php.
this is my function in file1.php EDITED this file is in a laravel 5.3 project
public function getPhotos($properties)
{
$codes = [];
foreach($properties as $property)
{
$codes[$property['codigo']] = $property['cod_filial'];
}
$client = new Client();
$response = $client->request('POST', 'http://local.app/file2.php', ['json' => \GuzzleHttp\json_encode($codes)]);
var_dump($response); exit;
}
and this is my file in a local url http://local.app/file2.php edited this file is in a project outside laravel and i have endpoint configured pointing.
<?php
$input = file_get_contents('php://input');;
$input = json_decode($input);
return $input;
Guzzle response is empty and i'm not figuring out what i'm doing wrong.
Can someone help me? Thanks a lot.
1) Try in your first file:
var_dump($response->getBody()->getContents());
// or
var_dump((string)$response->getBody());
2) Read the documentation about json option more carefully, this option accepts simple PHP array, you should not call json_encode manually.
I am fairly new to iOS development and trying make a simple app which will communicate with PHP API. Data request and response will be in XML format only..
this is my php method for login,
function login()
{
$mainframe = JFactory::getApplication();
$xmlcnt = array();
if (!isset($HTTP_RAW_POST_DATA))
{
$HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
if(empty($HTTP_RAW_POST_DATA))
{
$xmlcnt['code'] = "2";
return $xmlcnt;
}
$doc = new DOMDocument();
$doc->loadXML( $HTTP_RAW_POST_DATA);
$login_data = $doc->getElementsByTagName( "data" );
foreach( $login_data as $login )
{
$user_nm = $login->getElementsByTagName( "username" );
$user_nm = $user_nm->item(0)->nodeValue;
$password = $login->getElementsByTagName( "password" );
$password = $password->item(0)->nodeValue;
} ......
and the xmldata look like this "<data><username>testuser</username><password>password</password></data>"
i want to understand how/what should i use in xcode objective-c to send and recieve XML efficiently.
Thank you verymuch
you can check an XML parser for that, here some examples: http://cocoawithlove.com/2011/05/classes-for-fetching-and-parsing-xml-or.html
If you are asking which xml parser to use, Writing your own parser should help a lot in performance. We usually add data compression to keep size of data transfer low. We use simple zip library and also do encryption is needed. Zipping will help a lot if the data size is large
I have values inside an XMLList in Actionscript. Need to send these values to the DB and update it.
My actionscript code is as follows:
public static function saveUserPermList():void {
var ht:HTTPService = new HTTPService();
ht.url = Config.getServerURL();
ht.method = URLRequestMethod.POST;
//ht.resultFormat = "e4x";
ht.contentType = "text/xml";
ht.request["action"] = "saveUserPermListXML";
ht.request["pdata"] = Application.application.userPermListModel.toString();
ht.addEventListener(ResultEvent.RESULT,AdminUserList.saveUserPermListResult);
ht.send();
}
public static function saveUserPermListResult(e:ResultEvent):void {
trace(e);
}
How can I send the XMLList data to PHP? Should I add a toString() to it?
Also what should be the contentType in Flex.
How can I catch this inside PHP, pl let me know, trying to use, this way,
if($user -> isAllowedAccess()) {
header("Content-type:text/xml");
$postedData = $_POST["pdata"];
// $xmldoc = simplexml_load_string($POST['pdata']);
// echo($xmldoc);
}
No luck. Pl let me know.
The method property of HTTPService should probably be "POST", and the contentType for the request itself should probably be "application/x-www-form-urlencoded".
On the PHP side, $_POST["pdata"] would then be a string containing XML markup. You could either save that in a database directly, or first parse it into XML (via SimpleXML or DOMDocument) and do something with the contained data.
PS: I've just found this answer that seems to shed some light on the internal behavior of the HTTPService class.