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

How to Efficiently Search for Strings in Files with PHP

Susan Sarandon
Release: 2024-10-23 16:36:02
Original
647 people have browsed it

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

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

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

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 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template