How can file paths and names be securely passed as parameters in a PHP script?

When passing file paths and names as parameters in a PHP script, it is important to validate and sanitize the input to prevent any potential security vulnerabilities such as directory traversal attacks. One way to securely pass file paths and names is to use PHP's built-in functions like realpath() to validate the paths and ensure they point to the correct file or directory. Additionally, you can use functions like basename() to extract the file name from the path and further sanitize it before using it in your script.

// Example of securely passing file paths and names as parameters in a PHP script

// Validate and sanitize the file path
$filePath = realpath($_GET['file']);
if ($filePath === false || strpos($filePath, '/path/to/secure/directory/') !== 0) {
    die('Invalid file path');
}

// Extract the file name from the path and sanitize it
$fileName = basename($filePath);

// Now you can safely use $filePath and $fileName in your script
echo "File path: $filePath<br>";
echo "File name: $fileName";