PHP File Upload

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:

<form action="upload_file.php" method="post"
    enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />

<!-- NEW TEXTBOX -->
<label for="newname">Rename to (optional):</label>
<input type="text" name="newname" id="newname" /> 
<br />

<input type="submit" name="submit" value="Submit" />
</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, "https://stackoverflow.com/") !== 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(...

Leave a Comment