Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I debug problems with move_uploaded_file?

Tags:

php

upload

I have a form like

<form action="send.php" method="post" enctype="multipart/form-data">
    <div>
        <label for="subject">Subject</label>
        <input type="text" name="subject" />
    </div>
    <div>
        <label for="image">Image</label>
        <input type="file" name="image" />
    </div>
    <input type="submit" value="Send" />
</form>

PHP like

echo '<pre>'; print_r($_FILES); echo '</pre>';
if (move_uploaded_file($_FILES['image']['tmp_name'], 'images/' . $_FILES['image']['name'])) {
    echo 'ok';
} else {
    echo 'error!';
};

I keep getting error the print_r looks like

Array
(
    [image] => Array
        (
            [name] => Untitled-1.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpprWdjN
            [error] => 0
            [size] => 61768
        )

)
like image 904
JM at Work Avatar asked Mar 08 '11 01:03

JM at Work


2 Answers

Activate error reporting, then you should see the error thrown by move_uploaded_file telling you what's wrong.

like image 80
deceze Avatar answered Nov 07 '22 18:11

deceze


Your $_FILES looks file, error=0 means the upload completed successfully. Most likely it's a permissions error. You can try doing something like:

if (!is_writeable('images/' . $_FILES['image']['name'])) {
   die("Cannot write to destination file");
}

However, be aware that you're using a user-provided filename, so if someone uploads "pwn_my_server.php", your script will write it out to the images directory, and then they can simply visit yoursite.com/images/pwn_my_server.php and take control of your site.

In general it is NEVER a good idea to trust anything in the $_FILES array, or use it directly, since the entirety of its contents are under remote user control. The only thing created by the server is the error code and tmp_name. The rest is potentially malicious.

like image 31
Marc B Avatar answered Nov 07 '22 18:11

Marc B