【问题标题】:How do I save user uploaded files (images) to a specific file instead of the root directory with php?如何使用 php 将用户上传的文件(图像)保存到特定文件而不是根目录?
【发布时间】:2014-05-10 21:40:00
【问题描述】:

好的,在我的网站中,用户可以上传图片作为他们的个人资料照片,我将它们保存为 $username.jpg,因此所有图片文件名都是唯一的。问题是它们都保存在我的根目录中,使那里的一切变得一团糟。那么我需要什么样的脚本来自动将所有照片保存在一个名为“profileimages”的文件夹中?

这几乎是我目前拥有的代码。

Select an image: <br/> <input type="file" name="profilepicture" size="10" />;

if ($_FILES) {
    if($_FILES['profilepicture']['name']){
        $name = $_FILES['profilepicture']['name'];

        switch($_FILES['profilepicture']['type']){
            case 'image/jpeg': $ext = 'jpg'; break;
            default: $ext = ''; break;
        }

        if ($ext == ''){
            echo '<script> alert("Your uploaded file is of the wrong file type, only jpeg image file types are accepted"); </script>';
        }

        if ($ext){
            $profimg = "$user.$ext";
            move_uploaded_file($_FILES['profilepicture']['tmp_name'], $profimg);
        }
    }
}

【问题讨论】:

    标签: php html image jpeg root


    【解决方案1】:

    你可以简单的换线

    move_uploaded_file($_FILES['profilepicture']['tmp_name'], $profimg);
    

    进入

    move_uploaded_file($_FILES['profilepicture']['tmp_name'], 'profileimages/'.$profimg);
    

    当然目录 profileimages 必须存在并且有足够的权限来移动文件

    【讨论】:

      【解决方案2】:

      只需编辑 move_uploaded_file 的第二个参数,如下所示:

      move_uploaded_file($_FILES['profilepicture']['tmp_name'], "profileimg/".$profimg);
      

      第二个参数是目的地。

      要确保目录(可能包含子目录)存在,您可以将其用作 mkdir:

      mkdir("/dir1/dir2", 0, true);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 2018-07-30
        • 1970-01-01
        • 2019-02-02
        相关资源
        最近更新 更多