Peter DeMartini
Peter DeMartini

Reputation: 15

Only partial content from a remote file is being read (PHP)

I need some help with this code. I am pretty sure the code is correct but I could be wrong. The problem is that the getSourceCode() isn't pulling the entire contents of the URL. It only returns a third of the data, for example: the $size variable would return 26301 and the returned data size would only be 8900. I have changed php.ini to have max file size of 100M so I don't think that is problem.

private function getSourceCode($url){     
    $fp = fopen($url, "r");
    $size = strlen(file_get_contents($url));;
    $data = fread($fp, $size);
    fclose($fp);
    return $data;
}

Upvotes: 0

Views: 1153

Answers (2)

stoj
stoj

Reputation: 679

Short answer is that byte != 1 character in a string. You can use $data= file_get_contents($url) to get the entire file as a string.

Long answer fread is looking for the number of bytes but strlen is returning the number of characters and a character can be larger than 1 byte so you can end up not getting the entire file. Alternatively you could use filesize() to get the file length in bytes instead of strlen().

Upvotes: 2

cwallenpoole
cwallenpoole

Reputation: 81988

Ok, well, if you're using file_get_contents you shouldn't be using fread too.

private function getSourceCode($url){     
    return file_get_contents($url);
}

Upvotes: 6

Related Questions