Note: Undefined index: HTTP_X_FORWARDED_FOR Error in function

I get a notification: Undefined index: HTTP_X_FORWARDED_FOR in the function below:

function _ip( ) { return ( preg_match( "/^([d]{1,3}).([d]{1,3}).([d]{1,3}).([d]{1,3})$/", $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'] ); } 
+4
source share
4 answers

You should use the getenv () method instead of $ _SERVER.

 function _ip( ) { if (preg_match( "/^([d]{1,3}).([d]{1,3}).([d]{1,3}).([d]{1,3})$/", getenv('HTTP_X_FORWARDED_FOR')) { return getenv('HTTP_X_FORWARDED_FOR'); } return getenv('REMOTE_ADDR'); } 

In addition, I would only stick with $ip = getenv('REMOTE_ADDR') , since spammers themselves can set the HTTP_X_FORWARDED_FOR header to whatever they want, while they cannot change remote_addr. The problem is that the “good” proxies tell the truth about HTTP_X_FORWARDED_FOR so you skip this.

+15
source

$ _ SERVER ['HTTP_X_FORWARDED_FOR'] does not exist in your array. You can confirm with print_r($_SERVER) . You will need to check for the presence of this array index before using it.

 function _ip( ) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { return ( preg_match( "/^([d]{1,3}).([d]{1,3}).([d]{1,3}).([d]{1,3})$/", $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'] ); } else { return null; //something else } } 
+3
source

No title ``. You need to check if he is present before his access.

 function _ip( ) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) { if (preg_match( "/^([d]{1,3}).([d]{1,3}).([d]{1,3}).([d]{1,3})$/", $_SERVER['HTTP_X_FORWARDED_FOR']) return $_SERVER['HTTP_X_FORWARDED_FOR']; } } return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; } 
+1
source

Obviously, this is because this index does not exist in the $ _SERVER array. You can avoid the notification by doing

 if( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) { // your code here } else { if( isset( $_SERVER['REMOTE_ADDR'] ) ) return $_SERVER['REMOTE_ADDR']; else return FALSE; } 

I assume that you are trying to get the remote address, the code above may be a little more reliable.

0
source

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


All Articles