【问题标题】:How to upload a file to a folder outside web root如何将文件上传到 Web 根目录以外的文件夹
【发布时间】:2023-12-29 16:01:01
【问题描述】:

我在这里寻找类似的问题,但找不到任何解决我问题的方法。 我想将文件上传到 Web 根目录上方的文件夹(www 文件夹)。我在 Windows 上运行 wamp。请问我该如何实现?谢谢。

【问题讨论】:

标签: php file-upload wamp


【解决方案1】:

默认情况下,为了安全起见,文件将上传到 Web 根目录的上方,您必须将它们移动到您想要的任何位置。看看move_uploaded_file()

查看print_r($_FILES),它会显示您上传的每个文件的位置。

【讨论】:

  • 我不想重新配置我的 apache 服务器,因为我在托管服务器上没有该权限,我使用 move_uploaded_file() 将文件移动到我的 Web 根目录,但现在我想要它们移动到 Web 根目录上方的名称目录。
  • 你可以将它移动到你需要的任何文件夹,只需更改 move_uploaded_file() 中的第二个参数
  • 是的,我知道我可以,我试过这个 $upload_folder = "../../matrials/";因为上传脚本位于文档根目录(mywebsitefolder/user/the-upload-script.php)内的文件夹内的文件中。文件夹“材料”就在我的网络根目录上方,即材料/www/我不知道还能尝试什么。感谢您的宝贵时间
  • 给它一个完整的路径,例如:$_SERVER['DOCUMENT_ROOT'].'/www/' - 你应该使用相对路径
  • 只是为了澄清一些事情,我最后的评论应该说“不应该”;)
【解决方案2】:

这类似于我用于通过表单上传的图像。这是假设输入字段的名称为“图像”。

function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return strtolower($ext);
}    

// Get the extension of the uploaded file
$ext = getExtension($_FILES['image']['name']);

// Give the file a new name (if you need) and append the extension.
$img_name = time().$ext;

// Set destination for upload
$new_image = "./images/uploaded/" . $img_name;

// Copy the file to the new location
$copied = copy($_FILES['image']['tmp_name'], $new_image);

您可以将其用于上传的任何文件,如上一个答案所述,在您对上传的文件进行任何操作之前,执行var_dump($_FILES) 将向您展示您需要了解的有关上传文件的所有信息。

【讨论】: