Are there any best practices for handling file uploads in PHP to prevent overwriting existing files?
When handling file uploads in PHP, one best practice to prevent overwriting existing files is to generate a unique filename for each uploaded file. This can be done by appending a timestamp or a random string to the original filename before saving it to the server.
// Generate a unique filename for the uploaded file
$timestamp = time();
$randomString = uniqid();
$originalFilename = $_FILES['file']['name'];
$extension = pathinfo($originalFilename, PATHINFO_EXTENSION);
$newFilename = $timestamp . '_' . $randomString . '.' . $extension;
// Move the uploaded file to the desired directory with the unique filename
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $newFilename);
Related Questions
- What potential issue arises when including PHP files before the doctype declaration in a web page?
- What are the best practices for implementing mod_rewrite in PHP for generating links with specific formats?
- What are some best practices for separating queries from output and using objects for JavaScript output?