【问题标题】:PHP fwrite without duplicatePHP fwrite 没有重复
【发布时间】:2017-04-19 13:17:11
【问题描述】:

我想以这样一种方式编写代码,它将任何输入写入并保存在 .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")
?> 

【问题讨论】:

  • 到目前为止您尝试过哪些代码/方法?
  • 这里是另一个代码

标签: php fopen fwrite


【解决方案1】:

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

如果找到名称,则回显“名称存在”。如果没有找到,它会回显“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");
    }
} 
?>

【讨论】:

  • 非常感谢。有效。如果我在 TeX 字段中没有任何内容刷新页面,它会告诉我名称存在。它将空白空间视为数组。帮助
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 2015-03-24
  • 2015-10-25
相关资源
最近更新 更多