Your code is good for monitoring users activity on the server but to be honest, It can't help preventing DDOS attacks since the aim of DDOS attacks is to send tons of requests to the server to make it too busy to respond to its intended users.
your code seems to be doing lots of checking to determine if the number of requests has reached beyond your standards, and this means that not only the attacker has reached his goal keeping your server busy but also you are helping him with lots of processing which is done by your code.
Imagine that each time there is a request, your code has to search through database and retrieve information and then compare them and do lots of other stuff.
there is nothing you could do in PHP to stop this kind of attacks.and also if the attacker uses UDP attack, your code will do nothing since the Apache listens to TCP port.The only thing that can protect your website from DDOS attacks is your Hosting company. the company needs to have needed equipments like:
- Firewalls
- rate-limiting Switches
- appropriate Routers
- Application front end hardware
- IPS based prevention
- DDS based defense
- Blackholing and sinkholing
- Clean pipes
but if you need a secure login system you could use a captcha, even the one you created yourself. simply generate a random 5 digit number and create an image in PHP with the number printed in it and show the picture on the form and when the user submits the form, check if the number you generated matches with the one user entered. and also you can use PHP/JavaScript AES libraries to encrypt user inputs on the client side and decrypt them on the server.