11

So I am trying to encode/decode a url that when decoded will return the encoded + symbols from teh url. For example, I encodewebsite.com/index.php?eq=1+12 which when encoded turns the + into %2B, as it should. When I retrieve the value from $_REQUEST['eq'] and use urldecode() it echo's as "1 12". I cannot seem to get the decode to bring back the + so to speak. Am I doing something wrong here, or is there a more efficient/better way to go about doing this? Here is the exact encode/decode lines I use.

Submit Page

<?php
$eq = "1+12";
$send = '<a href="website.com/index.php?eq='.urlencode($eq).'</a>';
echo $send;

Retrieval page

<?php
$eq = urldecode($_REQUEST['eq']);
echo $eq;
?>
S L
  • 14,262
  • 17
  • 77
  • 116
Ed R
  • 2,129
  • 6
  • 24
  • 32

3 Answers3

20

Don't run urldecode, the data in $_REQUEST is automatically decoded for you.

A plus sign, in a URL, is an encoded space. PHP decodes the hex value to a + automatically. Then, by running the result through urldecode, you are manually (and incorrectly) decoding the + to a .

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • so I removed the urldecode, and kept the urlencode. It still is registering the $_REQUEST as a space. – Ed R Mar 31 '11 at 06:19
  • It doesn't when I copy/paste that code and remove the `urldecode` statement. – Quentin Mar 31 '11 at 06:21
  • I'm not sure, maybe the php version is different and functions differently? Or could be other parts of my page conflicting. I figured a workaround by using str_replace(" ", "+", $eq). Probably not ideal, but since my URL will never need spaces, seems to work. Thank you for your help. – Ed R Mar 31 '11 at 06:25
  • It probably is some other part of your code. You should trace through and find out what modifies it and where (starting with checking that the URL in the link is actually containing `eq=1%2B12`. – Quentin Mar 31 '11 at 06:27
  • @Andrew — That is what the line "urldecode($_REQUEST['eq'])" in the question does. It is the problem. – Quentin Mar 04 '18 at 16:53
15

Try using the function rawurldecode() instead of urldecode()

Mats Rietdijk
  • 2,576
  • 3
  • 20
  • 25
Maurice
  • 159
  • 1
  • 2
2

I encode it in JavaScript with encodeURIComponent() and decode it in PHP with rawurldecode() and it encodes/decodes properly for me, including the "+", but NOT with urldecode()

adrianTNT
  • 3,671
  • 5
  • 29
  • 35