0

I'd like a section of text that is already dynamically changing every 10 minutes to do it without refreshing the page. I was thinking something along the lines of:

<?php
   while (1 < 2) {
      echo $value;
      sleep(60);
   }
?>

I realize that's a dumb way to make a while loop run and I would think it would work with just "while(){}" but I just wanted to make sure, that will be corrected when I actually write this thing as long as this isn't terrible to do. If there is a better way I'd love to hear it! thanks!

Edit: I just noticed it would echo the value after the first, any cleaver ways to make it replace it?

Edit2 Here's the php function I already written to retrieve the changing value:

<?php
   function getTotal($basePrice){
      $dogeValue = file_get_contents("https://www.dogeapi.com/wow/?a=get_current_price");
      $postage = .49/$dogeValue;
      return round($sellAmount = $basePrice/$dogeValue - $postage - ($basePrice*0.1/$dogeValue));
   }
?>

2 Answers2

2

The short answer: yes, that is bad practice.

Reasons include:

  1. You tie up your server (will probably time out)
  2. Unless you play around with the buffering, things will not be reflected at the time you want
  3. You never send the close tag to the browser (or anything else that happens later).
  4. It is tricky to overwrite what was already there, so you end up with the output increasing instead of changing.

Recommendation:

Use client side code (javascript, AJAX) - don't try to do this server side.

You can see an example of periodic AJAX at https://stackoverflow.com/a/6378771/1967396 .

For periodic JavaScript, see many good answers at Is there any way to call a function periodically in JavaScript?

Community
  • 1
  • 1
Floris
  • 45,857
  • 6
  • 70
  • 122
0

This script will never show you anything, because until processing the php script is not done, web server doesn't send anything to output, considering your infinite loop, it will never happen.

instead of this not-working idea, use Ajax, cron jobs, or even pure javascript, its very simple and more rational certainly.

Alireza Fallah
  • 4,609
  • 3
  • 31
  • 57
  • 1
    Not entirely true. Some web server will output "on the go" it depand if there is some cache or not – Nicolas Racine Jan 30 '14 at 23:59
  • I'm talking about usual web servers like apache or NginX – Alireza Fallah Jan 31 '14 at 00:01
  • Well using apache i was able to output on the go i used that method in the pass as cron job was not an option and the page had to be able to load fast so The part that was taking time to run was after all output of html – Nicolas Racine Jan 31 '14 at 00:10