What are some best practices for handling file paths and filenames in PHP when accessing them for streaming purposes?
When handling file paths and filenames in PHP for streaming purposes, it's important to sanitize and validate the input to prevent directory traversal attacks and ensure compatibility across different operating systems. One common approach is to use the realpath() function to resolve the full path of the file and then use functions like basename() to extract the filename for streaming.
// Example of handling file paths and filenames for streaming purposes
$filePath = '/path/to/file.txt';
// Sanitize and validate the file path
$realPath = realpath($filePath);
if ($realPath && is_file($realPath)) {
$fileName = basename($realPath);
// Implement streaming logic here
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
readfile($realPath);
} else {
echo 'Invalid file path';
}