Skip to content
PHP Logo

What are some best practices for using PHP to browse directories and view file contents?

When browsing directories and viewing file contents using PHP, it is important to ensure proper error handling, security measures, and efficiency. Use functions like scandir() to list directory contents, file_get_contents() to read file contents, and htmlspecialchars() to prevent XSS attacks when displaying file contents.

php
// List directory contents
$dir = 'path/to/directory';
$files = scandir($dir);

foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        echo $file . '<br>';
    }
}

// View file contents
$file = 'path/to/file.txt';
if (file_exists($file)) {
    $contents = file_get_contents($file);
    echo htmlspecialchars($contents);
} else {
    echo 'File not found';
}