What potential pitfalls should be considered when attempting to save uploaded files for future use in PHP?

One potential pitfall to consider when saving uploaded files for future use in PHP is ensuring that the file is properly sanitized to prevent security vulnerabilities such as directory traversal attacks. It is important to validate the file type, rename the file to prevent overwriting existing files, and store the file in a secure directory to prevent unauthorized access.

// Example code snippet to sanitize and save uploaded file
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type.');
}

// Rename file to prevent overwriting existing files
if (file_exists($uploadFile)) {
    $uploadFile = $uploadDir . uniqid() . '_' . basename($_FILES['file']['name']);
}

// Move uploaded file to secure directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
    echo 'File is valid, and was successfully uploaded.';
} else {
    echo 'File upload failed.';
}