user2492064
user2492064

Reputation: 591

Treating & as normal character with $_GET

I have an application that posts content to a MySQL DB via PHP. The PHP uses $_GET to pull the content from the URL and then inserts it into the DB.

This works great, but I have discovered an issue. If the user enters certain characters (", &, and others), the $_GET method does not properly separate the content from the URL.

Let's say the user posts this content: I love blue & green

In this situation, the & symbol cuts the string after the word blue.

Is there any way for me to edit my PHP file to ignore the & symbol and to actually treat it as part of the variable it is supposed to $_GET? Any help would be great!

Upvotes: 2

Views: 158

Answers (7)

Mario Dian
Mario Dian

Reputation: 166

You have to URL encode the string before you pass it as a GET parameter. In this particular case you have to replace & symbol with %26.

This can be done for example using javascript right before you send the form.

Upvotes: 0

m1k1o
m1k1o

Reputation: 2364

What about, before creating Query string, encode it ?

$str = "I love blue & green ?=&˙Đ[]";
$str = urlencode($str);
echo $str;

Will return:

I%20love%20blue%20%26%20green%20%3F%3D%26%CB%99%C4%90%5B%5D

Upvotes: 1

Someoneinthe
Someoneinthe

Reputation: 372

try to urlencode your string:

&

becomes

%26

it's a PHP function : http://php.net/manual/fr/function.urlencode.php

Upvotes: 1

Alexandre Brach
Alexandre Brach

Reputation: 325

The correct method is to urlencode the "&" caracter by the client : pass "%26" instead of "&"

Upvotes: 2

netvision73
netvision73

Reputation: 4921

You can URLencode data before sending it to the PHP. It's a better solution.
Specials chars must not be used in a query string if those chars are in data.

In Javascript, you can use the escape function : escape(&ee) will give %26ee

Upvotes: 5

subZero
subZero

Reputation: 5176

You could send the request as a base64 encoded string:

$string = base64_encode("This is my long string with &ampersands and 'quotes'");
print base64_decode($string);

Note that base64-encoded data takes about 33% more space than the original data.

From the manual: http://php.net/manual/en/function.base64-encode.php

You also have urlencode

Upvotes: 1

exussum
exussum

Reputation: 18550

you can use $_SERVER['QUERY_STRING']

from http://php.net/manual/en/reserved.variables.server.php

Upvotes: 1

Related Questions