Check if running script is in array

Viewed 21

I'm trying to run a function but only on specific pages. I thought this would be fine...

$allowed_pages = array('/admin/update.php', '/admin/system.php', '/admin/install.php');
if($_SERVER['SCRIPT_NAME'] == $allowed_pages) {
    myCoolFuntion();
}

...but it doesn't seem to work as expected and the myCoolFuntion() runs regardless of what page I am on.

If I echo $_SERVER['SCRIPT_NAME'] on any given page, I can see it does match up correctly (it matches a page specified in the array, for example, /admin/update.php as expected) and so I know the values in the array are in the correct format.

What am I doing wrong?

1 Answers

Based on the example provided, I can't see any way that myCoolFunction(); can ever execute.

$_SERVER['SCRIPT_NAME'] will never be equal to $allowed_pages because the first is a string and the second is an array.

Instead of the code as presented, use a function such as in_array to verify that the SCRIPT_NAME value is in the array:

$allowed_pages = array('/admin/update.php', '/admin/system.php', '/admin/install.php');
if (in_array($_SERVER['SCRIPT_NAME'], $allowed_pages)) {
    myCoolFunction();
} else {
    echo 'Not found in array';
}

in_array is defined thus:

Checks if a value exists in an array

More information about in_array is in the official docs.

Related