PHP: Interscript Communication via File

Sometimes we want a php script to communicate with another script. For what purpose? Suppose you have a script that runs a long process and you want to update the status of that script every second (consider a progress bar, for example). The simplest solution is to let the main script echo the status every second, but then the whole screen will be covered by status update, and that’s not what we want. The idea then is to have another script “ask” the status of the main script and echo it. By putting some javascript to refresh that other page every second, we can get a neat update.

The question is how does the other script “ask” the status of the main script? The simplest solution would be using file as a pipe between the two scripts. Let the main script keep writing status to the file and let the other script read the file, parse it, and display the status. Consider this simple piece of code:


for ($i=0; $i<50; $i++){
  file_put_contents("pipe", $i);


echo file_get_contents("pipe");
//put javascript to refresh
echo "<script>
function refresh(){ window.location.reload(); }
setTimeout( 'refresh()', 1000 );

Browse main.php and let that page open or the script will eventually die, then browse other.php to see the updated status. With this simple idea, you can make a progress bar using some javascript to draw the bar. You can even make the progress bar in main.php if you put AJAX in main.php calling other.php.

This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

6 Responses to PHP: Interscript Communication via File

  1. Captain_kurO says:

    script di atas memberi ide dasar, tinggal dikasih mekanisme mutexnya

    • evangozali says:

      Iya Wil, mutexnya paling sederhana bisa make file lain sebagai lock (dicreate untuk lock, terus dihapus untuk unlock), atau bisa juga pake fungsi flock untuk locking file pipenya.

  2. Dody Dharma says:

    Nice Tutorial…

  3. Dody Dharma says:

    van postingan ente benar-benar membantu…
    awak telah menerapkannya…
    senang sekali…
    Thx Van…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s