r/PHPhelp • • May 13 '20

Can I write PHP that gets executed on the server automatically?

Hi,

for instance let's I wanna check regularly if there are customers in my database who have open invoices. How can I write a script that automatically gets executed without needing a user to request a php file from the server? Is that even possibly with PHP? If not how would you approach this otherwise?

7 Upvotes

12 comments sorted by

6

u/sitrate May 13 '20

You can run the script via the command line:

php my_script.php

You can do this with a script via Windows Scheduler or cron on Linux.

4

u/wh33t May 13 '20

Like other users have said you can execute a php script via the command line or you can make this happen at regular intervals via cron job (linux) or scheduled task (windows), I think OSX might also use cron but I'm not sure, either way I'm positive there is a way to regularly execute a script on OSX.

You can also launch the script and have it run indefinitely until closed, using sleep() or usleep() you can control how many times per second you want the script to run.

Any time you run a php script from the command line or cron it executes under the php-cli environment which has a separate configuration than php that would be used under Apache/nginx etc.

3

u/CyberJack77 May 13 '20

If your site is running on a Linux server, you can use cron jobs for this.

3

u/stfcfanhazz May 13 '20

crontab -e

4

u/greatdeveloper0 May 13 '20

And this site for the time format of the cron https://crontab.guru

3

u/smo0f May 13 '20

Yes.

Your first goal is to write a PHP script that can run successfully and do everything you want it to do by running it from the server's command prompt:

php /path/to/script.php

Once that's done, you now want to schedule when you want to run that script. Linux/MacOS you can use cron jobs, and on Windows you can use Task Scheduler.

2

u/[deleted] May 13 '20

The first thing you should do is read the thread, see that nine people have already replied that you should use cron.

Then you should reply that you should use cron

2

u/TheBadStick May 13 '20

Or, if that doesn’t work, take a look at cron.

1

u/[deleted] May 13 '20

Cron jobs or you can run a php script with a while loop that does a sleep 60 or something to run every minute

-4

u/SomeOtherGuySits May 13 '20

No you can’t. Not possible

0

u/[deleted] May 13 '20

[deleted]

2

u/AdmiralAdama99 May 13 '20

u/Yakuwari Just to add to this. If you're on shared hosting, look for cron / scheduled tasks in your control panel (cpanel, etc)

If they dont have this for some reason, a backup option would be to write code on a busy page that checks when the last time the job was run, then if it hasnt been run in awhile, it runs it.

1

u/PetahNZ May 13 '20

Or change host