Home >Backend Development >PHP Tutorial >How to Efficiently Search for Strings in Files with PHP
Finding Strings in Files with PHP
In web development, it's often necessary to check if a specific string is present within a file. This article demonstrates a method to accomplish this task in PHP.
Problem Statement
The following PHP code attempts to verify if a file contains a string sent to the page through a GET request. However, it returns incorrect results:
<code class="php"> // ... while (($buffer = fgets($handle)) !== false) { if (strpos($buffer, $id) === false) $valid = TRUE; } // ...</code>
Solution 1: file_get_contents()
A more efficient approach is to use the file_get_contents() function, which loads the entire file into memory:
<code class="php"> if( strpos(file_get_contents("./uuids.txt"),$_GET['id']) !== false) { // ... }</code>
Solution 2: exec()
For large files, it's preferable to use exec() to avoid potential memory issues:
<code class="php"> if( exec('grep '.escapeshellarg($_GET['id']).' ./uuids.txt')) { // ... }</code>
The above is the detailed content of How to Efficiently Search for Strings in Files with PHP. For more information, please follow other related articles on the PHP Chinese website!