Is there a way for me to have a PHP script run constantly on the server, rather than only run when a user loads the page?

Sorry if this is a stupid question. I just haven't ever had the need until now.

Recommended Answers

All 7 Replies

It can be done using AJAX if you don't want the page to reload.

It can be done using AJAX if you don't want the page to reload.

I mean something that is never in a URL and never echo's anything, that would constantly update something in my MySQL database. Is there no way in PHP, or do I have to learn another language?

There is no way in PHP, but like I said AJAX would do exactly what you are describing and with a framework like Prototype.js it is surprisingly easy and can be accomplished with an additional 3 or 4 lines of code.

Thanks for your help. I'll check it out.

I tool a look at it. But I have a question about security, since it runs in my client's browser, can't they see my code? I was looking for something that would run on my server, not my client's browser.

Here is a quick example using Prototype:

function someFunction()
{
	new Ajax.PeriodicalUpdater('div_id', 'your_function_page.php', {
  method: 'post', frequency: 2, decay: 1
});
}

Using body onload or window.onload in your js will start the script running when the page loads. The script will execute every 2 seconds (if the decay is set to 1). The script is the only thing viewable to your users if they decide to look.

if you want something to just run on the server side you can look into cron jobs as well. You can set it up to run at certain times/dates. I don't use it much myself but it's worth looking into either way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.