0

I basically need to check the text file that is acting as a makeshift database, for any duplicates against the incoming entry. The examples I have seen using strpos, all have the $searchfor = 'actual string in quotes' but even when I cheat and put the email in question in by manually typing it in 'quotes' it still does not find the match.

I know the $file = fopen("db.txt", "a+") or die("unable to find"); is working, because it adds the entry to the file. I just can't seem to search it properly. Help.

  <!DOCTYPE html>
<html>
<head>
<title>Form Validation
    <style type = "text/css">
    p { margin: 0px; }
    .error { color: red }
    p.head { font-weight: bold; margin-top: 10px; }
    </style>
</title>

</head>
<body>

<!-- <?php include 'db.txt';?> -->

<?php
//Sends an error message and instructs to try again if email is not in the correct email formal
    if(!preg_match(" /\S+@\S+\.\S+/", $_POST['email']))
    {
        print("<p class = 'error'>Invalid email. Must be in the form of name@emailprovider.com </p>
        <p>Click back and enter a valid email. </p>");
        die();
    }
?>


<?php
$entry = array(
    $fname = $_POST['fname'],
    $lname = $_POST['lname'],
    $email = $_POST['email'],
    $uname = $_POST['user_name'],
    $age   = $_POST['age_bracket']);

print "The information you entered:<br>";
foreach($entry as $value){
    echo $value, " ";
}
//Opens existing file, appends data, writes entire file back to textfile
    $file = fopen("db.txt", "a+") or die("Unable to open file!");
    // $searchfor = 'benjamin.henry@selu.edu';
    $searchfor = $email;
    $filecontents = file_get_contents($file);
    if(strpos($filecontents, $searchfor))
    {
        echo "Duplicate Found";
    }

    $data = $fname. "|" .$lname. "|" .$email. "|" .$uname. "|" .$age. "\n";
    fwrite($file,$data);
    fclose($file);
//Welcome message to user and confirms the information will posted to the database.
    ?>
    <p>Hi <?php print( $_POST["fname"] ); ?>. Thank you for your request.</p>
    <p class = "head">The following information has been saved in our database:</p>
    <p>First Name: <?php print( $_POST["fname"]);?></p>
    <p>Last Name: <?php print( $_POST["lname"]);?></p>
    <p>Email: <?php print( $_POST["email"]);?></p>
    <p>User Name: <?php print( $_POST["user_name"]);?></p>
    <p>Age Bracket: <?php print( $_POST["age_bracket"]);?></p>

</body>
</html>
  • Move your fopen after the file_get_contents. It doe not require the file to be open. And since fopen with option +a moves the pointer at the end of the file, either file_get_contents does not want to read an open file, or it searches from the end of the file (where the pointer is). Try and let us know. – Nic3500 Oct 11 '17 at 17:50
  • Try this - https://stackoverflow.com/questions/9059026/php-check-if-file-contains-a-string?answertab=active#tab-top – waterloomatt Oct 11 '17 at 18:05

0 Answers0