Skip to main content
1 of 4

Function to get URL

This is a function I wrote which has the intention of extracting bits of the URL.

function getPage($options = "", $page = "")
{
    $self = "{$_SERVER["REQUEST_SCHEME"]}://{$_SERVER["HTTP_HOST"]}{$_SERVER["REQUEST_URI"]}";
    /*
     *   - return the string untouched
     * a - return the page name, extension, and get variables
     * b - no extension, no get variable
     * c - url up to extension, no get variable
     * d - all get variables (everything after "?" excludes the "?") (if no "?" then sets to "")
     * e - domain name e.g. google
     * f - full domain without any page information e.g. http://www.google.com
     * g - full domain e.g. http://www.google.com/search?q=query (overwrites all other options)
     */
    if (empty($options)) return $self;
    
    $options = str_split($options);
    $page = ($page !== "") ? $page : $self;

    if (in_array("a", $options)) $page = substr($page, strrpos($page, "/") + 1);
    if (in_array("b", $options)) $page = substr($page, 0, strrpos($page, ".php"));
    if (in_array("c", $options)) $page = substr($page, 0, strrpos($page, "?"));
    if (in_array("d", $options)) $page = (strpos($page, "?")) ? substr($page, strrpos($page, "?") + 1) : "";
    if (in_array("e", $options)) $page = (strpos($page, "www.")) ? substr($page, strpos($page, "www.") + 4, strpos($page, ".", strpos($page, "www.")) + 4) : ((strpos($page, "/localhost/")) ? substr($page, strpos($page, "://") + 3, strpos($page, "localhost/") + 2) : (strpos($page, "www") ? substr($page, strpos($page, "://") + 3, strlen($page) - strpos($page, "www.") + 5) : substr($page, strpos($page, "://") + 3, strpos($page, ".") - strpos($page, "://") - 3)));
    if (in_array("f", $options)) if (preg_match("/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/", $page, $matches)) $page = $matches[0];
    if (in_array("g", $options)) return $self;

    return $page;
}

I'm not sure if I am creating this in the best way (there are lots of substrings).

One of my current examples of using this code is to determine which page is selected.

<ul id="nav">
    <li class="button <?php echo getPage("ab") == "page1" ? "active" : "inactive"; ?>"><a href="page1.php">Page 1</a></li>
    <li class="button <?php echo getPage("ab") == "page2" ? "active" : "inactive"; ?>"><a href="page2.php">Page 2</a></li>
</ul>

Assuming the URL is "http://www.example.com/page1.php?myVar=myVal"
getPage("ab") would find the page name.
a Would return the page name (e.g. "page1.php")
b Would return "http://www.example.com/page1"
Combining the two returns "page1".