The trick to security in PHP is FIEO, Filter Input, Escape Output.
It is your job to filter this output, and make sure you don't accept any illogical or otherwise invalid value, strip tags, etc, etc.
And do not ever write anything to any data source (like a database) you haven't checked at all.
Escape Output: Here you assume that everything you did in the "Filter input" step didn't work (although hopefully it did!) and you have to prevent from propagating your problem on to the users. For example, you don't want that XSS attack to someone entered into a textfield to actually work, so you run the contents through htmlentities() which makes sure tags don't render as tags but will be output as plain text on the screen rendering the XSS attack useless.
As you can see the main trick is to be creative and think about everything that can go wrong, assume it will, and then prevent it