user978122
user978122

Reputation: 5771

PHP: Number of bytes in a string, raw HTTP

I am trying to get the number bytes in a PHP string. I seem to be running into a problem trying to send raw HTTP requests (PROPFIND, REPORT), and getting the proper length of the content. From which point, following the headers, do I start counting the content? And at which point, do I stop?

Upvotes: 1

Views: 939

Answers (2)

bardiir
bardiir

Reputation: 14792

You count the complete content, starting after the two linebreaks that delimit the header section:

$contentlength_bytes = strlen(strstr($http, "\r\n\r\n")) - 4;

If you're doing it that way already i guess you might have run into problems with encoding...

When your content has multibyte characters, using strlen() to return it's bytelength might not work correctly as multibyte characters might get interpreted as one byte under certain system configurations (see edit below - and comments for that part).

This will give you the correct bytelength of any content-string you feed it under any system configuration:

$contentlength_bytes = mb_strlen(strstr($http, "\r\n\r\n"), 'latin1') - 4;

Edit:
As Jon pointed out in the comments, this is not always needed as strlen() will return the correct bytecount of a string in most circumstances.

I just added this method of measuring as on multibyte systems and under certain circumstances (for example mbstring.func_overload set to 2) strlen() is not safe to use against binary strings.

The above method is the only known (to me) way to completely binary safe calculate the byte-length of a given string. And i tripped over this a couple of times already..

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324800

If you have your entire request in a variable, say $request, then:

list($headers,$body) = explode("\r\n\r\n",$request,2);

Basically, the two CRLFs mark the end of the headers, and the contents start after that.

Upvotes: 3

Related Questions