How can the filename of an uploaded file be structured and stored in both the database and a designated folder in a consistent manner?
To ensure consistency in storing filenames of uploaded files in both the database and a designated folder, you can use a unique identifier combined with the original filename. This can help prevent filename conflicts and make it easier to retrieve files later on. You can achieve this by generating a unique identifier (such as a UUID) for each uploaded file and appending it to the original filename before storing it in both the database and folder.
// Generate a unique identifier for the uploaded file
$uniqueID = uniqid();
// Get the original filename of the uploaded file
$originalFilename = $_FILES['file']['name'];
// Combine the unique identifier with the original filename
$newFilename = $uniqueID . '_' . $originalFilename;
// Store the filename in the database
// Assuming $db is the database connection
$query = "INSERT INTO files (filename) VALUES ('$newFilename')";
$result = mysqli_query($db, $query);
// Store the file in the designated folder
$uploadDirectory = 'uploads/';
$targetPath = $uploadDirectory . $newFilename;
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);