Search code examples
phpimagecorruptionrapidshare

Corrupted images when downloading from RapidShare


I offload a lot of my sites uploads to RapidShare for storage. I then have a script that when accessed by a user wanting to download a file, downloads it from RapidShare using their API and serves it to the user. Here's the relevant code in the script that serves the file:

// Stream file to user
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $result->name);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $result->size);

$url = 'https://' . $host . '/cgi-bin/rsapi.cgi?sub=download';
$url .= '&login=login';
$url .= '&password=mypass';
$url .= '&fileid=' . $result->rs_fileid;
$url .= '&filename=' . $result->name;

$handle = fopen($url, 'rb');
if(!$handle) {
    throw new Exception('Failed to open file handle');
}

while(!feof($handle)) {
    echo fread($handle, 1024*1024);
    ob_flush();
    flush();
}

fclose($handle);

This works fine for all the files I've tested except for images. When the images are downloaded, they're corrupt. Windows Photo Viewer can't open the image and neither can programs like Photoshop.

Weird thing is, if I download a .exe and run it, everything works fine. It's not corrupt. It only happens with images as far as I can tell. I've also tested it with .pdf's.

To make it weirder, if I look at the filesize of the original image (2,882 bytes) and then the filesize of the image downloaded through this script, they're the same. The filesizes for both are 2,882 bytes. But the image is still corrupt.

What could be the cause of this and the solution? It's not like I'm adding any binary data to the file as it's downloaded. :/

Thanks.

Edit: Forgot to mention, if I download the file straight from RapidShare without going through the script the image is fine and isn't corrupt. So it must be the script at fault here.


Solution

  • Check my answer for a similar problem, I'm pretty sure there will be some notice at the beginning of your files!