Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7433703
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T09:42:53+00:00 2026-05-29T09:42:53+00:00

Using PHP , I would like to make a while loop that reads a

  • 0

Using PHP, I would like to make a while loop that reads a large file and sends the current line number when requested. Using Ajax, I’d like to get the current line count and print it out onto a page. Using html buttons, I’d like to be able to click and activate or terminate a javascript thread that runs only ONCE and calls the ajax method.

I have given it a shot but for some reason, nothing prints unless I comment out the echo str_repeat(' ',1024*64); function and when it’s commented out, it shows the entire loop result:

1 row(s) processed.2 row(s) processed.3 row(s) processed.4 row(s) processed.5 row(s) processed.6 row(s) processed.7 row(s) processed.8 row(s) processed.9 row(s) processed.10 row(s) processed.

In a single line instead of showing them in separate lines like:

1 row(s) processed.
2 row(s) processed.
3 row(s) processed.
4 row(s) processed.
5 row(s) processed.
6 row(s) processed.
7 row(s) processed.
8 row(s) processed.
9 row(s) processed.
10 row(s) processed.

Also I’m not sure how to terminate the JavaScript thread. So 2 problems in total:

 1. It's returning the entire While loop object at once instead of each time it loops.
 2. I'm not sure how to terminate the JQuery thread.

Any ideas? Below is my code so far.

msgserv.php

<?php

//Initiate Line Count
$lineCount = 0;

// Set current filename
$file = "test.txt";

// Open the file for reading
$handle = fopen($file, "r");

//Change Execution Time to 8 Hours
ini_set('max_execution_time', 28800);

// Loop through the file until you reach the last line
while (!feof($handle)) {

    // Read a line
    $line = fgets($handle);

    // Increment the counter
    $lineCount++;

    // Javascript for updating the progress bar and information
    echo $lineCount . " row(s) processed.";

    // This is for the buffer achieve the minimum size in order to flush data
    //echo str_repeat(' ',1024*64);

    // Send output to browser immediately
    flush();

    // Sleep one second so we can see the delay
    //usleep(100);
}

// Release the file for access
fclose($handle);

?>

asd.html

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" charset="utf-8"></script>

        <style type="text/css" media="screen">
            .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
            .new{ background-color:#3B9957;}
            .error{ background-color:#992E36;}
        </style>

    </head>
    <body>

    <center>
        <fieldset>
            <legend>Count lines in a file</legend>
            <input type="button" value="Start Counting" id="startCounting" />
            <input type="button" value="Stop Counting!" onclick="clearInterval(not-Sure-How-To-Reference-Jquery-Thread);" />
        </fieldset>
    </center>

    <div id="messages">
        <div class="msg old"></div>
    </div>

    <script type="text/javascript" charset="utf-8">
        function addmsg(type, msg){
            /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
            $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
        }

        function waitForMsg(){
            /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
            $.ajax({
                type: "GET",
                url: "msgsrv.php",
                async: true, /* If set to non-async, browser shows page as "Loading.."*/
                cache: false,
                timeout:2880000, /* Timeout in ms set to 8 hours */

                success: function(data){ /* called when request to barge.php completes */
                    addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                    setTimeout(
                    'waitForMsg()', /* Request next message */
                    1000 /* ..after 1 seconds */
                );
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    addmsg("error", textStatus + " (" + errorThrown + ")");
                    setTimeout(
                    'waitForMsg()', /* Try again after.. */
                    "15000"); /* milliseconds (15seconds) */
                },
            });
        };

        $('#startCounting').click(function() {
            waitForMsg();
        });
    </script>

</body>
</html>

test.txt

1
2
3
4
5
6
7
8
9
10
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T09:42:53+00:00Added an answer on May 29, 2026 at 9:42 am

    Using:

    • jQuery kill ajax request
    • ignore_user_abort()
    • ob_flush()

    should do all you need in one php thread

    EDIT

    Take a look at nickb’s answer, if you’re looking for a way how to do this simply it would be following algorithm:

    1. javascript opens process.php via ajax (which will do all the work AND print status reports), you have to look up whether jQuery ajax supports continuous loading
    2. if user decides to stop refreshes you’ll kill loading as show in provided link

    In process.php:

    ignore_user_abort(); // Script will finish in background
    while(...){
      echo "Page: $i\n";
      ob_flush();
    }
    

    EDIT 2 requested example (bit of different and ugly, but simple). test_process.php:

    // This script will write numbers from 1 to 100 into file (whatever happens)
    // And sends continuously info to user
    $fp = fopen( '/tmp/output.txt', 'w') or die('Failed to open');
    set_time_limit( 120);
    ignore_user_abort(true);
    
    for( $i = 0; $i < 100; $i++){
        echo "<script type=\"text/javascript\">parent.document.getElementById( 'foo').innerHTML += 'Line $i<br />';</script>";
        echo str_repeat( ' ', 2048);
        flush();
        ob_flush();
        sleep(1);
        fwrite( $fp, "$i\n");
    }
    
    fclose( $fp);
    

    And main html page:

    <iframe id="loadarea"></iframe><br />
    <script>
    function helper() {
        document.getElementById('loadarea').src = 'test_process.php';
    }
    function kill() {
        document.getElementById('loadarea').src = '';
    }
    </script>
    
    <input type="button" onclick="helper()" value="Start">
    <input type="button" onclick="kill()" value="Stop">
    <div id="foo"></div>
    

    After hitting start lines as:

    Line 1
    Line 2
    

    Appeared in the div #foo. When I hit Stop, they stopped appearing but script finished in background and written all 100 numbers into file.

    If you hit Start again script starts to execute from the begging (rewrite file) so would parallel request do.

    For more info on http streaming see this link

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a jar file that I would like to execute using PHP, but
Using Php I would like to extract the current Url of a page including
I would like to access a MySQL database using PHP. Can someone please explain
I would like to extract the GPS EXIF tag from pictures using php. I'm
Assuming the input string +123-321+123 345 , using PHP's regex functions I would like
I would like to redirect all images to a showimage.php, using htaccess But if
I'm using a multi dimensional array in php, I would like to know how
I would like to run a PHP script from another PHP script so that
Using MySQL, i'm selecting a list of songs in spanish that i would like
I know how I would achieve this using PHP, but with jQuery / JavaScript

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.