Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm working on a php image upload script and I've run into a weird problem. The files are being successfully uploaded but they're only around 10bytes. Preview gives me the error:

The file 'filename' could not be opened. It may be damaged or use a file format that Preview doesn’t recognize.

Image upload script:

$FileType = $_FILES['picture_file']['type'];
$FileSize = $_FILES['picture_file']['size'];
$FileName = $_FILES['picture_file']['name'];
$Dir = "uploads/";

if($_FILES){
    if (($FileType == "image/gif") 
    || ($FileType == "image/jpg") 
    || ($FileType == "image/jpeg") 
    || ($FileType == "image/png") 
    && ($FileSize < 2097152)) {
        if(move_uploaded_file($_FILES['picture_file']['tmp_name'], $Dir . $FileName === FALSE)){
            echo "<div class='alert alert-danger'> Could not move uploaded file to \"uploads" . htmlentities($FileName) . "\"</div>\n";
        } else {
            mkdir($Dir, 0777);
            file_put_contents($Dir . $FileName, $FileName);
            echo "<div class='alert alert-success'>Successfully uploaded \"uploads/" .htmlentities($FileName) . "\"</div>\n";
        }
    } else {
        echo "<div class='alert alert-danger'>File must be a JPG, JPEG, GIF or PNG and weigh <2MB. <strong><a class='alert-link' href='/nnash_ex2/'>Start over?</a></strong></div>";                            
    }                               
} 

I really haven't got a clue as to why partial files are being uploaded so a point in the right direction would be greatly appreciated.

share|improve this question
Is this locally? – jakenoble Jul 30 at 8:12
Yes I'm using mamp and the address is localhost:8888. – nnash Jul 30 at 8:13
And be careful verify the mime type, else someone can execute php code on your server – Freelancer Jul 30 at 8:15
Yes good advice Olivier, this is mostly placeholder validation code. – nnash Jul 30 at 8:25
add comment (requires an account with 50 reputation)

1 Answer

up vote 3 down vote accepted

file_put_contents($file,$str) will overwrite $file with contents $str. The line:

        file_put_contents($Dir . $FileName, $FileName);

Is clearing the file and adding $FileName as it's contents. If you open the file in a text editor you can confirm this.

share|improve this answer
I ended up using move_uploaded_file(); instead of file_put_contents(); cheers. – nnash 2 days ago
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.