简体   繁体   中英

Trouble moving picture with move_uploaded_file()

I'm trying to set up some image handling for a webpage I'm creating, but I can't get move_uploaded_file() to work properly... I keep getting these errors:

Warning: move_uploaded_file(/htdocs/PHP/Pictures/picture.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /opt/lampp/htdocs/PHP/useredit.php on line 17

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpY0KKxH' to '/htdocs/PHP/Pictures/picture.jpg' in /opt/lampp/htdocs/PHP/useredit.php on line 17

My code looks like this:

if(isset($_FILES['image_file']))
{
    $img_tmp_name = $_FILES['image_file']['name'];
    $img_dir = "/htdocs/PHP/Pictures/";
    $img_name = $img_dir . $img_tmp_name;
    if(move_uploaded_file($_FILES['image_file']['tmp_name'],$img_name))
    {
        list($width,$height,$type,$attr) = getimagesize($img_name);
        switch($type)
        {
            case 1:
                $ext = ".gif";
                break;
            case 2:
                $ext = ".jpg";
                break;
            case 3:
                $ext = ".png";
                break;
            default:
                echo "Image format not accepted";
        }
        $query = "UPDATE profile_pic SET img_path=$img_name WHERE uid='$uid'";
        $img_id = mysql_insert_id();
        $new_img_name = $img_dir . $img_id . $ext;
        rename($img_name, $new_img_name);
    }
}
if(mysql_query($query)or die('Error: ' . mysql_error()))
{
    header("Refresh:0; url='control.php'");
}

The folder PHP/Pictures exist. How do I fix this?

You've got some major security and logistical problems with this code:

a) You don't check if the upload succeeded and proceed as if it has. There's exactly ONE way for an upload to succeed, and far too many reasons for it to fail.

if ($_FILES['image_file']['error'] !== UPLOAD_ERR_OK) {
    die("Upload failed with error code {$_FILES['image_file']['error']}");
}

b) You're using the filename provided by the user in the path to save on your server. A malicious user can embed pathing data in that filename and specify any location on your server they want. eg

$_FILES['image_file']['name'] = '../../../../../../etc/passwd';

$img_dir should contain a path relative to you current file and not from root folder.

if your current directory contains upload_file.php (ur code) and a folder hierarchy like PHP/Pictures/

then $img_dir="/PHP/Pictures/";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM