What is the meaning of the '?', '()', and ':' symbols in PHP?

后端 未结 4 1086
一整个雨季
一整个雨季 2021-01-14 02:17

I\'ve finally remembered what to ask. I never really got what : and ? do when a variable is being defined like this:

$ip = ($_SERVER[\'HTTP_X_FORWARDED_FOR\'         


        
4条回答
  •  孤街浪徒
    2021-01-14 03:19

    The expression looks like this:

    $var = (condition) ? if_true : if_false
    

    ?: is the ternary operator. If condition is true, $var will be assigned the value if_true; otherwise it will be assigned the value if_false.

    In your particular case:

    • This assigns the value of the X-Forwarded-For HTTP header to $ip if it exists; otherwise it uses the remote address itself.

    • This is usually used as a way to get a client's IP address. However, note that in general this is a terrible way to check for client identity. See this StackOverflow question. (Use session cookies or some sort of authentication if you need to make sure users don't clobber each other.)

    • Also, it's HTTP_X_FORWARDED_FOR, not HTTP_X_FORWARD_FOR.

    • Finally, HTTP_X_FORWARDED_FOR can be a comma-delimited list of IP addresses, not just a single one, so this has the potential to be a bug.

提交回复
热议问题