Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Get the user IP address : REMOTE_ADDR

By editor , 28 November, 2015
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();

Tags

  • Drupal 8
  • Code
  • User
  • Add new comment

Comments4

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

timo (not verified)

10 years 4 months ago

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?

 

  • Reply

editor

10 years 4 months ago

In reply to were to place it? by timo (not verified)

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 ";
  }
}

 

  • Reply

timo (not verified)

10 years 4 months ago

thanks!

Hi,

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

  • Reply

editor

10 years 4 months ago

In reply to thanks! by timo (not verified)

Use this Example

Please use this example to insert your codes.

http://drupal8.ovh/sites/drupal/files/2016-07/test_hook_system.zip

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer