Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems downloading remote files using fopen()

Status
Not open for further replies.

raphaelp

Programmer
Jul 24, 2004
3
AT
Hey all,

I've got a big problem. When downloading remote websites using fopen() [sourcecode below] text-files get downloaded correctly however images can't get displayed (they get downloaded, but they're mostly smaller than their original counterparts). The most strange thing, however, is that when testing locally it works (Windows XP Home // Apache), but on the remote server it doesn't (SuSE Linux // Apache).

Here's the code-snippet:

<?php
if (!file_exists($dest)) {
$fp_ori = fopen ($src, "rb");
$fp_new = fopen ($dest, "wb");
if ($fp_ori && $fp_new) {
while (!feof ($fp_ori)) {
fwrite($fp_new,fgets($fp_ori, 1000000));
}
fclose ($fp_ori);
fclose ($fp_new);
}
}
?>

Any help would be greatly appreciated.

Best regards,

Raphael Pirker
 
Since you say that the unusable image files are usually smaller than the originals, it may be that the foreign server is compressing all output. Maybe using mod_deflate.

The easiest way to tell might be to telnet to the server on port 80 and issue:

GET /name_of_the_image.jpg HTTP/1.1[enter]
Host: host.name.of.the.server[enter]
[enter]

Then examine the HTTP headers being sent from the server.




Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Thanks for your reply. After trying a little I found out the problem: Apache seems to include HTTP headers into the file or something, messing up the images. Here's a code snippet that fixes the bug. It now works! :)

<?php
function http_get($url)
{
$url_stuff = parse_url($url);
$port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;

$fp = fsockopen($url_stuff['host'], $port);

$query = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
$query .= 'Host: ' . $url_stuff['host'];
$query .= "\n\n";

fwrite($fp, $query);

while ($tmp = fread($fp, 8192)) {
$buffer .= $tmp;
}

preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
return substr($buffer, - $parts[1]);

}
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top