Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By ParisLiakos on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Description:
In Drupal 8 ip_address()
has been removed in favor of Request::getClientIp()
The recommended way to access a client's IP address in Drupal 8 is to register an object with the service container and depend on the request service.This way the correct request object will be always provided. If that's not possible Drupal::request() can be used to access the current registered Request object.
D7
Procedural Code
if ($ip == ip_address()) {
drupal_set_message('ip', t('You may not ban your own IP address.'));
}
OOP
class Foo {
public function bar() {
if ($ip == ip_address()) {
drupal_set_message('ip', t('You may not ban your own IP address.'));
}
}
}
D8
Procedural Code
if ($ip == Drupal::request()->getClientIp()) {
drupal_set_message('ip', t('You may not ban your own IP address.'));
}
OOP
In your MYMODULE/MYMODULE.service.yml
:
services:
foo:
class: Drupal\MYMODULE\Foo
arguments: ['@request_stack']
In MYMODULE/src/Foo.php
namespace Drupal\MYMODULE;
use Symfony\Component\HttpFoundation\RequestStack;
class Foo {
/**
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructs a Foo object.
*
* @param Symfony\Component\HttpFoundation\RequestStack $request
* The request object.
*/
public function __construct(RequestStack $request_stack) {
$this->requestStack = $request_stack;
}
public function bar() {
$ip = $this->requestStack->getCurrentRequest()->getClientIp();
// Do something with $ip.
}
}
Impacts:
Module developers