Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, what is a binary string (b'xxxx')?

Tags:

What does b'' ("binary string") mean in the PHP statement $str=b'xxxxxx';?

like image 787
lovespring Avatar asked Nov 14 '09 11:11

lovespring


2 Answers

The PHP language reference describes the distinction between unicode strings and native binary strings, denoted with b'this is a binary string'

It doesn't seem to be a method of representing binary numbers.

The notation "is available since PHP 5.2.1. However, it will only have effect as of PHP 6.0.0"

like image 84
pavium Avatar answered Oct 19 '22 14:10

pavium


Binary strings were introduced in PHP 5.2.1 but were expected to become effective only starting from PHP 6. It was an attempt to distinguish between Unicode and binary strings. The former being the new string format, the latter being the current format but changed to "b" notation.

As you may know, PHP 6 had been abandoned and string format didn't change. The "b" notation is just a relic from that era.

'foobar' === b'foobar'; // true


So nowadays (PHP 5 and 7), binary string is the only string format. The character encoding (which can be multibyte) is managed at the "upper level", by your text editor, web browser, etc. You can consider a binary string to be a string consisting of the full 0-255 range of byte values.

A string with nonprintable characters and such, can be manipulated in PHP as any other string, but you'll get garbage displaying it. Also some characters have special meaning: \0 marks string termination in C and SQL, there are control characters, etc. So as soon as you use them outside of PHP you are likely to encounter troubles.

For example, random_bytes() produces such strings.

like image 30
Gras Double Avatar answered Oct 19 '22 14:10

Gras Double