PHP File Upload and Overwrite File with Same Name
When handling file uploads in PHP, the default behavior of move_uploaded_file() is straightforward: it moves the temporary upload file to the destination path. If a file with that specific name already exists at the target location, the move operation fails because the destination directory does not permit overwriting existing files by default. This results in the upload being ignored or triggering an error, which explains why your second upload of text.php appears to do nothing while a completely new filename works perfectly.
To enable overwriting, you must explicitly check for the existence of the target file before attempting the move and remove it if necessary. The logic requires a conditional check using file_exists(). If the file exists, you invoke unlink() to delete the old version before calling move_uploaded_file(). This ensures that the new content replaces the old one seamlessly.
Here is how to modify your existing code snippet:
if ($_POST["greg"] == 'true') {
$fileName = $_FILES["file1"]["name"];
$fileTmpLoc = $_FILES["file1"]["tmp_name"];
// ... (validation checks for size, type, etc.) ...
$destinationPath = "documenti/$fileName";
// Check if the destination file already exists
if (file_exists($destinationPath)) {
echo "WARNING: A file named '$fileName' already exists. It will be overwritten.";
// Delete the existing file to allow overwriting
if (!unlink($destinationPath)) {
echo "ERROR: Failed to delete the existing file. Check permissions.";
exit();
}
}
// Attempt to move the uploaded file
if (move_uploaded_file($fileTmpLoc, $destinationPath)) {
echo "The file named <strong>$fileName</strong> uploaded successfully and overwrote the previous version.<br><br>";
// Optional: Check again just in case the move failed silently (rare but possible)
if (!file_exists($destinationPath)) {
echo "ERROR: File verification failed after upload.<br>";
exit();
}
} else {
echo "ERROR: Failed to upload file. Check permissions on 'documenti' folder.<br>";
// Ensure you clean up the temp file if the move fails
if ($fileTmpLoc) {
unlink($fileTmpLoc);
}
}
}
Security Considerations and Best Practices
While enabling overwrite functionality solves your immediate problem, it introduces specific security risks that must be managed. The most critical issue is path traversal. A malicious user could upload a file named ../../../etc/passwd (or similar) to overwrite system files if you do not sanitize the filename. You are currently trusting $fileName directly from the client.
You should always extract the base name of the file using basename() and ensure it contains only safe characters or matches your allowed list. Additionally, never trust the MIME type reported by $_FILES["file1"]["type"]. Always verify the content against the actual file extension and validate the content hash if possible. For example, even if a user uploads a .php file, you should treat it as untrusted code unless it passes strict validation.
File Permissions
Your current code checks for permissions like 0755, which is correct for directories but insufficient for files that need to be overwritten. To allow the web server user (often www-data or apache) to delete and replace existing files, the target directory must have write permissions for its owner, and the directory itself must be writable by the process attempting the upload.
If you are using shared hosting, standard users often lack permission to overwrite arbitrary files in public directories due to security restrictions. In such environments, you might need to:
- Restrict uploads to a subdirectory owned by your account (e.g.,
~/public_html/uploads/) rather than the root of the domain. - Configure the server's file manager or control panel to allow "force overwrite" for specific folders if supported.
Implementation in Modern Frameworks
If you are building a new application or migrating from legacy PHP, consider using Laravel, which abstracts these complexities into robust helpers. The Storage facade handles disk operations safely, preventing direct path traversal attacks by default and managing permissions more securely out of the box. For instance, using Storage::disk('public')->put($fileName, $file->get()) internally handles the overwrite logic with better security defaults than raw PHP functions.
For more details on secure file handling patterns in modern stacks, you can refer to resources like https://laravelcompany.com.