How to get everything after a domain name in a string

My goal is to get everything after the domain name into a string. As in mysite.com/page/page2, you will get the string "page / page2". I can do this, but it starts to give me problems when, for example, the site is in a subfolder, and not in the root directory, then the folder in which the site is located will also be included in the line, and if I do not use mod_rewrite to get pretty links, it will also add index.php to the string.

So, I will need a trick or two to understand the script whether the site is in a subfolder such as mysite.com/sitefolder/page/page2, and that it will still result in a line

page/page2 

If the site does not use mod_rewrite and the url is mysite.com/sitefolder/index.php/page/page2, it will still result in a string

 page/page2 

Keep in mind that I have the URL and USE_MOD_REWRITE defined in the configuration file, so there is no need for magic. I just don't know how to do this. I know I can do $ _SERVER ['REQUEST_URI'] to get the string, but then index.php will still be in it. I apologize if I do not explain well enough, but all help is appreciated.

+4
source share
2 answers
  • get the path by analyzing uri request
  • remove the final script name from the end of the line (e.g. index.php)
  • rtrim any trailing slashes

      $ request = parse_url ($ _ SERVER ['REQUEST_URI']);
     $ path = $ request ["path"];
     $ result = rtrim (str_replace (basename ($ _ SERVER ['SCRIPT_NAME']), '', $ path), '/');
    

EDIT

 $request = parse_url($_SERVER['REQUEST_URI']); $path = $request["path"]; $result = trim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/'); $result = explode('/', $result); $max_level = 2; while ($max_level < count($result)) { unset($result[0]); } $result = '/'.implode('/', $result); 
+11
source

You can use $_SERVER['REQUEST_URI'] and then change the string using the PHP substr() function. So, put the URI in a variable and then run this function to remove the first number of X characters (length of the domain name) from the beginning and the number of X characters from the end (index.php = 9).

For instance:

$new_url = substr($uri_variable, 10, -9);

Where $uri_variable is $_SERVER[ REQUEST_URI ']', 10 is the character after the domain name, and -9 are the characters in index.php.

https://www.php.net/manual/en/reserved.variables.server.php http://php.net/manual/en/function.substr.php

+2
source

Source: https://habr.com/ru/post/1389866/


All Articles