I am having a 'names.txt' text file having names like John, Mike, Julia. Now i enter another set of names in append mode to the existing 'names.txt' file like Steve, Ben, Mike. How can I restrict the 'Mike' duplicate entry in php? Or how can I prompt an error message something like 'Mike, name already existed. Please enter another name' so that duplication can be avoided.
The code is
<!DOCTYPE html>
<html>
<head>
<title>Form Page</title>
</head>
<body>
<form action="Files.php" method="POST">
<textarea rows="15" cols="30" value="textbox" name="textbox"></textarea></br>
<input type="submit" value="Save" name="Save">
<input type="submit" value="Fetch" name="Fetch">
</form>
</body>
</html>
<?php
/*** Get names from 'names.txt' file and prints the names stored in it ***/
if(isset($_POST['Fetch'])){
$file_names = "names.txt";
$current_names = file_get_contents($file_names);
echo nl2br($current_names);
}
/*** Get names from text box and Put to the 'names.txt' file in append mode ***/
if(isset($_POST['Save'])){
$current_names = $_POST["textbox"];
file_put_contents("names.txt", PHP_EOL.$current_names, FILE_APPEND);
/*** Get names form 'names.txt' file and prints the names stored in it ***/
$file_names = "names.txt";
$current_names = file_get_contents($file_names);
echo nl2br($current_names);
}
?>
when separating your text-file entries with PHP_EOL
:
(be careful - the output of PHP_EOL
depends on the operating system PHP is running on!)
//new name to insert if not in file:
$new_name = "Martin";
$file_content = file_get_contents('names.txt');
//names into array elements
$content_array = explode(PHP_EOL, $file_content);
//trim spaces and stuff from the data in your array:
foreach($content_array AS $key => $value)
{
$content_array[$key] = trim($value);
}
if(in_array($new_name, $content_array)) echo "name found - don't save it again";
probably the best way would be to
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With