I would like prevent anyone trying to access my website thro\' code. Code in the sense, any program that is like bot, which would cause traffic surge.
For instance,
Short answer is you can't. However, you can make some checks like user agent (but again, this is easily changed/spoofed).
But let's say you want to get the majority, check that the User Agent is acceptable, check the device for mobile devices accessing you page.
Another method I know that people have done is track the number of requests a source is making and having a threshold of request / time to test if the connection is "legit". I haven't done this myself, so I can't speak to it's reliability.
If you want to distinguish between robots, tools like ( ReCaptcha) will help.