1

I have a C++ program that reads a file and prints it one line at a time (one line per second).

I need the code executed from within a PHP script and the output piped back to a browser. So far, I have tried exec and passthru but in both these cases, the entire output is 'dumped' on the browser after program execution.

How do I get PHP to stream the output back to the browser.

Here is the code I have written so far:
sender.php: Sends the request to execute.

<?php 

/*
 * Purpose of this program:
 * To display a stream of text from another C++-based program.
 * Steps:
 * 1. Button click starts execution of the C++ program.
 * 2. C++ program reads a file line-by-line and prints the output.
 */

?>

<html>

<head>
    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#startDisplaying").click(function() {
                console.log("Starting to display.");
                /*
                //initialize event source.
                if(!!window.EventSource) {
                    console.log("Event source is available.");
                    var evtSource = new EventSource("receiver.php");

                    evtSource.addEventListener('message', function(e) {
                        console.log(e.data);
                    }, false);

                    evtSource.addEventListener('open', function(e) {
                        console.log("Connection opened.");
                    }, false);

                    evtSource.addEventListener('error', function(e) {
                        console.log("Error seen.");
                        if(e.readyState == EventSource.CLOSED) {
                            console.log("Connection closed.");
                        }
                    }, false);
                } else {
                    console.error("Event source not available.");
                }
                */
                $.ajax({
                    type: 'POST',
                    url: 'receiver.php',
                    success: function(data) {
                        console.log("Data obtained on success: " + data);
                        $("#displayText").text(data);
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        console.error("Error seen: " + textStatus + " and error = " + errorThrown);
                    }
                });
            });
        });
    </script>
</head>

<body>
<textarea id="displayText"></textarea><br/>
<button id="startDisplaying">Start Displaying</button>
</body>

</html>  

The receiver.php, which executes the program:

<?php 

/* This file receives the request sent by sender.php and processes it.
 * Steps:
 * 1. Start executing the timedFileReader executable.
 * 2. Print the output to the textDisplay textarea.
 */

header('Content-Type: text/event-stream');
header('Cache-control: no-cache');

function sendMsg($id, $msg) {
    echo "id: $id".PHP_EOL;
    echo "data: $msg".PHP_EOL;
    echo PHP_EOL;
    ob_flush();
    flush();
}

$serverTime = time();

$cmd = "\"timedFileReader.exe\"";
//sendMsg($serverTime, 'server time: '.exec($cmd, time()));
passthru($cmd);

/*
$cmd = "\"timedFileReader.exe\"";
exec($cmd. " 2>&1 ", $output);
print_r($output);
*/
?>

The C++ program:

#include<fstream>
#include<string>
#include<unistd.h>
#include<cstdlib>
#include<iostream>
using namespace std;

int main(int argc, char *argv[]) {

  ifstream ifile;
  string line;

  ifile.open("file.txt");
  if(!ifile) {
    cout << "Could not open file for reading." << endl;
    exit(0);
  }

  while(getline(ifile, line)) {
    cout << line << endl;
    //usleep(5000000);  //sleep for 1000 microsecs.
    sleep(1);
  }

  return 0;
}

Is this model of execution even possible within PHP?
Any help is most welcome.

Sriram
  • 10,298
  • 21
  • 83
  • 136
  • Unless you plan to compile the program dynamically and then run it, the language doesn't really matter - you're simply running a binary. – Shomz May 02 '15 at 21:13

1 Answers1

1

Refer to http://php.net/manual/en/function.popen.php.

It also could be HTTP server dependent, as it can close browser session before you will read your C++ application output.

Not sure reasons you using that PHP to C++ bridge, but based on your code - you could do whole work within just PHP. Or use C++ CGI interface...

(similar question: how get the output from process opend by popen in php?)

Community
  • 1
  • 1