I am trying to upload a file and then rename the file as something else.
Everything worked fine unless the renamed filename already existed. So I added
some extra code to check if the filename already existed and if so to delete it
before renaming the uploaded file. Everything now works fine in the following
code:
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($_FILE S['userfile']['name']);
echo '<pre>';
if (move_uploaded_ file($_FILES['userfile']['tmp_name'], $uploadfile)) {
$imagefilename = $_POST['imagefilename'];
$renamedfile = $uploaddir . $imagefilename;
if (file_exists($r enamedfile)) {
unlink($renamed file);
}
rename($uploadf ile , $renamedfile);
}
else {
echo "There was an error in your file upload. \n";
echo 'Here is some more debugging info:';
print_r($_FILES );
}
That seems like a lot of code to do something relatively simple. So my question
is, is there a simpler way like forcing the rename function to overwrite an
existing file with the same filename if it exists.
Regards
Dynamo
Everything worked fine unless the renamed filename already existed. So I added
some extra code to check if the filename already existed and if so to delete it
before renaming the uploaded file. Everything now works fine in the following
code:
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($_FILE S['userfile']['name']);
echo '<pre>';
if (move_uploaded_ file($_FILES['userfile']['tmp_name'], $uploadfile)) {
$imagefilename = $_POST['imagefilename'];
$renamedfile = $uploaddir . $imagefilename;
if (file_exists($r enamedfile)) {
unlink($renamed file);
}
rename($uploadf ile , $renamedfile);
}
else {
echo "There was an error in your file upload. \n";
echo 'Here is some more debugging info:';
print_r($_FILES );
}
That seems like a lot of code to do something relatively simple. So my question
is, is there a simpler way like forcing the rename function to overwrite an
existing file with the same filename if it exists.
Regards
Dynamo
Comment