Search code examples
phpdevelopment-environmenturl-parametersstrpos

Detecting if a URL contains a certain string but NOT as a parameter using PHP


I'm trying to force different modes of debugging based on different development urls using PHP. I currently have this set up:

$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']), 'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$req_uri = $_SERVER['REQUEST_URI'];
$currentUrl = $protocol . '://' . $host . $req_uri;

$hostArray = array("localhost", "host.integration", "10.105.0"); //Don't use minification on these urls


for ($i = 0; $i < count($hostArray); $i++) {
    if (strpos($currentUrl, $hostArray[$i])) {
        $useMin = false;
    }
}

However, using this method, you would be able to trigger the $useMin = false condition if you were to pass any of the strings in the host array as a parameter, for example:

http://domain.com?localhost

How do I write something that will prevent $useMin = false unless the URL starts with that condition (or is not contained anywhere after the ? in the url parameter)?


Solution

  • Don't use the $currentUrl when checking $hostArray, just check to see if the $host itself is in the $hostArray.

    If you want to check for an exact match:

    if(in_array($host, $hostArray)) {
        $useMin = false;
    }
    

    Or maybe you want to do this, and check to see if an item in $hostArray exists anywhere within your $host:

    foreach($hostArray AS $checkHost) {
        if(strstr($host, $checkHost)) {
            $useMin = false;
        }
    }
    

    And if you only want to find a match if $host starts with an item in $hostArray:

    foreach($hostArray AS $checkHost) {
        if(strpos($host, $checkHost) === 0) {
            $useMin = false;
        }
    }