PHP sleep()是否为多个用户加起来?

Does the sleep() function add up for all the user using example.php through an ajax request?

If i put sleep(2) in example.php; do all user get afftected/add up sleep()?

I basicly want to limit requests for example.php, without using unsecure javascript, instead inside the php. Thanks

No. The sleep(2) will only affect the single user. However, if you want to do rate limiting, this is still not a great way to go about it.

A malicious user could theoretically open up 1,000 simultaneous requests to example.php and in 2 seconds, have it executed 1,000 times. If requests are overlapped, this could theoretically be executed as many times per second as the attacker wants (up to the capacity of the server of course).

As an alternative, you may want to look at something like the generic cell rate algorithm. The general idea with rate limiting is to throw away requests which go over the limit as efficiently as possible.

Putting sleep() inside a PHP file will affect every load of that PHP file, so yes, all users that go to load example.php, regardless of how they do it, will have the page delayed by 2 seconds.

However, this does not limit requests for example.php, it only puts a pause in its execution and return to the user.

You can not limit HTTP requests to a php file on your server from inside the PHP in the meaning that it's already really late in the request to actually limit something.

Check with your HTTP server or the load-balancer in front of it, how you can limit requests. Tools exist for such and they normally do a good job. Most often a much better job than you would be able to implement (most certainly with much complexity) from inside PHP.

In any case, sleep sounds like a totally wrong function to limit requests.

I hope this is helpful and answers your question somewhat.

No, it does not limit the rate of requests that are executed by example.php. It only delays its execution for seconds.

Rather, you should be setting a server-side variable (preferably on a database), to store the time of the last execution, then filter it as you need by comparing it with the current time. (even adding specialized sleep(n) to throttle).

Use mutexes (flock) to achieve a certain level of resource access regulation. Use with caution as it can become your sites bottleneck if it's heavy trafficked.