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


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 }}.

| improve this answer | |

From PHP:

if (craft()->request->getIpAddress() == '')

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() == '' %}
{% 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.

| improve this answer | |
  • Thanks Brad - I'd searched the docs using 'ip ' and should've used 'ipa'! – Clive Portman Nov 5 '14 at 16:00
  • Actually, is there any reason {{ craft.request.getIpAddress() }} would be empty? – Clive Portman Nov 5 '14 at 16:05
  • If your server isn't populating $_SERVER['REMOTE_ADDR']? – Brad Bell Nov 5 '14 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. – Clive Portman Nov 6 '14 at 13:04
  • And have tried this on two sites on different server setups, too. – Clive Portman Nov 6 '14 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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