What are the best practices for handling file paths in PHP scripts to avoid errors and security vulnerabilities?

When handling file paths in PHP scripts, it is important to sanitize user input to prevent directory traversal attacks and other security vulnerabilities. One way to do this is by using the realpath() function to resolve the full path of a file and ensure it is within the allowed directory. Additionally, always use absolute paths rather than relative paths to avoid confusion and potential errors.

// Sanitize user input for file path
$filePath = realpath($_POST['file']);

// Check if the resolved path is within the allowed directory
$allowedDirectory = '/path/to/allowed/directory/';
if (strpos($filePath, $allowedDirectory) !== 0) {
    die('Invalid file path');
}

// Use the sanitized file path in your script
// For example, to read the contents of the file
$fileContents = file_get_contents($filePath);