Get the user IP address : REMOTE_ADDR | Drupal 8

Get the user IP address : REMOTE_ADDR

Submitted by editor on Sat, 11/28/2015 - 10:22
Question

How to get the ip address properly in Drupal 8 ?

Drupal do not like using the $_SERVER['REMOTE_ADDR']; to get the remote ip (the user ip address).

In Drupal 7, the function ip_address() exist but not in D8.
$ip = ip_address();

Drupal 8
$ip = \Drupal::request()->getClientIp();

Comments

timo (not verified)

Thu, 07/07/2016 - 17:31

Hi there,

With the new contact module of drupal 8, i don't have a clue where to place your script.

Can you receive user-ip after they have submitted a form?

 

Hi,
To add the user IP address to the contact mail, you must create a small module and use the hook hook_mail_alter(&$message). (See How to create a module in Drupal 8 with Hook)

Example (not tested)

function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'contact_user_mail' || $message['id'] == 'contact_user_copy') {
    // Add the visitor IP address at the end of the contact mail body
    $ip = \Drupal::request()->getClientIp();
    $message['body'][] =  "--\nUser IP Address : $ip ";
  }
}

 

timo (not verified)

Fri, 07/08/2016 - 12:19

Hi,

Thanks a lot, still trouble creating it. But will come there eventually!

Add new comment