In what ways can PHP developers ensure that file paths passed as input are sanitized and secure?

To ensure that file paths passed as input are sanitized and secure, PHP developers can validate the input to ensure it contains only allowed characters and does not allow directory traversal attacks. This can be achieved by using functions like realpath() to resolve the path to its canonical form and checking if it matches an allowed directory. Additionally, developers can use functions like basename() to extract the filename from the path and verify it against a list of allowed filenames.

$input_path = $_POST['file_path'];

$allowed_directory = '/path/to/allowed/directory/';
$allowed_filenames = ['file1.txt', 'file2.txt'];

$real_path = realpath($input_path);

if (strpos($real_path, $allowed_directory) !== 0) {
    die('Invalid file path');
}

$filename = basename($real_path);

if (!in_array($filename, $allowed_filenames)) {
    die('Invalid file name');
}

// Proceed with secure file path