Page 1 of 1

Ho do I confirm all bytes have been read from stream

Posted: Mon Dec 01, 2008 5:00 am
by Ravisankar
<?php

$handle = fopen("php://input");
$how_much=100;
$str = read_data($handle,$how_much);

Function read_data($handle,$how_much)
{

$string='';
while(1)
{
$string .= fread($handle,$how_much);//Up to 8kb data can be read from inputstream using fread()
$read_len = strlen($string);//it will take some CPU
if($read_len == $how_much)
{
break;
}
else if($read_len < $how_much)
{
$how_much = $how_much-$read_len;
}
}
return $string;
}
?>


In this above code, I have read 100 bytes from stream. after read I need to confirm
that whether I have read all 100 bytes or not. For that one thing can be done, using strlen()
we can confirm the no. of bytes. I thing strlen() is inefficient way for big amount of data.
suppose we are reading 8kb bytes. when we use strlen() function to compare at that time
function's loop would run 1b to 8kb times to find length of string.

In java has function in inputstream ,
public int read(byte[] b,int offset,int len) this function will return no. of bytes which is read.

Will PHP has this kind of function?
Any Idea about confirming read bytes.?
please give me suggestion.
thanks in advance

Re: Ho do I confirm all bytes have been read from stream

Posted: Mon Dec 01, 2008 5:19 am
by requinix
PHP keeps track of the length of a string so strlen() only tells you that value. It doesn't have to compute it every time like in other languages.

Re: Ho do I confirm all bytes have been read from stream

Posted: Mon Dec 01, 2008 5:45 am
by Ravisankar
/****PHP keeps track of the length of a string so strlen() only tells you that value. It doesn't have to compute it every time like in other languages.***/

Thank you for your reply

I did not understand, while reading the stream at that time itself will strlen() started to count
?

Re: Ho do I confirm all bytes have been read from stream

Posted: Mon Dec 01, 2008 5:54 am
by requinix

Code: Select all

$string .= fread($handle,$how_much);
As soon as you put the string into the variable the length was recorded.

Re: Ho do I confirm all bytes have been read from stream

Posted: Mon Dec 01, 2008 7:03 am
by Ravisankar
/***As soon as you put the string into the variable the length was recorded.**/

Oh! my doubt is got over. Thank you friend.