Skip to content
PHP Logo

What are the potential security risks associated with using file_get_contents() on user-input data in PHP?

Using file_get_contents() on user-input data in PHP can pose security risks such as directory traversal attacks, allowing an attacker to access sensitive files on the server. To mitigate this risk, it is important to validate and sanitize user input before using it in file_get_contents() to ensure that only allowed files are accessed.

php
$user_input = $_GET['file']; // Assuming user input is coming from a GET parameter
$allowed_files = ['file1.txt', 'file2.txt']; // List of allowed files

if (in_array($user_input, $allowed_files)) {
    $file_contents = file_get_contents($user_input);
    // Process the file contents
} else {
    // Handle error or show appropriate message
}