Sanitizing URL in a WordPress plugin

Good on you for trying to do this properly – but… how about this?

global $wp;
echo esc_url( home_url( $wp->request ) );

EDIT:
Versions of your above code have been written all over the internet – see this SO question with 000s of votes. rather UN-intuitively it’s not a super simple thing to do as the client can set some of these themselves, so you’re right to want to sanitize.

Sanitization is just the removal of anything you’re not expecting in your string… You’re expecting a URL – so only allow valid URL characters through. If you don’t need to echo out query strings – well then you could also remove everything that’s not in your page names or site structure. The point is – you decide – there isn’t a function that just does sanitize_this() your job is to work out exactly what the limit is for allowing data through. Maybe one of these work? Look at what is permitted through and decide what’s right in that use case.

Generally you should only need to sanitize once and escape once to avoid over complication and if you’re encoding you don’t want to double encode – you could actually be making your code less secure as other functions could be looking for strings such as '<script>' in “decoded” strings and only seeing %3Cscript%3E meanwhile your JavaScript decodes and outputs later on. You see what I mean?

My point above about using wp is that it’s already there for you. Re-writing these functions is asking for mistakes, security implications and odd error conditions and dealing with common PHP issues using your own custom functions is naive at best and arrogant at worse – professionals have already done this for you – why do you want to do it again?

Regarding the critical issue you mention – sanitize_url( $_SERVER['REQUEST_URI'] ); is valid markup – sanitize_url() is a WordPress function and will need WordPress to have been loaded to work. Check your logs for the exact cause.