15

I have the following URL: $url = 'http://mysite.com/?p=welcome&x=1&y=2';

I need to decode it so that header("Location: $url"); actually works.

However, using urldecode($url) is not working because it's not decoding the & -> & and so the browser is getting redirected to http://mysite.com/?p=welcome&x=1&y=2 which fails.

I need it to decode so that it looks like: http://mysite.com/?p=welcome&x=1&y=2

How do I do that?

ProgrammerGirl
  • 3,157
  • 7
  • 45
  • 82

4 Answers4

33

Try with htmlspecialchars_decode

echo htmlspecialchars_decode('http://mysite.com/?p=welcome&x=1&y=2');
//"http://mysite.com/?p=welcome&x=1&y=2"
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • 2
    What the difference between `htmlspecialchars_decode` you are recommending and the `html_entity_decode` everyone else is recommending? Which one should I use? – ProgrammerGirl Jul 30 '12 at 14:45
  • 1
    @Programmer `html_entity_decode` is for heavy weight entity decoding, such as turning `←` into `←`. `htmlspecialchars_decode` is only for unescaping escaped html, it decodes only the characters necessary to escape html. `htmlspecialchars_decode` is semantically more correct one to use here imo. – Esailija Jul 30 '12 at 14:47
  • Perfect fix. Had an odd header("location:") issue where sometimes I was seeing & being turned into & ... used $ref = htmlspecialchars_decode($ref); to clean the variable and FIXED. thank you! – CA3LE May 07 '19 at 06:20
6

& isn't URL encoded (aka percent-encoding), but is an HTML entity. URL-encoded it would look like %26.

Use html_entity_decode().

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
5

& isn't url-encoded. You need use htmlspecialchars_decode() http://php.net/manual/en/function.htmlspecialchars-decode.php

Matt
  • 6,993
  • 4
  • 29
  • 50
4

I'd try this:

$url = html_entity_decode($url);
header("Location: $url");

taken from http://php.net/manual/en/function.html-entity-decode.php

I'd do so 'cause your $url is not url-encoded but html-encoded, with html special characters replaced with the corresponding html entity.

Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81