Share
Today we are going to look at 3 ways to use sleep() in your PHP apps.
 ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌

ALEX WEB DEVELOP
Alex

3 Ways to Use the sleep() Function

sleep


Hey,
I'm Alex, from Alex Web Develop. I hope you had a nice weekend.

The sleep() function stops the PHP script execution for the specified number of seconds.
And today, we are going to look at 3 ways you can use this function in your apps.


1. Use sleep() to create PHP daemons.

PHP daemons are scripts that keep running indefinitely.
They are a smart alternative to CRON-fired scripts.
At regular intervals, daemons perform tasks such as database cleanup, sending email alerts, or analyzing data.

Daemons use the sleep() function to "wait" for the desired amount of time between iterations.
For example, the following daemon prints the time every 10 minutes:

$interval = 600;

while (true) {
  sleep($interval);
  echo "It's " . date('H:i:s') . " 'o clock.";
}


One of the cool things about sleep() is that, while the script is sleeping, no system resources are used.
Therefore, making the script sleep between iterations is much like executing it at regular intervals manually. Except, of course, that it is completely automatic.


2. Use sleep() for authentication and security.

One of the most effective strategies against login attacks is to limit how often login attempts can occur.
Put simply: if someone tries to log in a few times, then you force a wait timeout before another attempt can be made.

The exact implementation of this strategy is a bit too complex to be explained here.
However, you can implement a simplified version of this strategy (that still works fine in most cases) by using sleep().

This is the idea:
  • A remote user tries to log in.
    When this happens, your login script sets a database flag that means: "a login attempt is being made".
  • The script then checks the credentials and sleeps for X seconds before clearing the database flag.
  • If a new login attempt from the same user arrives, the script checks if the database flag is set. If it is, then it exits immediately.

Here's how the code looks like:

$user = $_POST['user'];
$pass = $_POST['password'];

if (flagExists($user)) {
  die();
}

setFlag($user);
logIn($user, $pass);
sleep(2);
clearFlag($user);


If you are interested in the complete and more secure implementation, you can find it in my PHP security course.


3. Use sleep() for remote connection attempts.

Finally, you can use sleep() when you need to access remote resources such as APIs and FTP servers.

Let's say that the remote resource is not responding, and you want to try again for a few times.
Instead of trying immediately, sleep() lets you wait for a timeout and increase the chances of the resource becoming available.
For example:

$conn = false;

while (!$conn) {
  $conn = connectToResource();
  if (!$conn) {
    sleep(10);
  }
}


What do you think?
Here are some links to read more about variable variables:

the cool bit

THE COOL BIT


If you need more precise sleep intervals, PHP offers two more sleep functions:
  • usleep() makes the script sleep for the given number of microseconds (1 second = 1 million microseconds).
  • with time_nanosleep() you can even specify the nanoseconds.
  • with time_sleep_until() you can sleep until the specified timestamp.

tip of the week

TIP OF THE WEEK


The null coalescing operator assigns a default value to variables in a concise and readable way.
For example, let's say that you want to count the occurrences of a database result value, and store the result in an array.
With the coalescing operator, you can initialize any unset element to 0 without any additional if blocks:

$itemsCount = [];

while ($row = mysqli_fetch_assoc($conn, $res)) {
  $item = $row['item'];
  $itemsCount[$item] = ($itemsCount[$item] ?? 0) + 1;
}
the challenge

WEEKLY CHALLENGE


Find the error.
This code snippet should filter out all commands except for "1", "2", and "3". However, a few different values are able to pass the filter. Can you figure out which ones and how to solve the problem?

$commands = ["1", "2", "3"];
$cmd = $_GET['cmd'] ?? "1";

if (in_array($cmd, $commands)) {
  echo 'Valid command: ' . $cmd;
}
else {
  echo 'Command not valid.';
}


Let me know if you can solve it or if you need a hint :-)

next steps

NEXT STEPS


Want to take your PHP skills to the next level?
Take a look at my professional PHP courses:


If you have any questions just reply to this email. I'm happy to help.


Before you go:
  • If you enjoyed this email, click here to share it with your friends.
  • Add my address (alex@alexwebdevelop.com) to your Contacts to make sure my next emails will reach you.
  • Send me a reply and let me know what you think. I read all the emails.

All the best,
Alex



Thanks to Freepik for the images used in this email.



You are receiving this newsletter because you subscribed to Alex Web Develop.

If you unsubscribe, you will not get any more emails from me.

Alessandro Castellano, P.IVA (VAT ID): 07012140484, via Luigi Morandi 32, 50141 Firenze FI, Italy

Email Marketing by ActiveCampaign