1

Suppose a website with 'high' traffic, I want to use the php sleep(4) function to avoid flooding. Is it a good idea or should I use different delay ways ? sleep() keeps a connection open, could this be a problem ?

I do:

index.php -> stuff.php -> index.php

Stuff.php does something and then sleep(4); so the user waits 4 seconds with a blank screen, and then goes back to index. Thanks.

Update: My enemies are both, hackers, that wants a DOS, and stressed pepole that click fast on the search button, lets say... Thats why I would use a server-side delay.

3
  • 2
    why not update to a server that can handle 'high' traffic? slowing down everything doesn't seem to be a good idea... Commented Jun 6, 2016 at 2:07
  • Imagine some shop queue. Is it good idea to ask people in that queue to wait several minutes before they join to this queue? Good idea is to add additional checkout or reduce time for each client serving some ways. If you want avoid flooding - you should recognize it and limit(some module, that limits rps by ip, for example) Commented Jun 6, 2016 at 5:38
  • (Thanks Will and Amaksr... for your opposite answers) Commented Jun 6, 2016 at 23:43

2 Answers 2

7

It is not good approach because even doing 'sleep' apache/php still occupies OS process for that connection. So, on website with high traffic you will get lots of simultaneously running Apache processes that will eat all your server's RAM.

Instead, You can modify one of your pages and put some Javascript code to it, so it could wait for few seconds, and then navigate to the next page by javascript. That should solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't really avoid keeping the connection open, otherwise there's no waiting that could happen. You'd have to either do it client side or server side. However, if you run PHP via nginx and php-fpm, you should be able to get much better performance out of it than, say, Apache 2 and mod_php with the Worker MPM.

However, sleep() itself is fairly efficient, so you shouldn't have to worry about it eating CPU or anything. See here for more information on how it's implemented in the lower layers.

In general, the best way to "wait efficiently" is to be using as much of an asynchronous stack as possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.