I have a script that does an update function live. I would move it to a cron job, but due to some limitations I’d much rather have it live and called when the page loads.
The issue is that when there is a lot of traffic, it doesn’t quite work, because it’s using some random and weighted numbers, so if it’s hit a bunch of times, the results aren’t what we want.
So, question is. Is there a way to tell how many times a particular script is being accessed? And limit it to only once at a time?
Thank you!
You could do something like this (requires PHP 5):
file_put_contents() overwrites the file (as opposed to appending) by default, so the contents of the file should only ever be “locked” or nothing. You’ll want to specify the LOCK_EX flag to ensure that the file isn’t currently open by another instance of the script when you’re trying to write to it.
Obviously, as @Pekka mentioned in his answer, this can cause problems if a fatal error occurs (or PHP crashes, or the server crashes, etc, etc) in between placing the lock and removing it, as the file will simply remain locked.