0

I am trying to post # parameter in query string like...

www.demo.php?tag=c#

Now i am trying to get tag value in another page with

$_GET['tag']

But i am not getting somehow # value is not coming with $_GET. I can get only "c".

Hardik
  • 1,283
  • 14
  • 34

1 Answers1

1

The hash character (#) has a special meaning in URLs. It introduces a fragment identifier. A fragment identifier is usually used to locate a certain position inside the page.

A fragment identifier is handled by the browser, it is removed from the URL when the browser makes the HTTP request to the server.

Being a special character, if you want it to have its literal value you must encode it. The correct way to write the URL in your question is:

www.demo.php?tag=c%23

When it's written this way, $_GET['tag'] contains the correct value ('c#').

If you generate such URLs from PHP code (probably by getting the values of tag from an external resource like a database) you have to use the PHP function urlencode() to properly encode the values you put in URLs. Or, even better, create an array with all the URL arguments and their values then pass it to http_build_query() to generate the URL:

$params = array(
   'tag'  => 'c#',
   'page' => 2,
);
$url = 'http://localhost/demo.php?'.http_build_query($params);
axiac
  • 68,258
  • 9
  • 99
  • 134
  • Already tried this. its not working... – Hardik Mar 16 '16 at 17:30
  • Try harder. It works. – axiac Mar 16 '16 at 17:38
  • Actually i have changed my url with htaccess for clean url. like http://localhost/demo/tag/c#/ – Hardik Mar 16 '16 at 17:51
  • 1
    Maybe I didn't explain it very well. You **cannot** put `#` unencoded in an URL, if you want it to be `#` and not something else. The same for `?`, `%`, `/`, `&`, `=` and several other characters. It doesn't matter if you use URL rewriting or not. I clicked on the link you put in your comment. The server replied with *"The requested URL `/demo/tag/c` was not found on this server."*. See? No `#` reaches the server if it is not [URL-encoded](https://en.wikipedia.org/wiki/Percent-encoding). Still not convinced? Search for [tag:c#] on StackOverflow and check the (nice and clean) URL you get. – axiac Mar 16 '16 at 18:05
  • Axiac, i have not issue to use url like www.demo.com/tag/c%23/ but when i am trying to get this value of tag on another page using $_GET['tag'], i can only see 'c' not 'c#' or 'c%23' – Hardik Mar 16 '16 at 18:11
  • Maybe your rewriting rules are the cause. `print_r($_SERVER);` could help you debug the issue – axiac Mar 16 '16 at 18:20