How can PHP be used to check if an entry exists in a text file and output a message if it does or add it if it doesn't?

To check if an entry exists in a text file using PHP, you can read the file line by line and compare each line to the entry you are looking for. If the entry is found, you can output a message indicating its presence. If the entry is not found, you can append it to the end of the file.

<?php
$entry = "example_entry";

$filename = "data.txt";

$found = false;

$file = fopen($filename, "r");

while(!feof($file)) {
    $line = trim(fgets($file));
    if($line == $entry) {
        $found = true;
        echo "Entry already exists in the file.";
        break;
    }
}

fclose($file);

if(!$found) {
    $file = fopen($filename, "a");
    fwrite($file, $entry . "\n");
    fclose($file);
    echo "Entry added to the file.";
}
?>