Home  >  Article  >  Backend Development  >  How to Efficiently Search for Strings in Files with PHP

How to Efficiently Search for Strings in Files with PHP

Susan Sarandon
Susan SarandonOriginal
2024-10-23 16:36:02464browse

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!

Statement:
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