Twifty
Twifty

Reputation: 3378

parsing a url localhost vs online

I have this simple method which checks if a url is for part of my admin area.

protected function is_admin_url ( $url ) {
    $parts = parse_url( $url );
    if ( !empty($parts['path']) ) {
        $steps = explode('/', $parts['path']);
        if ( $steps[1] == $this->slug ) // $steps[0] will always be empty
            return true;
    }
    return false;
}

It should return true for any url in the form http://example.com/slug/foo?bar=baz The problem I'm having is that while developing on my local machine (using WAMP) all urls are in the form http://localhost/example.com/slug/foo?bar=baz. This of course breaks the method since the domain is now part of the path.

Hard coding the array index is bound to lead to bugs. Is there any conditional statement I can add in to handle this?

I should also note, this is part of a plugin for WordPress. The site url is not known.

Upvotes: 0

Views: 712

Answers (3)

evuez
evuez

Reputation: 3387

You can check if there is a dot in $steps[1] or just check if you are working in a local environment:

protected function is_admin_url ( $url ) {
    $parts = parse_url( $url );
    if ( !empty($parts['path']) ) {
        $steps = explode('/', $parts['path']);
        $slug = $steps[1];
        if (strpos($steps[1], '.')) $slug = $steps[2];
        if ( $slug == $this->slug )
            return true;
    }
    return false;
}

or

protected function is_admin_url ( $url ) {
    $parts = parse_url( $url );
    if ( !empty($parts['path']) ) {
        $steps = explode('/', $parts['path']);
        $slug = $steps[1];
        if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') $slug = $steps[2];
        if ( $slug == $this->slug )
            return true;
    }
    return false;
}

Upvotes: 1

linkamp
linkamp

Reputation: 215

Maybe you can use a Check with $_SERVER['REMOTE_ADDR']=='127.0.0.1' for detect if is development environment or put in global config a variable $local = true and use inside function is_admin_url.

Upvotes: 0

BurninLeo
BurninLeo

Reputation: 4474

Just check the part between the most recent /s

protected function is_admin_url ( $url ) {
    $pFile = strrpos($url, '/');
    $pFolder = strrpos($url, '/', $pFile-1);
    if (($pFile === false) or ($pFolder === false)) {
        return false;
    }
    $folder = substr($url, $pFolder+1, $pFile-$pFolder-1);
    return ($folder == $this->slug);
}

BurninLeo

Upvotes: 0

Related Questions