How to convert byte array to image in php? - php

I want to convert the byte array from a webservice to image. The webservice response array looks like the following but I could not figure out how to render this array back to an image. Please help me
'MemberImage' =>
array (size=151745)
0 => int 255
1 => int 216
2 => int 255
3 => int 224
4 => int 0
5 => int 16
6 => int 74
7 => int 70
8 => int 73
9 => int 70
10 => int 0
11 => int 1
12 => int 1
13 => int 1
14 => int 0
15 => int 72
16 => int 0
17 => int 72
18 => int 0
19 => int 0
20 => int 255 ...

Use pack to convert data into binary string, es:
$data = implode('', array_map(function($e) {
return pack("C*", $e);
}, $MemberImage));
// header here
// ...
// body
echo $data;

If you want to convert that array to an actual byte array (i.e. a binary string in PHP) you could use the following function...
function arrayToBinaryString(Array $arr) {
$str = "";
foreach($arr as $elm) {
$str .= chr((int) $elm);
}
return $str;
}
You could also use pack instead of the above function to do the same thing like so...
call_user_func_array('pack', array_merge(['C*'], $arr));
or in PHP 5.6+
pack('C*', ...$arr);
With that you could then - in theory - use the binary string as an image. So, for example, assuming you want to output the raw image data, and that the image is say a PNG, you would do something like the following, in conjunction with the above code...
header('Content-type: image/png');
echo arrayToBinaryString($myArray);
Just be sure to edit the Content-type header with whatever type the actual image is. If you don't know you could use something like getimagesize on the binary string to extract the MIME type from the image data.
$tmpFile = tempnam("/tmp");
$image = arrayToBinaryString($myArray);
file_put_conetnts($tmpFile, $image);
$imageData = getimagesize($tmpFile);
header("Content-type: {$imageData['mime']}");
echo $image;
unlink($tmpFile);

Related

Decode a CS:GO match sharing code with PHP

I am trying to build a function which decodes a CS:GO match sharing code. I have seen enough examples but everyhting is in JS or C# but nothing in PHP.
I took the akiver demo manager as an example and i tried to replicate it in PHP. I am going bit blind because i have no idea what is the output on a certain points so i can only hope that the result will be what i expect it to be. I think i am on the right path, the problem comes when the bytes have to be created/interpeted/converted to the desire outcome.
The code that should be decoded is the following: 'CSGO-oPRbA-uTQuR-UFkiC-hYWMB-syBcO' ($getNextGame variable)
The result should be 3418217537907720662
My code so far:
/**
* #param $getNextGame
* #return array
*/
public function decodeDemoCode(string $getNextGame): array
{
$shareCodePattern = "/CSGO(-?[\w]{5}){5}$/";
if (preg_match($shareCodePattern, $getNextGame) === 1) {
$result = [];
$bigNumber = 0;
$matchIdBytes = $outcomeIdBytes = $tvPortIdBytes = [];
$dictionary = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijkmnopqrstuvwxyz23456789";
$dictionaryLength = strlen($dictionary);
$changedNextGame = str_replace(array("CSGO", "-"), "", $getNextGame);
$chars = array_reverse(str_split($changedNextGame));
foreach ($chars as $char) {
$bigNumber = ($bigNumber * $dictionaryLength) + strpos($dictionary, $char);
}
}
}
This brings me back something like that:
1.86423701402E+43 (double)
Then i have the following:
$packed = unpack("C*", $bigNumber);
$reversedPacked = array_reverse($packed);
and this brings the following back:
array(17 items)
0 => 51 (integer)
1 => 52 (integer)
2 => 43 (integer)
3 => 69 (integer)
4 => 50 (integer)
5 => 48 (integer)
6 => 52 (integer)
7 => 49 (integer)
8 => 48 (integer)
9 => 55 (integer)
10 => 51 (integer)
11 => 50 (integer)
12 => 52 (integer)
13 => 54 (integer)
14 => 56 (integer)
15 => 46 (integer)
16 => 49 (integer)
Now here i am not really sure what to do because i do not completely understand C# and i have never worked with bytes in PHP before.
Generally the return type should be an array and would look something like that:
$result = [
matchId => 3418217537907720662,
reservationId => 3418217537907720662,
tvPort => 55788
];
Thanks in advance. Any help is deeply appreciated
I have created a PHP class which makes that possible:
CS:GO ShareCode Decoder PHP
The first problem you have to solve is the returned double value. PHP has limitation when it comes to big integers. More to that here What is the maximum value for an integer in PHP.
Because of this limitation you are losing precision leading to inaccurate results. In order to solve this problem you will have to use one of these libraries GMB, BC Math. What these libraries do, is to give you back the result as a string which solves the double value you got.
So your code has to look something like that:
foreach ($chars as $char) {
$bigNumber = gmp_add(
gmp_mul($bigNumber,$dictionaryLength),
strpos($dictionary,$char)
);
}
json_encode($bigNumber);
$result = json_decode($bigNumber, true, 512, JSON_BIGINT_AS_STRING);
This will give you back the following "18642370140230194654275126136176397505221000"
You do not really need the PHP pack and unpack functions since the results can be generated without them. The next step is to convert your number to hexadecimal. You can do that with the following:
$toHex = gmp_strval(gmp_init($number, 10), 16);
Again you need to use the gmp library in order to get the desired value. What you do, is to make sure that the result is a string and then you convert your number's base from 10 to 16 which is the equivalent of hexadecimal. The results is the following:
"d6010080bdf26f2fbf0100007cf76f2f5188"
The next step is to convert the hex value to an array of byte integers. It looks like this:
$bytes = [];
$byteArray= str_split($toHex, 2);
foreach ($byteArray as $byte) {
$bytes[] = (int)base_convert($byte, 16, 10);
}
What you do here is to split the array to every two chars. The $byteArray variable looks like this (before it enters the foreach loop)
array(18 items)
0 => 'd6' (2 chars) 1 => '01' (2 chars) 2 => '00' (2 chars) 3 => '80' (2 chars)
4 => 'bd' (2 chars) 5 => 'f2' (2 chars) 6 => '6f' (2 chars) 7 => '2f' (2 chars)
8 => 'bf' (2 chars) 9 => '01' (2 chars) 10 => '00' (2 chars) 11 => '00' (2 chars)
12 => '7c' (2 chars) 13 => 'f7' (2 chars) 14 => '6f' (2 chars) 15 => '2f' (2 chars)
16 => '51' (2 chars) 17 => '88' (2 chars)
Now you will have to convert each entry into integer. Since the results are not that big anymore you can change the base of your values with the base_convert function. The base is 16 (hex) and you will have to change it back to 10. The results $bytes after the foreach loop looks like this:
array(18 items)
0 => 214 (integer) 1 => 1 (integer) 2 => 0 (integer) 3 => 128 (integer)
4 => 189 (integer) 5 => 242 (integer) 6 => 111 (integer) 7 => 47 (integer)
8 => 191 (integer) 9 => 1 (integer) 10 => 0 (integer) 11 => 0 (integer)
12 => 124 (integer) 13 => 247 (integer) 14 => 111 (integer) 15 => 47 (integer)
16 => 81 (integer) 17 => 136 (integer)
Now you have to define which bytes are responsible for each result.
$matchIdBytes = array_reverse(array_slice($bytes, 0, 8));
$reservationIdBytes = array_reverse(array_slice($bytes, 8, 8));
$portBytes = array_reverse(array_slice($bytes, 16, 2));
For the match id you will have to get the first 8 entries and the reverse the array
For the reservation id you will have to get the next 8 entries starting from the 8th entry and reverse the array
For the port you will have to get the last 2 entries and reverse the array
Now you will have to return the value
return [
'matchId' => $this->getResultFromBytes($matchIdBytes),
'reservationId' => $this->getResultFromBytes($reservationIdBytes),
'tvPort' => $this->getResultFromBytes($portBytes)
];
The getResultFromBytes() function:
**
* #param array $bytes
* #return string
*/
public function getResultFromBytes(array $bytes): string
{
$chars = array_map("chr", $bytes);
$bin = implode($chars);
$hex = bin2hex($bin);
return gmp_strval($this->gmp_hexDec($hex));
}
/**
* #param $n
* #return string
*/
public function gmp_hexDec($n): string
{
$gmp = gmp_init(0);
$multi = gmp_init(1);
for ($i=strlen($n)-1;$i>=0;$i--,$multi=gmp_mul($multi, 16)) {
$gmp = gmp_add($gmp, gmp_mul($multi, hexdec($n[$i])));
}
return $gmp;
}
Best regards

PHP - Convert string to unicode

I'm working on it
$source = mb_convert_encoding('test', "unicode", "utf-8");
$source = unpack('C*', $source);
var_dump($source);
return:
array (size=8)
1 => int 0
2 => int 116
3 => int 0
4 => int 101
5 => int 0
6 => int 115
7 => int 0
8 => int 116
but i want this return:
array (size=8)
1 => int 116
2 => int 0
3 => int 101
4 => int 0
5 => int 115
6 => int 0
7 => int 116
8 => int 0
I want use this return in openssl function for encryption. just $source important to me, i write other code for debugging.
What can i do to solve this problem?
"Unicode" is not a real encoding; it's the name of the overarching standard and used as an alias for UTF-16BE mostly by Microsoft, and apparently PHP supports it for that reason. What you expect is UTF-16LE, so use that explicitly:
$source = mb_convert_encoding('test', 'UTF-16LE', 'UTF-8');

Using unpack() to convert to a byte array in PHP

I'm trying to convert a binary string to a byte array of a specific format.
Sample binary data:
ê≤ÚEZêK
The hex version of the binary string looks like this:
00151b000000000190b2f20304455a000003900000004b0000
The Python script uses struct package and unpacks the above string (in binary) using this code:
data = unpack(">hBiiiiih",binarydata)
The desired byte array looks like this. This is also the output of the data array is:
(21, 27, 0, 26260210, 50611546, 912, 75, 0)
How can I unpack the same binary string using PHP's unpack() function and get the same output? That is, what's the >hBiiiiih equivalent in PHP?
So far my PHP code
$hex = "00151b000000000190b2f20304455a000003900000004b0000";
$bin = pack("H*",$hex);
print_r(unpack("x/c*"));
Which gives:
Array ( [*1] => 21 [*2] => 27 [*3] => 0 [*4] => 0 [*5] => 0 [*6] => 0 [*7] => 1 [*8] => -112 [*9] => -78 [*10] => -14 [*11] => 3 [*12] => 4 [*13] => 69 [*14] => 90 [*15] => 0 [*16] => 0 [*17] => 3 [*18] => -112 [*19] => 0 [*20] => 0 [*21] => 0 [*22] => 75 [*23] => 0 [*24] => 0 )
Would also appreciate links to a PHP tutorial on working with pack/unpack.
This produces the same result as does Python, but it treats signed values as unsigned because unpack() does not have format codes for signed values with endianness. Also note that the integers are converted using long, but this is OK because both have the same size.
$hex = "00151b000000000190b2f20304455a000003900000004b0000";
$bin = pack("H*", $hex);
$x = unpack("nbe_unsigned_1/Cunsigned_char/N5be_unsigned_long/nbe_unsigned_2", $bin);
print_r($x);
Array
(
[be_unsigned_1] => 21
[unsigned_char] => 27
[be_unsigned_long1] => 0
[be_unsigned_long2] => 26260210
[be_unsigned_long3] => 50611546
[be_unsigned_long4] => 912
[be_unsigned_long5] => 75
[be_unsigned_2] => 0
)
Because this data is treated as unsigned, you will need to detect whether the original data was negative, which can be done for 2 byte shorts with something similar to this:
if $x["be_unsigned_1"] >= pow(2, 15)
$x["be_unsigned_1"] = $x["be_unsigned_1"] - pow(2, 16);
and for longs using
if $x["be_unsigned_long2"] >= pow(2, 31)
$x["be_unsigned_long2"] = $x["be_unsigned_long2"] - pow(2, 32);

Removing items from an array php

I'm new to php so please take it easy.
I have created an array of integers. 1-100. What I want to do is shuffle the array and remove random numbers from it leaving only lets say 15 numbers.
This is what I have done so far, can't figure out how to remove the random numbers. I know I could possibly use unset function but I'm unsure how could I use it in my situation.
// Create an Array using range() function
$element = range(1, 100);
// Shuffling $element array randomly
shuffle($element);
// Set amount of number to get rid of from array
$numbersOut = 85;
// Remove unnecessary items from the array
var_dump($element);
Just try with:
$element = range(1, 100);
shuffle($element);
$output = array_slice($element, 0, 15);
var_dump($output);
Output:
array (size=15)
0 => int 78
1 => int 40
2 => int 10
3 => int 94
4 => int 82
5 => int 16
6 => int 15
7 => int 57
8 => int 79
9 => int 83
10 => int 32
11 => int 13
12 => int 96
13 => int 48
14 => int 62
Or if you want to use $numbersOut variable:
$numbersOut = 85;
$output = array_slice($element, $numbersOut);
It will slice an array from 85 to the end. Remember - if you will have 90 elements in the array, this method will return just 5 elements.

Unpack Cassandra Map Type

I have created some data using Cassandra DB 2.0.1 (CQL 3)
CREATE TABLE fans (id text PRIMARY KEY, fans map<text, text>);
INSERT INTO fans (id, fans) VALUES ('John', {'fruit' : 'apple', 'band' : 'Beatles'});
UPDATE fans SET fans = fans + {'movie' : 'Cassablanca'} WHERE id = 'John';
It work's fine.
cqlsh:testdb> SELECT * FROM fans;
id | fans
------+---------------------------------------------------------------
John | {'band': 'Beatles', 'fruit': 'apple', 'movie': 'Cassablanca'}
(1 rows)
Now I'm trying to get data with PHP (thobbs/phpcassa v1.1.0).
include_once ("/include/autoload.php");
$pool = new phpcassa\Connection\ConnectionPool('testdb');
$connection = $pool->get();
$rows = $connection->client->execute_cql3_query("SELECT id, fans FROM fans", cassandra\Compression::NONE, cassandra\ConsistencyLevel::ONE);
var_dump($rows->rows);
$pool->return_connection($connection);
unset($connection);
$pool->close();
It also work's fine.
array (size=1)
0 =>
object(cassandra\CqlRow)[10]
public 'key' => string '' (length=0)
public 'columns' =>
array (size=2)
0 =>
object(cassandra\Column)[11]
public 'name' => string 'id' (length=2)
public 'value' => string 'John' (length=4)
public 'timestamp' => null
public 'ttl' => null
1 =>
object(cassandra\Column)[12]
public 'name' => string 'fans' (length=4)
public 'value' => string '��band�Beatles�fruit�apple�movie�Cassablanca' (length=51)
public 'timestamp' => null
public 'ttl' => null
The problem is how to unpack the value that represented as a map?
I can see
��band�Beatles�fruit�apple�movie�Cassablanca
and I know it showld be
{'band': 'Beatles', 'fruit': 'apple', 'movie': 'Cassablanca'}
Is there any internal function to deserialize or unpack that encoded string into a map or array?
I wroute a function that reads non-printable symbols:
function unistr_to_ords($str, $encoding = 'UTF-8') {
$str = mb_convert_encoding($str, 'UCS-4BE', $encoding);
$ords = array();
for ($i = 0; $i < mb_strlen($str, 'UCS-4BE'); $i++) {
$s2 = mb_substr($str, $i, 1, 'UCS-4BE');
$val = unpack('N', $s2);
$ords[] = $val[1];
}
return($ords);
}
And when I try it with that value I see the following result:
array (size=51)
0 => int 0
1 => int 3
2 => int 0
3 => int 4
4 => int 98
5 => int 97
6 => int 110
7 => int 100
8 => int 0
9 => int 7
10 => int 66
11 => int 101
12 => int 97
13 => int 116
14 => int 108
15 => int 101
16 => int 115
17 => int 0
18 => int 5
19 => int 102
20 => int 114
21 => int 117
22 => int 105
23 => int 116
24 => int 0
25 => int 5
26 => int 97
27 => int 112
28 => int 112
29 => int 108
30 => int 101
31 => int 0
32 => int 5
33 => int 109
34 => int 111
35 => int 118
36 => int 105
37 => int 101
38 => int 0
39 => int 11
40 => int 67
41 => int 97
42 => int 115
43 => int 115
44 => int 97
45 => int 98
46 => int 108
47 => int 97
48 => int 110
49 => int 99
50 => int 97
As I understood 0 (zero) is a splitter, after 0 is a length, e.g. first 03 means 3 items in the map. Then 04 means 4 is a length of word 'band', then 07 means new word with length 7 for word 'Beatles' on so on.
But is any internal built-in method or function to extract map, list or set?
Somebody may have hacked something together, but for now the official answer is that phpcassa doesn't support CQL3 and hence doesn't support CQL3-only features like column collections (maps, sets, and lists).
I was hoping to just find something to do this, but couldn't so I hacked this up. Works for a map of <text,text>. Which is what I'm using. Thought I'd put it on here for anyone else looking.
function cql3_map_to_array($map) {
$byte_array = unpack('C*', $map);
$map_array = array();
if(sizeof($byte_array) > 2) {
$pos = 1;
$size = (intval($byte_array[$pos]) * 256) + intval($byte_array[$pos + 1]);
$pos += 2;
while($size > 0) {
$length = (intval($byte_array[$pos]) * 256) + intval($byte_array[$pos + 1]);
$pos += 2;
$key = substr($map, $pos - 1, $length);
$pos += $length;
$length = (intval($byte_array[$pos]) * 256) + intval($byte_array[$pos + 1]);
$pos += 2;
$value = substr($map, $pos - 1, $length);
$pos += $length;
$map_array[$key] = $value;
$size--;
}
}
return $map_array;
}

Categories