What are the potential security risks of allowing users to input image paths for display on a website in PHP?

Allowing users to input image paths for display on a website in PHP can pose a security risk known as path traversal. This vulnerability can allow attackers to access sensitive files on the server by manipulating the input path. To mitigate this risk, it is important to validate and sanitize user input to ensure that it only contains allowed characters and does not allow access to files outside the intended directory.

// Sanitize user input for image path
$userInput = $_POST['image_path'];
$allowedPath = '/path/to/allowed/directory/';

// Check if user input is within the allowed directory
if (strpos($userInput, $allowedPath) !== 0) {
    die('Invalid image path');
}

// Display the image
echo '<img src="' . $userInput . '" alt="User Image">';