Add two fields to the user's table: number_login_attempts and last_failed_login_attempt.
If the script performs a check of the u/p and it fails, then perform the following steps:
Check to see when the last failed login attempt was. If it was over two hours ago, then this is not really a brute force attack so set the number_login_attempts=1 and set last_failed_login_attempt to the current time.
Else, if it was more recent than two hours ago, then see how many failed login attempts there have been. If the number is less than four, then this is not the 5th failed login attempt so simply update the users table with number_login_attempts + 1 and set the last_failed_login_attempt to the current time.
Else, if the number of attempts was at 4, then this is the fifth and you should (A) pick a random string and set that as the new password, and (😎 email that password to the email on file for the user.
That's the basic logic. The author provided you the code so you should be able to make those mods.
On a higher level, though, changing someone's password isn't really normal and sending it to them via email isn't really the most secure thing in the world. (Packets can be sniffed, and email accounts can be hacked, or the user could be on vacation and his co-workers could simply sit down at his machine and check his email). Besides, a pest could irritate the hell out of someone by deliberately guessing their password wrong 5 times and making them change their password if they don't want to.
A more normal (and more secure) speedbump would be to let them try 3 passwords immediately, make them wait 5 mins before they could try the 4th, and make them wait a half hour before they could try the 5th. (The logic for that is: if the counter==3, then this is the 4th attempt. If the last attempt was less than 5 mins ago, then don't even check to see if the pw is right or wrong, simply tell them that they didn't wait long enough.)
Once they wait 45 mins with no failed attempts, then the bad password attempt counter goes back to zero.