PHP corrupt file upload

I'm trying to let users upload files onto my website, but unfortunately some of them seem to turn corrupt when reading them. I've tried both images and html files, and all the images come through corrupt (the HTML files come through fine).

To upload the files I'm using a standard HTML form and the PHP $_FILES array. I'm then using the following code to read the contents of the file:

$filename = $_FILES['varname']['tmp_name'];

$handle = fopen($filename, "r");`

$contents = fread($handle, filesize($filename));

fclose($handle);

Unfortunately the value of $contents is now slightly different to the file I uploaded (here's a snippet from the top of the file):

Original file:

ˇÿˇ·ExifII*ˇÏDucky<ˇÓAdobed¿ˇ€Ñ

New file:

ˇÿˇ· Exif II* ˇÏ Ducky < ˇÓ Adobe d¿ ˇ€ Ñ

As you can see there's a difference in the spacing. Any ideas what would be causing this? Am I handling the file read incorrectly for binary files? It seems odd that it's fine for any text files I upload..

Thanks!


how do you print $contents ? Are you sure this is a problem with reading the file ?

I guess that maybe this is a problem with PRINTING the file to the output... Try printing it binary way. Something like:

$data = unpack("C*", $contents);    
foreach ($data as $v)
{
   echo $v, ' ';
}

and compare that with binary dump of the original file...


I usually output files like this:

header("Content-Disposition: attachment; filename="$fileName"");    
readfile("$HOME_DIR/uploads/$fileName");
exit();

Anyway, to try to debug your problem, you should first understand which phase is failing. Upload or download? To check, just go to your webserver and download the file via FTP, then open it in a binary editor. If it is already corrupt then you need to investigate your upload phase, otherwise it's the other way around.

链接地址: http://www.djcxy.com/p/45516.html

上一篇: 如何从word文件中提取文本.doc,docx,.xlsx,.pptx php

下一篇: PHP损坏的文件上传