What is the meaning of the characters "?", "()" AND ":" in PHP?

I finally remembered what to ask. I never had anything: huh? when a variable is defined as follows:

$ip = ($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']; 

As you can see, there is? and: and ()

Can someone give me a brief information on why and how they are used?

+4
source share
4 answers

The expression is as follows:

 $var = (condition) ? if_true : if_false 

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

In your particular case:

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

  • This is usually used to obtain the client IP address. However, note that overall this is a terrible way to verify client identification. See fooobar.com/questions/99827 / .... (Use session cookies or some authentication if you need to make sure that users are not compressing each other.)

  • In addition, it is 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 one, so this could be a mistake.

+24
source

It is known as a ternary operator and is a shorthand (in your case):

 if($_SERVER['HTTP_X_FORWARD_FOR']) { $ip = $_SERVER['HTTP_X_FORWARD_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } 
+2
source
 "?:" (or ternary) operator 

Expression (expr1)? (expr2): (expr3) evaluates the expression expr2 if expr1 is TRUE and expr3 if expr1 is FALSE

See this example:

 <?php // Example usage for: Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; // The above is identical to this if/else statement if (empty($_POST['action'])) { $action = 'default'; } else { $action = $_POST['action']; } ?> 
0
source

The triple form is basically a shortcut for if-> then-> else

I generally avoid this because it is not all readable.

 $ip = ($_SERVER['HTTP_X_FORWARD_FOR']) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR']; 

logically equivalent to:

 if($_SERVER['HTTP_X_FORWARD_FOR']){ $ip = $_SERVER['HTTP_X_FORWARD_FOR']; }else{ $ip = $_SERVER['REMOTE_ADDR']; } 

It should be said that it is EXACTLY that it is most often used for: initializing variables. Very often with form data.

0
source

Source: https://habr.com/ru/post/1313654/


All Articles