How to Verify File Content in PHP
Searching a file for specific content is essential in various programming scenarios. This task can be achieved in PHP through the use of the file_get_contents() function or through the command-line utility grep.
Consider your original code, which attempted to check if a file contained a given string. The flaw in your code was in the conditional statement within the loop, where you were mistakenly using a positive equality check if (strpos($buffer, $id) === false) which would only mark the file as valid if the string was not present. To correct this, it should be changed to if (strpos($buffer, $id) !== false) to properly identify the presence of the string.
However, for simplicity's sake, here's a more efficient solution that utilizes file_get_contents():
<code class="php">if( strpos(file_get_contents("./uuids.txt"),$_GET['id']) !== false) { // do stuff }</code>
This approach loads the entire file into memory and searches for the string, which is more efficient than reading the file line by line.
If you're concerned about memory usage, you can alternatively use grep to search for the string without loading the entire file into memory:
<code class="php">if( exec('grep '.escapeshellarg($_GET['id']).' ./uuids.txt')) { // do stuff }</code>
Both of these methods effectively determine if the specified file contains the provided string, allowing you to proceed with the intended actions.
The above is the detailed content of How to Check if a File Contains Specific Content in PHP?. For more information, please follow other related articles on the PHP Chinese website!