Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do to pass '&' symbol inside value in URL?

Tags:

url

php

encoding

I was passing the query to my search results page with variable: ?s=.

I was testing the site and I discovered than when the query has a & symbol in it, when I try to retrieve $_GET['s'] it gets cut in the & symbol.

I tried with & and also converting it to %26 and I'm still having the same problem.

How can I encode them to pass them in URL?

EDIT:

I pointed that I tried encoding it to %26 and it still didn't work.

I tried with urlencode() and on ?s=pizza%26pasta when I print_r($_GET) I get:

Array ( [s] => pizza [pasta] => )

EDIT 2:

I just found out that the problem actually has to do with .htaccess it seems to transform the '&something' in '&something='. No idea how to fix it in htaccess.

This is my .htaccess file:

RewriteEngine On
RewriteBase /

# remove www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]

# rewrite to action
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^([^/]+)/?$ /a/?s=$1 [L,QSA]
like image 410
lisovaccaro Avatar asked Aug 02 '12 06:08

lisovaccaro


2 Answers

Url encoding the amersand (&) to %26 is the correct way to do this.

Using http://yoursite.com?var1=this%26that&var2=other will result in your $_GET superglobal array having two variables

$_GET['var1'] = 'this&that';
$_GET['var2'] = 'other';

You can use the function urlencode to automatically encode all characters that require encoding. These are typically the characters that are used to make up the component parts of a url. i.e. the At symbol (@), colon (:), question mark (?), etc.

var_dump(urlencode('one&two'));

string(9) "one%26two"
like image 81
Leigh Avatar answered Nov 11 '22 03:11

Leigh


Use these steps:

  1. First build your string in PHP
  2. Then use the function urlencode() to correctly encode your string.
  3. When using $_GET[] make sure you use urldecode() to get the variable to its original format.

Hope this helps :)

like image 23
itsols Avatar answered Nov 11 '22 05:11

itsols