PHP fwrite 不重复

PHP fwrite without duplicate

我想以这样的方式编写代码,它将任何输入写入并保存在 .TXT 文件中。然后应该有搜索整个文件(txt)的功能,如果一个文本或单词之前已经写过或保存过,它应该会带来错误。

如果有人写了Love,另一个人想再次输入Love,应该会报错。

这是我的代码

<?php
$name=$_POST['name'];
$myfile=
fopen("man.txt" , "a+") or
die("Unable to open file!");
fwrite($myfile, "Name:".$name. "\r\n")
?> 

这里我使用了 in_array 函数来检查我们为提交的名称填充的数组 ($users)。

如果找到名字,就是回显"Name Exists"。如果未找到,则回显 "No" 并添加名称。

<?php 

$name = $_POST['name'];
if (empty($name)) { echo "Please enter your name"; } else $name=$name;

$myfile= fopen("mam.txt" , "a+") or die("Unable to open file!");

$path="mam.txt";

if (file_exists($path)) {
    $contents = file_get_contents($path);
    $contents = explode("\r\n", $contents);

    $users = array();

    foreach ($contents as $value) {
        $users[] = $value;
    }
    // Search the file for the submitted name
    if (in_array($name, $users)) {
        // The name already exists
        echo "Name exist";
    } else {
        // The name doesnt exist
        echo "NO"; 
        // Add the new name
        fwrite($myfile, $name. "\r\n");
    }
} 
?>