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
were to place it?
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?
Add User IP to the contact mail
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 ";
}
}
thanks!
Hi,
Thanks a lot, still trouble creating it. But will come there eventually!
Use this Example
Please use this example to insert your codes.
http://drupal8.ovh/sites/drupal/files/2016-07/test_hook_system.zip
Add new comment