title: Function to read, search a string and modify a txt file using php
body: <p>I'm writing a php function which must open and read line by line the content of a txt file saved in the same directory of the php file and checks if the first value of the line is equal to a number which I give it as a parameter of the function and if this number isn't in the file I will create a new line with the number followed by another information separated by a space. This funcion is in a webhook file of a Facebook Messenger bot and it doesn't work if the function isn't commented out and I don't know why because I checked the code several times and I haven't found the error.
  The code of the function is:</p>
  
  <pre><code>function messagesNumber($userid)
  {
      $fo = ("url of the files", "a+");
      $found = false;
      if($fo) {
          $line = fgets($fo);
          while(! feof($fo) &amp;&amp; $found == false) {
              $words = explode(" ", $line, 2);
              if($words[0] == $userid) {
                  $found = true;
                  $words[1] += 1;
                  $messagges = $words [1];
                  str_replace($line, $words, $fo);
              }
              $line = fgets($fo);
          }
          if(! $found) {
              fprintf($fo, "%d 1", $userid);
              $messages = 1;
          }
      }
      else
          $messagges = -1;
      fclose($fo);
      return $messagges;  
  }
  </code></pre>
  
  <p>It returns: -1 if the file can't be open or an integer that coincides with the second number of every line.</p>
  
  <p>It is an example of the txt file:</p>
  
  <pre><code>282318736127 5
  827813487273 3
  ...
  </code></pre>
  
  <p>The first number is the id which Facebook assign to every user and the second number is a counter who counts how many messages a user writes to the bot and I increase this last number every times that a specific user sends a message to the bot.</p>