开发者

PHP Combining Two Negative OR Conditions

开发者 https://www.devze.com 2022-12-21 02:55 出处:网络
I\'m writing a PHP site, and am using google analytics to track site activity. I\'ve written a function that\'s going to echo the tracking code, that can be included in th开发者_StackOverflow中文版e

I'm writing a PHP site, and am using google analytics to track site activity.

I've written a function that's going to echo the tracking code, that can be included in th开发者_StackOverflow中文版e common site footer.

The thing is, I don't want it to track hits from our office (I've had mixed results with Google Analytics' IP filter before so have chosen to hard code it this time), and hits to admin pages.

So Pseudo code would be,

IF (PHP_self does contain admin) OR (IP address is not office) echo tracking code

The actual way I've written this is:

if (!( (substr($_SERVER['PHP_SELF'], 0, 7) == '/admin/') || ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx') )) {

Is the best way to do it?

I tried the following but it didn't work:

if ( (substr($_SERVER['PHP_SELF'], 0, 7) != '/admin/') || ($_SERVER['REMOTE_ADDR'] != 'xxx.xxx.xxx.xxx') ) {


De Morgan's laws means that the second should use && instead of ||.

Either way is fine, based on the fact that neither comparison has side effects.


because you want to do something when condition is false (and do nothing otherwise), the condition should be negative. Compare

// BAD
if(something) {
   ???
} else {
   do the job
}

// GOOD
if(not_something)
  do the job

so, the second option is the way to go (|| -> &&, as already suggested).

Besides that, early exits are generally better than complex conditions

function echo_counter() {
    if(is_admin_page)
         return;
    if(intranet_ip)
         return;
    ...potentially some more conditions...
   do the job
}
0

精彩评论

暂无评论...
验证码 换一张
取 消