PHP: Interscript Communication via File
Februari 2, 2010 at 3:38 pm 6 komentar
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:
main.php
for ($i=0; $i<50; $i++){
file_put_contents("pipe", $i);
sleep(1);
}
other.php
echo file_get_contents("pipe");
//put javascript to refresh
echo "<script>
function refresh(){ window.location.reload(); }
setTimeout( 'refresh()', 1000 );
</script>";
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.
Entry filed under: Programming. Tags: ajax, javascript, php, Programming, web.
6 Komentar Add your own
Tinggalkan Balasan
Trackback this post | Subscribe to the comments via RSS Feed
1.
Captain_kurO | Februari 2, 2010 pada 11:45 pm
script di atas memberi ide dasar, tinggal dikasih mekanisme mutexnya
2.
evangozali | Februari 3, 2010 pada 2:48 pm
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.
3.
petra | Februari 3, 2010 pada 10:24 am
nice post
4.
Dody Dharma | Februari 4, 2010 pada 12:12 pm
Great!
Nice Tutorial…
5.
Dody Dharma | Februari 12, 2010 pada 9:59 am
van postingan ente benar-benar membantu…
awak telah menerapkannya…
senang sekali…
Thx Van…
6.
evangozali | Februari 12, 2010 pada 10:06 am
Saya merasa tersanjung secuil tulisan ini bisa membantu dewa Dody