PHP : Fetch byte array from C# Web API - php

I am trying to fetch byte array from C# Web API. C# client can perfectly fetch byte array but it comes in PHP then it shows random string. This string looks like encoded.
I have tried the same API with POSTMAN also. Postman also provided same encoded string. How can I fetch byte array from C# web API in PHP?
I am using HTTP request with content-type of application/x-www-form-urlencoded. This API suppose to give byte array for the following the text,
Required Byte array of content: This is demo file.
Actual response: VGhpcyBpcyBkZW1vIGZpbGUuCg==

Byte values ​​come from webapi as strings. You need to convert this value to base64 type.
string str = yourbytestring;
byte[] cnvbyte = Convert.FromBase64String(str.ToString());

Related

How to save binary byte array from C# as file in PHP?

In C# (ASP.NET MVC) I have method which opens one file and put all the file content into the byte array like this:
byte[] bytes = File.ReadAllBytes(filename);
On PHP side I have PHP Slim Framework API method which is called from C# and I do a POST JSON object that contains this file byte array -> it has these properties:
myObjectId - int - id of my object
filename - string - file name
fileBytes - array - byte array of this file
You can get the demo of this JSON content here: https://justpaste.it/1d8jq
On PHP side I do json_decode of what I received like this:
$fileObject = json_decode($app->request->getBody());
And I get the same array of bytes in member:
$fileBytes = $fileObject->fileBytes;
The question now is how I can save this byte array into the Word file (it is a Word file). I used this method and it saves but it is some very strange content/strange symbols inside (not the original content)...
$binStr = '';
foreach ($fileBytes as $fileByte)
{
$binStr .= pack('i', $fileByte);
}
$binStr .= "\n";
$fileTemp = '/tmp/'.$filename;
file_put_contents($fileTemp, $binStr);
So, how I can properly save these bytes (this byte array has the same elements/integers in PHP like in C# - looks like it is correctly sent))?
If this matters, C# part is on Windows Server and PHP is on Linux/CentOS server.
Seems like you have a simple array of bytes as integers, so instead of using pack, you could just use chr. With some array_map magic, this could be written as this.
$fileObject = json_decode($app->request->getBody());
$data = implode(array_map('chr', $fileObject->fileBytes));
file_put_contents('/tmp/' . $fileObject->filename, $data);

iOS - PHP Match UTF-8 encoding

I am playing around with signatures for request on the iPhone.
I have a simple PHP script running that will verify incoming JSON data against the signature in the header (all in all it is very similar to two-legged OAuth).
The following Obj-C code generates the signature:
const char *cKey = [kConsumerSecret cStringUsingEncoding:NSUTF8StringEncoding];
const char *cData = [payload cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Payload: %s", cData);
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *hmac = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
NSString *signature = [hmac base64EncodedString];
And the verifying PHP code looks like this:
$originalPayload = '{"name":"Ben’s iPhone"}'; // The message received from iOS
$hash = hash_hmac("sha256", $originalPayload, "Secret Key", TRUE);
$signature = strtr(base64_encode($hash), array('=' => '', '+' => '-', '/' => '_'));
The functions work perfectly fine when using ASCII characters. But when they contain UTF-8 characteres iOS calculates the signature based on:
Ben’s iPhone
While PHP calculates it based on:
Ben\u2019s iPhone
Making the signatures invalid. I have tried multiple approaches and none of them have yielded any results. Does anyone have an idea for how to solve this issue?
Remark: Yes, I could simply use OAuth, but I'm just curious on how to implement it myself.
Update: I have tracked down the problem to a part in the code, that modifies the parsed JSON array in the PHP code. In order to hash, but not include it in the body, I added the temporary index 'time' that contained a UTC timestamp. That modification of the original array made PHP change the character representation (escaping UTF-8 characters). Just appending the timestamp work fine.
Nonetheless the functions should yield the same result, shouldn't they?

Transmitting zip data as part of a webservice response / reversible mb_detect_encoding

I have a PHP webservice which currently returns a zip archive as its only output. I'm reading the zip archive from disk using file_get_contents and sending it back as the body of the response.
I'd like it to return some additional metadata, in a JSON format:
{
"generatedDate": "2012-11-28 12:00:00",
"status": "unchanged",
"rawData": <zip file in raw form>
}
The iOS app which talks to this service will receive this response, parse the JSON, and then store the zip file locally for its own use.
However, if I try to stuff the result of file_get_contents into json_encode, it rightfully complains that the string is not in UTF-8 format. If I UTF-8-encode it using mb_convert_encoding($rawData, 'UTF-8',
mb_detect_encoding($rawData, 'UTF-8, ISO-8859-1', true));, it will encode it happily, but I can't find a way to reverse the operation on the client (calling [dataString dataUsingEncoding:NSUTF8StringEncoding] and then treating the result as a zip file fails with BOM could not extract archive: Couldn't read pkzip local header.
Can anyone suggest a good way to insert a blob of raw data as one field in a JSON response?
Surely if you successfully included the raw data in the JSON then you'd have the opposite problem at the other end, when you try to decode the JSON and whatever you use to decode can't handle the raw data?
Instead, I would suggest that you send the raw data only in the response body, and use headers to send the metadata.
Strike this question.
It turns out that UTF-8 encoding raw data like this is nonstandard at best, and the standard solution is base-64 encoding it and then using a base-64 decoder to recover it on the client:
$this->response(200, array('rawData' => base64_encode($rawData)));
...
NSString *rawDataString = [[response responseJSON] objectForKey:#"rawData"];
NSData *rawData = [Base64 decode:rawDataString];
ZIP archives are not text—they are binary files! Trying to convert your archive from ISO-8859-1 to UTF-8 makes as much sense as trying to rotate it.
There're several algorithms to serialize binary streams as text but they'll all increase the file size. If that's not an issue, have a look at:
base64_encode()
bin2hex()
unpack()

Pack/unpack and BSON encode/decode dat

We have an iOS app that sends data in an encoded format. In PHP the following code will decode it properly.
bson_decode(pack("H*", $hex_string));
In Python, the following code will create a valid encoded object that the PHP code can then decode (data is a dict in this).
from bson import BSON
def encode(data):
return str(BSON.encode(data)).encode('hex')
The following Python code will decode a string that was encoded by the above Python code:
from bson import BSON
def parse(str):
hexed = str.decode('hex')
return BSON.decode(BSON(hexed))
In theory that should decoded data sent from the app as well. But it throws the following exceptions:
bson.errors.InvalidBSON: bad eoo
It looks like the Objective C code that encodes the data in the app adds some extra padding. If I remove the last characters from the app encoded string it works. Is there anything I can do to account for this? Changing the app code is NOT possible. Even if it were there are millions of device running the old code which I need to support so I still need to have a fix for this.
According the BSON specification, BSON documents must be terminated with a NULL byte (\x00). Have you checked if the byte string you are trying to decode is NULL terminated? If not, you may need to append a NULL byte at the end.

convert image to byte array

i want convert image into byte array in php.actually i am accessing web service in dot net.where i want to pass image as byte array.i tried this code
$data1 = file_get_contents("upload/1311677409gen1.jpg");
$byteArr1 = str_split($data1);
foreach ($byteArr1 as $key=>$val)
{
$byteArr1[$key] = ord($val);
}
and send this array name to web service.but i got error parameter is not valid.i googled it.but dont get proper solution.i need it urgent.help.
Thanks in advance.
Without seeing the .net webservice, you probably have two options:
Stream the image
base64 encode the image before transfer, provided the webservice can decode it.

Categories