PHP - 读取 .txt 中的数据并输出 $Data?

PHP - Read data in .txt and output $Data?

你好,我有一个这样的文本文件

data.txt

data e.g. username

我需要将其放入 $tag

File.php

if ($username == "$data") { echo "User Found" } else{ echo "User not found";}

任何帮助真的会很好 :)?

$data = file_get_contents('filehere');
if($username == $data) { echo "User found"; } else { echo "User not found"; }

user_pass.txt:

thomas password
john password2

代码:

<?PHP
$data = fopen('user_pass.txt', 'r');
while (($line = fgets($data)) !== FALSE) {
    $data = explode(' ', $data);
    if ($username == $data[0] && $password == $data[1]) {
        echo "User found";
    } else {
        echo "User not found";
    }
}
?>

除非我错过了什么?如果您遇到错误,请回复。

这里可以使用的一种方法是使用 preg_match() 并同时使用 \b 字边界选项和 i 开关不区分大小写,这将适用于单行或多行数据。将匹配 "john" 或 "John",作为示例。

<?php 
$_POST['name'] = "john";

$var = trim($_POST['name']); // should there be a space entered
// $var = $_POST['name'];

$pattern = "/\b$var\b/i";

$fh = fopen('data.txt', 'r') or die("Can't open file");
while (!feof($fh)) {
    $line = fgets($fh, 4096);
    if (preg_match($pattern, $line)) { 

echo "MATCH FOUND";

    }

else{
echo "NOT FOUND";
}

}

fclose($fh);

但是,如果条目由 space 分隔,这将不起作用。即:"john doe".

如果是这种情况,您将需要使用以下内容,stripos() 不区分大小写。

<?php 
$_POST['name'] = "john doe";

$search = trim($_POST['name']);
// $search = $_POST['name'];


// Read from file
$lines = file('data.txt');
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(stripos($line, $search) !== false){
    echo "Found: " . $line; }

}

参考文献:


脚注:

  • 数据库将更容易实现这一点,并将提供比 text-based/flatfile 方法更多的自由和灵活性。

函数搜索:post function search in PHP

  function search($search, $string) {

    $pos = strpos($string, $search);  

    if ($pos === false) {

      echo "The string '$search' was not found.";       

    } else {

      echo "The string '$search' was found ";   
      echo "and exists at position $pos.";  

    }    

  }

love.txt 作为文件

we
love
php
programming

打开文件:

  $file = fopen("love.txt", "r");

为打开的文件调用函数搜索和函数 fread 'love.txt'

  search("love", fread($file, filesize("love.txt")));

结果:

The string 'love' was found and exists at position 4.