How to make Canonicals with PHP

I’ve search around on SO, but can’t find an exact answer to my needs. Generating a URL is pretty easy… Like so: