What are some best practices for handling file uploads in PHP to ensure files are saved with desired names?
When handling file uploads in PHP, it is important to ensure that files are saved with desired names to avoid conflicts and maintain organization. One way to achieve this is by using a combination of a unique identifier, such as a timestamp or random string, along with the original file extension. This can help prevent overwriting existing files and provide a systematic way of naming uploaded files.
// Generate a unique filename for the uploaded file
$originalFileName = $_FILES['file']['name'];
$extension = pathinfo($originalFileName, PATHINFO_EXTENSION);
$uniqueFilename = uniqid() . '_' . time() . '.' . $extension;
// Move the uploaded file to desired directory with the unique filename
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $uniqueFilename);
// $uniqueFilename now contains the desired name for the uploaded file