0

This is a simplified PHP version of my question:

I want to load http://localhost/test2.php in browser, and if it's missing #test_test, reload immediately with it http://localhost/test2.php#test_test .

  <?php

  // causes ERR_TOO_MANY_REDIRECTS
  if (strpos(strtolower($_SERVER['REQUEST_URI']), 'test_test') === false) {
      header("Location: /test2.php#test_test");
  }

  ?>     

In short, I want to check for an anchor in an URI, if it's missing, reload the page with it. I am getting ERR_TOO_MANY_REDIRECTS. Any suggestions on how to tackle this?

Mike Q
  • 6,716
  • 5
  • 55
  • 62
  • 2
    Possible duplicate of [How to obtain anchor part of URL after # in php](http://stackoverflow.com/questions/1032242/how-to-obtain-anchor-part-of-url-after-in-php) – chris85 Jan 14 '17 at 21:07
  • use `window.location.href` to get full url of current page and then match it (for example, by searching substring in it ) – Panama Prophet Jan 14 '17 at 21:08
  • The answer to the `ERR_TOO_MANY_REDIRECTS` is the linked thread. You never have `test_test` so you loop.. (also you should `exit` after a `header`) – chris85 Jan 14 '17 at 21:09
  • @chris85 , Not the same, the user in the question you posted is looking to extract $_GET data, I am looking to change the URI. – Mike Q Jan 14 '17 at 21:12
  • You are looking to obtain the `#test_test` server side, no? – chris85 Jan 14 '17 at 21:13
  • @chris85 yeah but I could do it on the client side, basically I want to see if the URI is X and turn it into Y. – Mike Q Jan 14 '17 at 21:14
  • 1
    @MikeQ You can't do it server side with the `#`. You'll need to do it client side with JS...or make it a `GET`.. – chris85 Jan 14 '17 at 21:17
  • @chris85 I did have the exit in there , and a die, it doesn't help lol so I left it out of this example to simplify things... I also tried setting the REQUEST_URI to something but it didn't help either. – Mike Q Jan 14 '17 at 21:17
  • @chris85 , ok It correctly changes the URI, just doesn't stop trying lol.. – Mike Q Jan 14 '17 at 21:18
  • Yes, see second comment. You're in an endless loop. The server gets `/test2.php` then sends it to `/test2.php#test_test` then gets `/test2.php` again and does it again.. (`exit` was just a note for `header` usage, not a solution) – chris85 Jan 14 '17 at 21:19

1 Answers1

1

You can do it using js this way:

let currentUrl = window.location.href;

if (currentUrl.indexOf('#test_test') === -1)  {
    window.location.href = currentUrl.replace(/(#.+)/gi, '#_test_test');
}
Panama Prophet
  • 1,027
  • 6
  • 6