If I want to change my filename before it goes to the server for its permanent location, not its temporary Location how could I do this.
The code is as followed:
I'm not sure if I understand what you mean. If you just want to rename the file when storing it in the "upload" directory, do so when using move_uploaded_file()
:
$destination = "upload/" . $new_filename;
if (file_exists($destination)) {
echo 'File ', $destination, ' already exists!';
} else {
move_uploaded_file($temp_filename, $destination);
}
You could also let the user define $new_filename
by providing an additional "rename" text field in your HTML form.
EDIT: Code could be something like that:
Form:
PHP:
$upload_dir = realpath('upload') . DIRECTORY_SEPARATOR;
$file_info = $_FILES['file'];
// Check if the user requested to rename the uploaded file
if (!empty($_POST['newname'])) {
$new_filename = $_POST['newname'];
} else {
$new_filename = $file_info['name'];
}
// Make sure that the file name is valid.
if (strpos($new_filename, '/') !== false || strpos($new_filename, '\\') !== false) {
// We *have* to make sure that the user cannot save the file outside
// of $upload_dir, so we don't allow slashes.
// ATTENTION: You should do more serious checks here!
die("Invalid filename");
}
$destination = $upload_dir . $new_filename;
// ... if (file_exists(... move_uploaded_file(...