6

I just want to run a couple of conditionals depending on a visitor's IP address. How would I do that?

2 Answers 2

9

To make use of your visitors IP address, use {{ craft.request.getIpAddress() }} in Craft 2.5. In Craft 3.x, there is {{ craft.app.request.userIP }}.

1
  • 2021 reference: craft.request.getIpAddress() has been deprecated. Use craft.app.request.userIP instead.
    – Dom Stubbs
    Commented Oct 22, 2021 at 10:46
9

From PHP:

if (craft()->request->getIpAddress() == '255.255.255.255')
{
    ...
}

Note from the docs that this is a "best guess" and can easily be spoofed, so you shouldn't use it to hide any sensitive information.

We currently don't expose that method at the template level, but we probably should. I'll add that on the Craft 2.3 branch.

If you want to hack it in before then, you can open up craft/app/variables/HttpRequestVariable.php and add:

public function getIpAddress()
{
    return craft()->request->getIpAddress();
}

Then from a template you'd use:

{% if craft.request.getIpAddress() == '255.255.255.255' %}
    ...
{% endif %}

Just note that there is a chance that a 2.2 update could overwrite that file at any time.

UPDATE: No hack is required since Craft 2.3.2615.

6
  • Thanks Brad - I'd searched the docs using 'ip ' and should've used 'ipa'! Commented Nov 5, 2014 at 16:00
  • Actually, is there any reason {{ craft.request.getIpAddress() }} would be empty? Commented Nov 5, 2014 at 16:05
  • If your server isn't populating $_SERVER['REMOTE_ADDR']?
    – Brad Bell
    Commented Nov 5, 2014 at 17:41
  • This is strange. In a simple PHP file I can echo $_SERVER['REMOTE_ADDR'] but if I put {{ craft.request.getIpAddress() }} at the top of my layout template, nothing is output. Commented Nov 6, 2014 at 13:04
  • And have tried this on two sites on different server setups, too. Commented Nov 6, 2014 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.