What are the potential security risks associated with accessing external directories for image counting in PHP?

When accessing external directories for image counting in PHP, one potential security risk is the possibility of directory traversal attacks, where an attacker could navigate to sensitive directories on the server. To prevent this, it is important to sanitize user input and validate the directory path before accessing it. One way to do this is by using the `realpath()` function in PHP to get the canonicalized absolute pathname of the specified path.

$directory = $_GET['directory'];

// Validate the directory path
$realPath = realpath($directory);

if ($realPath !== false && strpos($realPath, '/path/to/allowed/directory') === 0) {
    // Proceed with image counting
} else {
    die('Invalid directory path');
}