1

我有一个允许用户提交文件的 html 页面。
下面是我保存提交文件的网络服务。但我不希望 move_uploaded_files 覆盖现有文件?我应该怎么办?谢谢

$tmpname = $_FILES["image"]["tmp_name"];
$movedname = "submit-img/" . $_POST["category"] . "/" . $_FILES["image"]["name"];
$prevPage = parse_url($_SERVER['HTTP_REFERER']);

move_uploaded_file($tmpname, $movedname);
4

3 回答 3

5

三思而后行:

if (!is_file($movedname)) {
    move_uploaded_file($tmpname, $movedname);
}
于 2012-06-19T09:31:30.043 回答
1

我认为处理这种情况的一种更有效的方法是检查文件是否存在,在这种情况下编辑文件名直到找不到匹配项,然后上传文件。

$x=1;
$newfilename=$movedname;

while(is_file($_SERVER['DOCUMENT_ROOT'].$newfilename)){ //actual control

  $newfilename=$movedname;//to prevent creating flower123.jpg at the third iteration, see below

  $fn=explode(".",$newfilename);
  $fp=count($fn)-2;
  $fn[$fp].=$x;
  //here we get the filename before extension (eg. "flower" in fakepath/flower.jpg) and add $x to get "flower1"

  $newfilename=implode(".",$fn);
  //we rebuild our path having now fakepath/flower1.jpg
  $x++;
}

move_uploaded_file($filevar['tmp_name'], $_SERVER['DOCUMENT_ROOT'].$newfilename);
于 2016-07-21T14:19:54.063 回答
0

您可以检查如下:


if( !is_file($movedname)) {

    move_uploaded_file($tmpname, $movedname);
}

或者假设您想为其他目的上传相同的文件,而不是您可以执行以下操作:


$tmpname = $_FILES["image"]["tmp_name"];  // use timestamp string to prevent overwrite files
$filename = $_FILES["image"]["name"] . '_' . time();

$movedname = "submit-img/" . $_POST["category"] . "/" . $filename;

$prevPage = parse_url($_SERVER['HTTP_REFERER']);

move_uploaded_file($tmpname, $movedname);
于 2016-07-21T14:28:17.960 回答