3

I want to pass '&' operator in query string. I tried to use urlencode and urldecode but its not working. I am doing this:

$abc="A & B";
$abc2=urlencode($abc);

Then I am passing the value like this

<a href="hello.php?say=<?php echo $abc2 ?>"><?php echo $abc;?></a>

and getting value on next page as

$abc=$_GET['say'];
$abcd=urldecode($abc');
echo $abcd;

but the output is not A & B

What am I doing wrong?

Robert Groves
  • 7,574
  • 6
  • 38
  • 50
Manoj Kumar
  • 646
  • 1
  • 12
  • 24
  • 1
    Did you try echo `$_GET['say']` **without** `urldecode()`? You can always use `http_buil_query()`, which would be a nice, clean approach. – Mārtiņš Briedis Apr 19 '12 at 06:27

4 Answers4

2

Try this:

$url = '?' . http_build_query(array(
  'say' => 'A & B'
));

// Then just:
echo $_GET['say'];

Live example: http://codepad.viper-7.com/ibH79a?say=A+%26+B

Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
2

Basically it should work I tried the following on my webserver:

$a = 'A & B';
echo urlencode($a);
echo '<br />';
echo urldecode(urlencode($a));

Output

A+%26+B
A & B

I guess you have another logically or syntax error which causes your & not to be decoded correctly, in your code there's an apostroph in your urldecode()-syntax.

Is that all of your code or are you using a "similiar" one? your original code would be useful then.

peipst9lker
  • 605
  • 1
  • 5
  • 17
0

It seems you have added a single quote next to $abc on line 2 in the below code:

$abc = $_GET['say'];
$abcd = urldecode($abc);
echo $abcd;
Rory Hunter
  • 3,425
  • 1
  • 14
  • 16
Mahavir Munot
  • 1,464
  • 2
  • 22
  • 47
-1

& is a special HTML characters, you need to convert it to &amp;.

Try this:

$abc = "A & B";
<a href="hello.php?say=<?php echo htmlentities($abc); ?>"><?php echo $abc; ?></a>
Muhammad Alvin
  • 1,190
  • 9
  • 9
  • ` ` is a non-breaking space. `&` is an ampersand encoded as an HTML entity. In this case, however, `urlencode()` should be used, not `htmlentities()`. – RickN Apr 19 '12 at 07:04
  • ah, sorry. @RikkusRukkus is correct. What i mean is & :-) – Muhammad Alvin Apr 19 '12 at 07:10
  • You're right again. & is converted to %NN by urlencode(), so no need to use htmlentities(). But, it *should* be used in (become: , because & will generate warning by HTML validator. It should be & – Muhammad Alvin Apr 19 '12 at 07:16