I am practicing some PHP coding before I attempt anything complicated live. My goal is to validate a word entered on an HTML/JavaScript form. I want to use PHP to open and parse a text file and see if the word entered on the form matches a word on this text file. So far the only return I'm getting indicates that the word is NOT on the list, so I'm not sure the code is comparing the two strings. My HTML/JS code is:
<!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>
My PHP code is this:
<?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>");
?>
My .txt file is just a list of random words, the list has some characters that I'm trying to remove via trim. I've checked my PHP for any syntax errors using PHP checker and everything looks good. It's just not functioning like I want it to. Any ideas?
Your logic is broken, as you only check the result of the last string in the file. You'd want to move the check into the actual loop, so that you compare the value of each line, and not just the value of $a after the loop has finished.
$found = false;
while (!feof($fh))
{
$line = trim(fgets($fh));
if ($line == $s)
{
$found = true;
break;
}
}
.. and then check the value of $found after the loop has searched through the file. This will also end the loop as soon as a match is found.
I'd also like to point as that this is (very) inefficient, but as a learning exercise it's all good.