在尝试任何复杂的现场直播之前,我正在练习一些 PHP 编码。我的目标是验证在 HTML/JavaScript 表单上输入的单词。我想使用 PHP 打开和解析一个文本文件,看看表单上输入的单词是否与该文本文件中的单词匹配。到目前为止,我得到的唯一返回表明该单词不在列表中,因此我不确定代码是否正在比较两个字符串。我的 HTML/JS 代码是:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Using this html document</title>
<script language="JavaScript">
function trim(s) {
while (s.charAt(0) == ' ')
s = s.substring(1);
while (s.charAt(s.length - 1)== ' ')
s = s.substring(0, s.length - 2);
return s;
}
function check(lname)
{
var x = document.getElementById(lname);
var s = new String(x.value);
s = trim(s);
if(s == "")
{
alert("Please enter a word");
javascript:history.go(0);
}
else
x.value = s;
}
</script>
</head>
<body>
<form action="http://localhost/Exercise13.php" method="post">
<label for="fname">Name: </label>
<input type="text" name="lname" id="lname" size="20"><br><br>
<input type="submit" name="submit" id="submit" value=" Submit "onclick = "check ('lname');">
</form>
</body>
</html>
我的 PHP 代码是这样的:
<?php
$fh = fopen("a.txt","r")or die("Can't open file");
$s = $_POST["lname"];
while(!feof($fh))
{
$line = fgets($fh);
$a = trim($line);
}
if (strcmp($s,$a) == 0)
print ("<h1>" . $s . " is in the list</h1><br>");
fclose($fh);
print ("<h1>" . $s . " is not in the list</h1><br>");
?>
我的 .txt 文件只是一个随机单词列表,该列表中有一些我试图通过修剪删除的字符。我已经使用 PHP 检查器检查了我的 PHP 是否有任何语法错误,一切看起来都很好。它只是没有像我想要的那样运作。有任何想法吗?