Reputation: 833
I have a html page that allows users to submit a file.
Below is my web service for saving submitted files. But I dont want move_uploaded_files to overwrite existing files? What should I do? Thank you
$tmpname = $_FILES["image"]["tmp_name"];
$movedname = "submit-img/" . $_POST["category"] . "/" . $_FILES["image"]["name"];
$prevPage = parse_url($_SERVER['HTTP_REFERER']);
move_uploaded_file($tmpname, $movedname);
Upvotes: 1
Views: 4450
Reputation: 11
You can check as follows :
if( !is_file($movedname)) {
move_uploaded_file($tmpname, $movedname);
}
Or suppose if you want to upload the same file for other purposes as well than you can do as follows :
$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);
Upvotes: 0
Reputation: 4262
I think a more efficient way to handle this situation is checking if file exists, and in this case edit the filename until a match isn't found, then upload the file.
$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);
Upvotes: 1
Reputation: 437336
Look before you leap:
if (!is_file($movedname)) {
move_uploaded_file($tmpname, $movedname);
}
Upvotes: 5