Is string base 64 encoded? - php

How can I find whether a string is a data encoded with base64_encode() function or not?
Is it possible?

Attempt to decode it strictly against the Base64 alphabet. The second parameter allows you to enforce this strict check; by leaving it out, the decoding function simply strips out illegal characters before decoding:
if (base64_decode($str, true) === false)
{
echo 'Not a Base64-encoded string';
}

Try this:
if(base64_encode(base64_decode($img, true)) === $img)
echo 'is a Base64-encoded string' ;

Related

How can I convert this string into a human readable IP address in PHP?

I've got a string representing an IPv4 address:
$ip = '\x7F\0\0\x01';
When I try to pass that to inet_ntop($ip) it's giving me grief:
PHP Warning: inet_ntop(): Invalid in_addr value
If I declare the variable manually using double quotes it works:
$ip = "\x7F\0\0\x01";
inet_ntop($ip); // "127.0.0.1"
However, I am not declaring these variables manually. I'm working with what is given to me in an object.
How can I convert '\x7F\0\0\x01' into a string that inet_ntop() will accept?
In other words, how can I make PHP parse a string literally as if I were manually declaring it with double quotes?
Some interesting facts:
gettype('\x7F\0\0\x01'); // string
gettype("\x7F\0\0\x01"); // string
ord('\x7F\0\0\x01'); // 92
ord("\x7F\0\0\x01"); // 127
implode(unpack('H*', '\x7F\0\0\x01')); // 5c7837465c305c305c783031
implode(unpack('H*', "\x7F\0\0\x01")); // 7f000001
mb_detect_encoding('\x7F\0\0\x01'); // ASCII
mb_detect_encoding("\x7F\0\0\x01"); // UTF-8
"\x7F\0\0\x01" == '\x7F\0\0\x01'; // false
// and for the haters
long2ip('\x7F\0\0\x01'); // PHP Warning: long2ip() expects parameter 1 to be integer, string given
One possibility is to parse the string into its component pieces (starting with \); convert them to the decimal equivalent and use chr to get back the original characters. These can then be joined into a string which is suitable for inet_ntop:
$ip = '\x7F\0\0\x01';
preg_match_all('/\\\x?([\dA-F]+)/', $ip, $parts);
$ip = implode('', array_map(function ($v) { return chr(hexdec($v)); }, $parts[1]));
echo inet_ntop($ip);
Another alternative is to use pack, after stripping out the \x parts and replacing \0 with 00:
$ip = '\x7F\0\0\x01';
$ip = pack('H*', str_replace(array('\x', '\0'), array('', '00'), $ip));
echo inet_ntop($ip);
In both cases the output is:
127.0.0.1
Demo on 3v4l.org
The problem is that you've got the literal ASCII output of a binary string and not the real binary value you expect it to be. I'm not sure how you got the literal ASCII value. There is a way to convert it, but you're not going to like it.
You can use eval() to accomplish what you're trying to do. All arguments for eval() being evil still apply.
$ip = '\x7F\0\0\x01';
eval("\$ip = \"$ip\";");
echo inet_ntop($ip);
This will print out 127.0.0.1.
Since binary doesn’t always result in literal ASCII characters, I worry you’ll see literal characters like � in the strings, and these won’t convert properly to the binary value you expect them to be.
For example, here are the characters printed to screen in Psysh:
>>> hex2bin('7f000001') // This is 127.0.0.1
=> "\x7F\0\0\x01"
>>> hex2bin('ffffffff') // This is 255.255.255.255
=> b"ÿÿÿÿ"
The first value looks familiar, right? That's the string literal that we can convert back into a binary string using eval(), like we did in the example above. But the binary value for ffffffff is a different story. If we try to convert it, it doesn't give us the 255.255.255.255 value we expect.
$ip = 'ÿÿÿÿ';
eval("\$ip = \"$ip\";");
echo inet_ntop($ip);
In this case, inet_ntop() returns false, but we know it should work:
>>> inet_ntop(hex2bin('ffffffff'));
=> "255.255.255.255"
So, I worry that any attempt to convert these values from string literals into binary strings is not going to work in all cases, whether using eval() or any of the other answers provided here.
However, if everything is coming to you in the format \0\0\0\0, where each "segment" is either a zero or a hex value in the format x00, then you should be in good shape, because these are the same:
>>> "\xFF\xFF\xFF\xFF"
=> b"ÿÿÿÿ"
You can make your own function like this
function convertStringToInAddr(string $string) {
$return = null;
$exploded = explode("\\", $string);
foreach($exploded as $hex) {
if( $hex != "" ) {
$return .= chr(hexdec(str_replace("x", "", $hex)));
}
}
return $return;
}

PHP Encoding and Decode

I have a slice of php encoded code but I don't know how it encoded i mean by which why they encoded this code when i use unphp.net successfully it decode the code and get the real code
simple of encoded code define("\x53\x54\117\103\113\x5f\103\x48\105\x43\113", false) my question is how i can encode another code to be like this and it by which why is encoded please anyone have a knowledge about tell me or know any tool to suggest
I would need more information for me to be able to discern what obfuscator was actually used to encode this, but for this specific string, it appears to be a mix of hex- and octal- encoded letters
"\x53\x54\117\103\113\x5f\103\x48\105\x43\113"
\xFF - Hex
\000 - Octal
The sequence above is encoded as follows (where x is hex and 8 is octal): xx888x8x8x8
This sequence may be random or intentional. Assuming it's random, the following function may be used to encode any string in like manner using random_int() for selecting encoding method at random.
<?php
function hex_octal_rand_encode($s) {
$result = '';
foreach (str_split($s) as $c) {
$d = ord($c);
// select encoding method at random (0 = hex, 1 = oct)
$result .= (random_int(0, 1) === 0)
? '\\x' . dechex($d)
: '\\' . decoct($d);
}
return $result;
}
// Test
$input = "STOCK_CHECK";
$encoded = hex_octal_rand_encode($input);
echo sprintf("Encoded: %s\n", $encoded);
$cmd = sprintf('return "%s";', $encoded);
echo sprintf("Decoded: %s\n", eval($cmd));
?>
Sample outputs (notice the encoded value changes):
Encoded: \x53\x54\117\103\x4b\137\x43\x48\x45\x43\x4b
Decoded: STOCK_CHECK
Encoded: \x53\124\x4f\x43\113\x5f\x43\110\x45\x43\x4b
Decoded: STOCK_CHECK
Encoded: \123\124\x4f\x43\113\137\x43\x48\105\x43\113
Decoded: STOCK_CHECK

How to multilevel base64 decoder and show proper php code

How to multilevel base64 decoder and show proper php code....
i.e.....
base64_decode(
base64_decode(
'SkhSb2FYTXRQazh3TUU4d01FOVBUMDh3VDA4Z1BTQm1ZV3h6WlRzZ0NRa2tUekF3VDA4d1R6QXdUMDh3VHlBOUlITjBjblJ2Ykc5M1pYSW9jSEpsWjE5eVpYQnNZV05sS0dKaGMyVTJORjlrWldOdlpHVW9KMGw1T0hWTGFWRnFKeWtzSUNjbkxDQWtYMU5GVWxaRlVsdGlZWE5sTmpSZlpHVmpiMlJsS0NkVk1GWlRWbXRXVTFneFFsTlVNVkpRVVRBNVRTY3BYU2twT3c9PQ=='
)
);
Any buddy have php script to decode multi level base64_decode() and show proper php code.
Note:
Encoded string will be decoded to exact string if the string encoded or decoded equal no. of times.
It means two level encoded string can be decoded 2 level.
<?php
$string="Hello Stack Overflow";
echo $encodedString=base64_encode(base64_encode($string));//Multilevel(2) encode
echo base64_decode(base64_decode($encodedString));//Multilevel(2) decode
I would recommend to create a function similar to this:
function multiBase64Decode($string, int $iteration = 1){
for($i=0;$i<$iteration;$i++){
$string = base64_decode($string);
}
return $string;
}

base64 encoded then decoded failing

Here is the base64 encoded smilies generated form my android phone and saved into MySQL when I try to display it in browser first I need to check if the string is base64 encoded then I decoded and print it, but below code fails to
$mystring = "8J+YgPCfmInwn5iZ8J+YkPCflIfwn5Oi8J+OtfCfjqfwn5C18J+QiPCfpoTwn5CX8J+MjfCfl7vw\nn4+f8J+PofCfj4Himb/wn5uC8J+atA==\n";
if (base64_encode(base64_decode($mystring)) == $mystring) {
echo base64_decode($mystring);
} else {
echo $mystring;
}
but if I directly decode same string and print it works
echo base64_decode($mystring);
// output 😀😉😙😐🔇📢🎵🎧🐵🐈🦄🐗🌍🗻🏟🏡🏁♿🛂🚴
however same code worked for iOS phone generated smiles.
$mystring = "8J+YgvCfkoHwn5iK8J+RqeKAjfCfkanigI3wn5Gn8J+ZiPCfpKPwn5mJ8J+QvPCfkLbwn5CT8J+MmeKaoe+4j/CfjY7wn42U8J+NlfCfpYPimr3vuI8=";
if(base64_encode(base64_decode($mystring)) == $mystring) {
echo base64_decode($mystring);
} else {
echo $mystring;
}
//output 😂💁😊👩‍👩‍👧🙈🤣🙉🐼🐶🐓🌙⚡️🍎🍔🍕🥃⚽️
I don't understand what is the problem with this block:
if(base64_encode(base64_decode($mystring)) == $mystring)
if(base64_encode(base64_decode($mystring)) == $mystring)
You cannot compare the content of two strings in that way.
Use strcmp() function.
Moreover you cannot check in this way if $mystring is base64 encoded.
You will always get true as encoding a string and then decoding the result will always deliver the original string.
Comparing wil only tell you if encoding/decoding works.

How to check json encoded string?

I found that many of you use a function like this...
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
(from Fastest way to check if a string is JSON in PHP?)
Many of json encoded string contain these characters { : , "
If i check the string that contain these characters it may return true.
example:
$var = '{"1":"a2","a2":{"1":"a2.2","2":"a2.2"}}';
var_dump(isJson($var)) // true;
But when i check the string that is just a number, it return true too.
example:
$phone = '021234567';
var_dump(isJson($phone)); // true
I don't think the string '021234567' is json encoded and it should return false.
Let see more example for more clear question.
$var1 = '021234567'; // this is string. not integer. NOT json encoded.
$var2 = '"021234567"'; // this is json encoded.
$var3 = 021234567; // this is integer. NOT json encoded.
$var4 = 'bla bla'; // this is string. NOT json encoded.
$var5 = '{"1":"a2","a2":{"1":"a2.2","2":"a2.2"}}'; // this is json encoded.
var_dump(isJson($var1));
var_dump(isJson($var2));
var_dump(isJson($var3));
var_dump(isJson($var4));
var_dump(isJson($var5));
the results are:
true
true
true
false
true
But the expected results are:
false
true
false
false
true
The question is. How to check the string that is valid json encoded?
More example 2
If 021234567 is an integer. when i use json_encode it returns integer and have nothing to do with it again when use json_decode
$var = 021234567;
echo $var; // 4536695
echo json_encode($var); // 4536695
echo json_decode(4536695); // 4536695
echo json_decode($var); // 4536695
$var = 21234567;
echo $var; // 21234567
echo json_encode($var); // 21234567
echo json_decode(4536695); // 21234567
echo json_decode($var); // 21234567
so, the integer value should return false when i check json encoded string with isJson function. but it is not.
If 021234567 is string. when i use json_encode i should got "021234567" (with double quote). if this string has no double quote, it should not be json encoded.
$var = '021234567';
echo $var; // 021234567
echo json_encode($var); // "021234567"
echo json_decode('"021234567"'); // 021234567
echo json_decode($var); // 21234567
// example if string is text with double quote in it.
$var = 'i"m sam';
echo $var; // i"m sam
echo json_encode($var); // "i\"m sam"
echo json_decode('"i\"m sam"'); // i"m sam
echo json_decode($var); // null
As you see. the simple string with json encoded should contain at least double quote character at open and close of that string.
Please help me how to check that string is valid json encoded.
I think the valid json encoded string should at least have double quote " or curly bracket {} at the open and close of that string.
I don't know how to check that or don't know how to preg_match that.
From PHP Documentation:
PHP implements a superset of JSON - it will also encode and decode scalar types and NULL. The JSON standard only supports these values when they are nested inside an array or an object.
So, the reason leading zeros make this check pass is that json_decode just strips them during parsing without giving any errors. For example:
echo json_decode('0123');
will just display 123.

Categories