1

i want to get #var value from url like my url is mydomain.com/index.php#1 so i want to get has(#) value from url which is 1 after some research i got this article http://www.stoimen.com/blog/2009/04/15/read-the-anchor-part-of-the-url-with-php/

i use this code for get has(#) value, this is work fine in JavaScript but this is not work in php my code is :

<script language="javascript">
var query = location.href.split('#');
document.cookies = 'anchor=' + query[1];
alert(query[1]);
</script>
<?php
echo $_COOKIE['anchor'];
?>

this code give me alert value in JavaScript but not echo value. any solution for that ?

Tarun Baraiya
  • 506
  • 1
  • 9
  • 30
  • possible duplicate of [Can PHP read the hash portion of the URL?](http://stackoverflow.com/questions/940905/can-php-read-the-hash-portion-of-the-url) – Manse May 25 '12 at 07:36
  • @ManseUK: Not a dupe (of that, at least). Did you click on the link supplied? – Jon May 25 '12 at 07:37
  • @Jon sorry - i clicked the wrong duplicate link .... cannot undo a vote to close !!! Suppose i could delete the comment – Manse May 25 '12 at 08:24

5 Answers5

1

The cookie you are setting will not be visible to PHP until the next page request. The article you link to states this explicitly:

Of course, yes. This is not working correctly. In fact it’s working correctly from the second load on, but on the initial load of the page the $_COOKIE array does not has any anchor key inside. That’s because this part of the code is executed before the browser setup the cookie on the client.

There is a "workaround" presented in that article, but frankly: this sort of thing is rubbish and you should simply not put this information (only) in the query fragment if you want PHP to read it.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

By article which you sent, you must do a redirect like:

<?php if (!$_COOKIE['anchor']){ ?>
<script language="javascript">
  var query = location.href.split('#');
  document.cookie = 'anchor=' + query[1];
  window.location.reload();
</script>
<?php } ?>

<?php
echo $_COOKIE['anchor'];
?>
Anton
  • 1,029
  • 7
  • 19
1

Additionally, you seem to set wrong property in JS (it's .cookie, not .cookies):

document.cookie = 'anchor' + query[1];
bjauy
  • 929
  • 16
  • 22
0

You are setting a cookie that wont be passed to php until next reload. Am I wrong?

Client dynamics is the end of the chain.

tim
  • 2,530
  • 3
  • 26
  • 45
0

Use this method to prevent errors:

<script> 
query=location.hash;
document.cookie= 'anchor'+query;
</script>

And of course in PHP, explode that puppy and get one of the values

$split = explode('/', $_COOKIE['anchor']);
print_r($split[1]); //to test it, use print_r. this line will print the value after the anchortag
Aurora
  • 725
  • 1
  • 8
  • 17