sholkyman
sholkyman

Reputation: 107

What the correct way to get size of binary data in php?

I've read a part of file and now want to make sure the part is the right size. How can I do it in php?

$part = fread($file, 1024);
return some_function($part) == 1024;

I've read the examples, but a I doubt to use strlen in cause of Null-terminated string, that might be inside the binary data in $part. In this way strlen returns size from start of part and until first null-byte is presented in data.

Upvotes: 3

Views: 7064

Answers (2)

ino
ino

Reputation: 2581

According to PHP documentation of fread() function you may use the construction using filesize() as shown in the first example:

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Update: to find a size of the file can be used function stat() without opening or fstat() on opened file.

Upvotes: 0

inquam
inquam

Reputation: 12932

As stated in the PHP manual, strlen returns the number of bytes in the string, not the character length.

In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.

So strlen can be used for binary data, no matter if the data is from a file or some other source.

Upvotes: 16

Related Questions