HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Function to get URL

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
getfunctionurl

Problem

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

For the latest version visit my GitHub.

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 l

Solution

Have you tried using this function before? It does a fair bit of what you are trying to accomplish.

http://php.net/manual/en/function.parse-url.php

Failing that, I would try learning regular expressions, as they can make a lot of your strpos more concise. Its a handy skill to have in the toolbox.

http://php.net/manual/en/function.preg-match.php

I also find the a,b,c thing incredibly cryptic
You could use constants

const PAGE_NAME_EXT_GET_VARS = 'a';
const NO_EXT_NO_GET_VARS = 'b';

Code Snippets

const PAGE_NAME_EXT_GET_VARS = 'a';
const NO_EXT_NO_GET_VARS = 'b';

Context

StackExchange Code Review Q#159854, answer score: 4

Revisions (0)

No revisions yet.