What are some best practices for handling file paths and extensions in PHP?

When working with file paths and extensions in PHP, it is important to sanitize and validate user input to prevent security vulnerabilities such as directory traversal attacks. One best practice is to use PHP's built-in functions like realpath() to normalize file paths and ensure they point to valid locations on the server. Additionally, when handling file extensions, always validate and sanitize them to prevent malicious scripts from being executed on the server.

// Example of sanitizing file path input
$userInput = $_POST['file_path'];
$filePath = realpath('uploads/' . $userInput);

if ($filePath !== false && strpos($filePath, 'uploads/') === 0) {
    // File path is valid and safe to use
    // Proceed with file operations
} else {
    // Invalid file path, handle error accordingly
}