0

Let's say that I want a webpage that displays PHP memory usage in realtime.

I can get memory usage with:

memory_get_peak_usage(1)

I can print it in an input field like this:

<form>
    Memory usage: <input type="text" name="FirstName" value="<?echo memory_get_peak_usage(1);?>">
</form>

and an option to update the value in the input field would be reloading the page, but how can I do it without refreshing?

I bet I have to use GET/POST methods.

while (1)
{
    $mem =  memory_get_peak_usage(1);
    sleep(0.5);
    update_inputField_value($mem);
}
Alain1405
  • 2,259
  • 2
  • 21
  • 40
  • 1
    once page loads, the peak memory usage wont change so refreshing it is pointless. –  Feb 16 '14 at 22:57
  • I don't get your point. My initial purpose was to monitor memory usage to debug my Wordpress site, and understand which function I wrote was using too much memory. I could have a browser window from which I load Wordpress and another one that keep refreshing and tells me when too much memory is used. – Alain1405 Feb 16 '14 at 23:03
  • 2
    once the page is output, php is finished, so memory for that process is finished. –  Feb 16 '14 at 23:05
  • 2
    The function only returns the memory usage of the current request so you won't be able to achieve what you would like to. You need a `profiler` such as `XHProf` or `Xdebug`. – Andrew Mackrodt Feb 16 '14 at 23:08
  • Ok, thanks to have brought me to the point where I give up. :) – Alain1405 Feb 16 '14 at 23:16
  • you need to call memory_get_peak_usage(1) only once, after php has created the HTML. –  Feb 16 '14 at 23:18

1 Answers1

3

you have to use something like Long polling, where you have a website that keeps the client waiting for a request and occasionally delivers some html as needed; or an implementation like socket.io for nodejs that allows you to perform actions like you're looking for natively.

Here's a SO question on longpolling with PHP: How do I implement basic "Long Polling"?

here's a question on how to use a socket.io like implementation with php: Using PHP with Socket.io

A final alternative is to have an ajax call on a timer that hits a webservice that pulls the value every few seconds giving a real-time like feel to the page even though it's a periodic refresh.

Say you're using jquery:

setTimeout(function(){
    $.ajax({
        dataType: "json",
        url: 'memoryUsage.php',
        success: function(data){
            $("#FirstName").val(data.memory)
        }
    });
}, 5000); //5 seconds

assuming your memoryUsage.php echos a value that looks like {memory:"some value"}

keep in mind all of these options are pretty memory and network traffic intensive.

Community
  • 1
  • 1
Snowburnt
  • 6,523
  • 7
  • 30
  • 43