5

I had 2 cases where null bytes \0 are being appended to my data.

1.Casting object to an array

class myClass {
    private $var;
    function __construct() {}   
}
$myObject = (array) new myClass();
var_dump(array_map("addslashes", array_keys($myObject)));

Outputs:

array(1) { [0]=> string(14) "\0myClass\0var" } 

2.When decrypting encrypted data:

function encrypt_data($data) {
    return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH , SALT , $data , MCRYPT_MODE_ECB));
}

function decrypt_data($data) {
    $data = base64_decode($data);
    return mcrypt_decrypt(MCRYPT_BLOWFISH , SALT , $data , MCRYPT_MODE_ECB);
}

$data = '12345678901234567 aasdasd';
$edata = encrypt_data($data);
var_dump(addslashes(decrypt_data($edata)));

Outputs:

string(39) "12345678901234567 aasdasd\0\0\0\0\0\0\0" 

But I would never notice \0s if not addslashes function. Why just var_dump() does not show those ? var_dump("Hello\0 World"); for example outputs 'Hello World'. In my opinion bad representation of data. And as far as I know \0 byte is end of char array (string in PHP) in C and PHP is implemented in C.

  • 2
    `var_dump("Hello\0 World");` _does_ show the character. It's your browser that doesn't make it clear. Try that code from command line, I get `string(12) "Hello\000 World"` as the output. – jszobody Mar 18 '16 at 14:33
  • 1
    Dont see \0 on MAC `php -a; php > var_dump("Hello\0 World"); string(12) "Hello World"` –  Mar 18 '16 at 14:41
  • I'm on a mac as well.`php -a; php > var_dump("Hello\0 World"); string(12) "Hello\000 World"` Not sure why you're getting different results – jszobody Mar 18 '16 at 14:42

1 Answers1

2

var_dump outputs strings as is. If your string contains a NUL byte, that NUL byte will be output as is. The problem is that a NUL byte typically doesn't show up as anything in the browser, or possibly even the command line.

An indication is that the displayed string length is different from what you see. A string(42) "abc" probably has quite a number of "hidden" characters in it. Obviously this gets harder and harder to eyeball the longer your string gets...

var_export makes NUL bytes and similar much more obvious.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • That makes sense to me. Is there any combination of `var_export()` + `var_dump()` ? –  Mar 18 '16 at 14:54
  • Not that I know of. If you have a hunch that you may be dealing with hidden characters, you'll have to probe in more detail. – deceze Mar 18 '16 at 14:59