PHP and Header redirects – Issue with ampersands

Update 08-10-2012: Apparently WordPress formatted the &’s the wrong way, so my code didn’t make any sense. That’s fixed now.

For one of my websites I want to use a header redirect to external urls. I want to use a custom script because I don’t want to give those links a higher pagerank by backlinking to them.

So, normally you would have this script:

$url = 'http://www.somewebsite/index.php?options=with&more=parameters&and=stuff'; 
header('location: ' . $url);

For some reason, the url will be encoded, so all the ampersands will be replaced with &, ending with this url:

http://www.somewebsite/index.php?options=with&more=parameters&and=stuff

That will cause the link not to work.

The solution to this is very simple actually, just replace the &’s with real ampersands and you’re done!

$url = 'http://www.somewebsite/index.php?options=with&more=parameters&and=stuff';
header('location: ' . str_replace('&', '&', $url));
One Comment

Leave a Reply to Juan Manuel Doren Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.