How to Check if a File Contains Specific Content in PHP?

Mary-Kate Olsen
Release: 2024-10-23 18:21:42
Original
790 people have browsed it

How to Check if a File Contains Specific Content in PHP?

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!