Skip to content

Instantly share code, notes, and snippets.

@relliv
Last active June 18, 2018 20:58
Show Gist options
  • Save relliv/64ca5d708ffb64f2fce74c78e7e7067b to your computer and use it in GitHub Desktop.
Save relliv/64ca5d708ffb64f2fce74c78e7e7067b to your computer and use it in GitHub Desktop.
PHP URL Based Folder Parser

Examples

Request URL: https://sub-domain.domain.tld/sub/folder/folder_parser.php

Output 1:

$newPaths [ "sub-domain.domain.tld/", "sub-domain.domain.tld/sub", "sub-domain.domain.tld/folder" ];

in other way just on main domain;

Request URL: https://domain.tld/sub/folder/folder_parser.php

Output 2:

$newPaths [ "domain.tld/", "domain.tld/sub", "domain.tld/folder" ];

or included www field

Request URL: https://www.domain.tld/sub/folder/folder_parser.php

Output 3:

$newPaths [ "www.domain.tld/", "www.domain.tld/sub", "www.domain.tld/folder" ];

and there are other possibilities

// url based folder parser
public function folderParser(){
// get current protocol
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https" : "http";
// build current full url
$requesturl = "{$protocol}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
// parse request url with protocol
preg_match("/(https?:\/\/)(www.)?([a-z-_]+\.)?([a-z-_]+)(\.[a-z]{0,10})(\/)(.+)/", $requesturl, $allMatchs);
// explode sub folders
$folders = explode('/', $allMatchs[10]);
// current folder queue
$folder = '';
// new path with subdomain?domain
$newPaths = [];
// loop in folders
for ($i = 0; $i < count($folders); $i++){
// fist main folder
array_push($newPaths, "{$allMatchs[1]}{$allMatchs[2]}{$allMatchs[3]}{$allMatchs[4]}{$allMatchs[5]}/{$folder}");
// sub folders
$folder .= "{$folders[$i]}/";
}
return $newPaths;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment