使用move_uploaded_file()解决移动图片问题

时间:2012-08-15 18:36:51

标签: php

我正在尝试为我正在创建的网页设置一些图像处理,但我无法让move_uploaded_file()正常工作......我不断收到这些错误:

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

我的代码如下所示:

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'");
}

存在PHP / Pictures文件夹。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

此代码存在一些重大的安全和后勤问题:

a)您不检查上传是否成功并继续进行,就像它有。只有一种方法可以让上传成功,而且失败的理由太多了。

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

b)您正在使用路径中用户提供的文件名保存在您的服务器上。恶意用户可以在该文件名中嵌入路径数据,并在您的服务器上指定他们想要的任何位置。例如

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

答案 1 :(得分:0)

$ img_dir应包含相对于当前文件的路径,而不是来自根文件夹。

如果您当前的目录包含upload_file.php(ur代码)和文件夹层次结构,如PHP / Pictures /

然后$img_dir="/PHP/Pictures/";