I am new to the world of coding and PHP hence would like to learn what\'s the best way to sanitize form data to avoid malformed pages, code injections and the like. Is the s
Your example script isn't great - the so called sanitisation of a string just trims whitespace off each end. Relying on that would get you in a lot of trouble fast.
There isn't a one size fits all solution. You need to apply the right sanitisation for your application, which will completely depend on what input you need and where it's being used. And you should sanitise at multiple levels in any case - most likely when you receive data, when you store it and possibly when you render it.
Worth reading, possible dupes:
What's the best method for sanitizing user input with PHP?
Clean & Safe string in PHP