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']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
As you can see there is ? and : and ( )
Could anyone give me a brief detail about why and how they are used for?
The expression looks like this:
?:is the ternary operator. Ifconditionis true,$varwill be assigned the valueif_true; otherwise it will be assigned the valueif_false.In your particular case:
This assigns the value of the
X-Forwarded-ForHTTP header to$ipif 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, notHTTP_X_FORWARD_FOR.Finally,
HTTP_X_FORWARDED_FORcan be a comma-delimited list of IP addresses, not just a single one, so this has the potential to be a bug.