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);
Related
I have a base64 encoded string which my frontend team has provided me with.The string is a video which was encoded using base64. I want to convert that back into a video file using Php.
I am currently just using the following to decode the string but I don't know how to proceed further.
$decoded = base64_decode ($encoded_string);
There seems to be a way to convert images from string using imagecreatefromstring() function, but I could not find a way to convert it into a video.
Thank you
you should know the video file type. you can decode to original format
$fp=file_put_contents('sample.mp4',base64_decode($encoded_string,true));
Video streams tend to be very large so is isn't a good idea to convert them to plain text in the first place. We'd also need to know the exact mechanism (protocol, format...) used to deliver the base64 string. In any case, once there you can do something like this (error checking omitted for brevity):
$chunk_size = 8192; // Bytes (must be multiple of 4)
$input = fopen('php://input', 'rb');
$output = fopen('/tmp/foo.avi', 'wb');
while ($chunk = fread($input, $chunk_size)) {
fwrite($output, base64_decode($chunk));
}
fclose($output);
fclose($input);
Smaller chunks reduce RAM usage and larger chunks improve I/O performance. You'll need to find a balance that works best for you.
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());
In php is there a way to write binary data to the response stream,
like the equivalent of (c# asp)
System.IO.BinaryWriter Binary = new System.IO.BinaryWriter(Response.OutputStream);
Binary.Write((System.Int32)1);//01000000
Binary.Write((System.Int32)1020);//FC030000
Binary.Close();
I would then like to be able read the response in a c# application, like
System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("URI");
System.IO.BinaryReader Binary = new System.IO.BinaryReader(Request.GetResponse().GetResponseStream());
System.Int32 i = Binary.ReadInt32();//1
i = Binary.ReadInt32();//1020
Binary.Close();
In PHP, strings and byte arrays are one and the same. Use pack to create a byte array (string) that you can then write. Once I realized that, life got easier.
$my_byte_array = pack("LL", 0x01000000, 0xFC030000);
$fp = fopen("somefile.txt", "w");
fwrite($fp, $my_byte_array);
// or just echo to stdout
echo $my_byte_array;
Usually, I use chr();
echo chr(255); // Returns one byte, value 0xFF
http://php.net/manual/en/function.chr.php
This is the same answer I posted to this, similar, question.
Assuming that array $binary is a previously constructed array bytes (like monochrome bitmap pixels in my case) that you want written to the disk in this exact order, the below code worked for me on an AMD 1055t running ubuntu server 10.04 LTS.
I iterated over every kind of answer I could find on the Net, checking the output (I used either shed or vi, like in this answer) to confirm the results.
<?php
$fp = fopen($base.".bin", "w");
$binout=Array();
for($idx=0; $idx < $stop; $idx=$idx+2 ){
if( array_key_exists($idx,$binary) )
fwrite($fp,pack( "n", $binary[$idx]<<8 | $binary[$idx+1]));
else {
echo "index $idx not found in array \$binary[], wtf?\n";
}
}
fclose($fp);
echo "Filename $base.bin had ".filesize($base.".bin")." bytes written\n";
?>
You probably want the pack function -- it gives you a decent amount of control over how you want your values structured as well, i.e., 16 bits or 32 bits at a time, little-endian versus big-endian, etc.
I spent almost a day for this , but did not get success.
What i want to do is, i have a binary file "data.dat"
I want to read the file contents and output it in text format in say "data.txt" in php.
I tried unpack function of php, but requires the type to be mentioned as the first argument(May be i am wrong, new to php).
$data = fread($file, 4); // 4 is the byte size of a whole on a 32-bit PC.
$content= unpack("C", $data); //C for unsigned charecter , i for int and so on...
But what if i dont know that at what place , what type of data is stored in the file that i am reading?
This function is restricting me because of the type.
I want something similar to this
$content= unpack("s", $data); //where s can denote to string
Thanks.
PHP does not have a "binary" type. Binary data is stored in strings. If you read binary data from a file, it's already stored as a string. You do not need to convert it into a string.
If the binary data already represents text in some standard encoding, you don't need to do anything as you already have a valid string. If the binary data represents some encoding, you need to know what you need to do with it, we don't know.
Using php I need to read an image to a byte stream which has to be passed to a .NET web service. Can anyone provide me with a php code snippet to read an image to a byte array ? I am using using php 5.
thanks
I don't believe PHP natively supports byte arrays in the same sense that .NET does. However, you could try converting each character to its ASCII representation:
<?
$file = file_get_contents($_FILES['userfile']['tmp_name']);
$byteArr = str_split($file);
foreach ($byteArr as $key=>$val) { $byteArr[$key] = ord($val); }
?>
Source: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_23325692.html