There is a site where you need to display

<link rel='canonical' href='http://site.ru/?cat=id'>

But the URL of the pages can be of 2 types:

 http://site.ru/?cat=id&paged=id http://site.ru/?paged=id&cat=id 

id is a variable. Wrote just such a thing, but how it should still not work:

 if (stripos(parse_url($_SERVER["REQUEST_URI"]),'cat') !== false) { if ( ((stripos(current(split('&',parse_url($_SERVER["REQUEST_URI"])['query'],'paged'))) != false)) & ((stripos(next(split('&',parse_url($_SERVER["REQUEST_URI"])['query'],'cat'))) != false)) ) { echo '<link rel="canonical" href="https://'.$_SERVER["HTTP_HOST"].'/?'.next(split('&',parse_url($_SERVER["REQUEST_URI"])['query'])).'" />'; } else { echo '<link rel="canonical" href="https://'.$_SERVER["HTTP_HOST"].'/?'.current(split('&',parse_url($_SERVER["REQUEST_URI"])['query'])).'" />'; } } 

Where is my mistake? Perhaps there is a way to make it easier? It would not be desirable to invent a redirect in Apache c paged=id&cat=id on cat=id&paged=id . PHP5

  • I didn’t understand something about the redirect, why are you in the redirect offering link 2 to replace link 1? how do you determine the order of the elements, if it will always be the one after that. - teran
  • one
    and why do you call parse_url 5 times, do you like to write very long and incomprehensible code? - teran
  • one
    you generally seem to just need to output <link href="http://site.ru/?cat={$_GET['cat']}"> what? - teran
  • And why do you need a certain sequence? Does this somehow affect the routing? - Ninazu
  • @teran You correctly described everything and the criticism is very true. Thanks a lot for your help!! - theblackpost

2 answers 2

Parameter values ​​can be taken from the $ _GET array, and their order can be determined using the stripos function, into which you can transfer the entire query string. This function not only determines whether the substring is in a string, but also returns its position stripos

     <?php if (stripos(parse_url($_SERVER["REQUEST_URI"]),'cat') !== false) { echo '<link rel="canonical" href="https://site.com/?cat='.$_GET['cat'].'">'; } ?> 

    thanks, @teran!

    Of course, you can and without parse_url

    • you need, but you can not if(isset($_GET['cat'])).... your code will skip the link ?blablacat=1 , and there’s no point in manually parsing the URL - teran