How can realpath() function be used to ensure correct file paths in PHP file uploads?

When handling file uploads in PHP, it's important to ensure that the file paths are correct to prevent any potential security vulnerabilities or errors. One way to do this is by using the realpath() function, which resolves any symbolic links or relative paths to their absolute counterparts. This helps to ensure that the file paths are accurate and secure when processing file uploads in PHP.

$uploadDir = '/path/to/uploads/';

// Get the absolute path of the upload directory
$uploadDir = realpath($uploadDir);

// Check if the upload directory exists
if (!$uploadDir || !is_dir($uploadDir)) {
    die('Upload directory does not exist.');
}

// Proceed with file upload handling
// Example: move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $_FILES['file']['name']);