Here is my code:
<?php
$url="http://www.sina.com.cn";
$handle = @fopen($url, "r");
$len=get_headers($url,true);
print_r($len);
echo $len['Content-Length']."\n";
if ($handle) {
while (($buffer = fgets($handle,1024)) !== false) {
echo ftell($handle)."\n";
fseek($handle,200000,SEEK_CUR);
echo ftell($handle)."\n";
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
The result is as below:
Array
(
[0] => HTTP/1.1 200 OK
[Content-Type] => text/html
[Vary] => Accept-Encoding
[X-Powered-By] => shci_v1.03
[Server] => nginx
[Date] => Thu, 24 Dec 2015 04:03:39 GMT
[Last-Modified] => Thu, 24 Dec 2015 04:01:28 GMT
[Expires] => Thu, 24 Dec 2015 04:04:39 GMT
[Cache-Control] => max-age=60
[Age] => 32
[Content-Length] => 518264
[X-Cache] => HIT from xidan33-99.sina.com.cn
[Connection] => close
)
518264
16
200016
200058
400058
400065
518264
The Content-Length maybe not the same as mine--518264,it will be changed dynamically when you execute the code,it does no matter for the discussion. Why the result is not the following?
518264
1024
201024
202048
402048
403072
please explain the action of file pointer on fgets and ftell and fseek function .
ftell() in C In C language, ftell() returns the current file position of the specified stream with respect to the starting of the file. This function is used to get the total size of file after moving the file pointer at the end of the file.
The ftell() function obtains the current value of the file position indicator for the stream pointed to by stream. Behavior for binary streams: ANSI states that the ftell() function returns relative byte offsets from the beginning of the file for binary files.
The ftell function returns the current file position indicator for stream. If an error occurs, the ftell function will return -1L and update errno.
The ftell() function in PHP is an inbuilt function which is used to return the current position in an open file. The file is sent as a parameter to the ftell() function and it returns the current file pointer position on success, or FALSE on failure.
The length parameter of fgets indicates a maximum length. The PHP documentation states:
Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.
In your case, the first line contains <!DOCTYPE html>
, which explains the result of 16 given by ftell
.
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