If I have the following variable in PHP:
$Message='Hello, this is just test message';
How can I get the size of its content in bytes? For instance, to print something like:
<p>Message size is 20KB</p>
The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>
memory_get_usage() — Returns the amount of memory allocated to PHP.
php.net: The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18.
strlen
returns the number of bytes in the string, not the character length. View the PHP Manual here.
Look closely at:
Note:
strlen() returns the number of bytes rather than the number of characters in a string.
If you take the result and multiple by 8, you can get bits.
Here is a function which can easily do the math for you.
function strbits($string){ return (strlen($string)*8); }
Note, if you use, memory_get_usage()
, you will have the wrong value returned. Memory get usage is the amount of memory allocated by the PHP script. This means, within its parser, it is allocating memory for the string and the value of the string. As a result, the value of this before and after setting a var, would be higher than expected.
Example, the string: Hello, this is just test message
, produces the following values:
Memory (non-real): 344 bytes Strlen: 32 Bytes Strlen * 8bits: 256 bits
Here is the code:
<?php $mem1 = memory_get_usage(); $a = 'Hello, this is just test message'; echo "Memory (non-real): ". (memory_get_usage() - $mem1)."\n"; echo "Strlen: ". strlen($a)."\n"; echo "Strlen * 8bits: ". (strlen($a) * 8)."\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With