Restrict access to functionality for user by IP address

16,805

You have to use the $_SERVER global variable, like this:

if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
  // restrict
}

But You have to consider kojiro's note: it's not a good idea to restrict by IP address.

Edit: to be constructive.

If you want to do it on low level, you can use cookies. These variables stored in the user's browser, if the user clear the cookies locally, he/she can override your restriction.
http://www.php.net/manual/en/function.setcookie.php

The better solution is to use sessions for this filter:
http://php.net/manual/en/session.examples.basic.php

Share:
16,805
Dan Hanly
Author by

Dan Hanly

My name is Dan Hanly and I am a Full Stack Application Developer from Pontypridd in South Wales. I have a tremendous passion for developing in a range of languages and for bringing large-scale projects through their full development lifecycle into a production environment. I am highly capable and a quick learner, always bringing fresh ideas, out-of-the-box thinking and the ability to adapt my professional skills to any project requirement. I’m not constrained by technology, understanding instead the need to adopt the appropriate technology for each unique project. I am also keenly involved in the Open Source community, developing useful components and trying to involve myself in large projects in need of development help. My strengths are: Great at tackling complex problems I write clean, well-commented code Experienced with a range of testing (TDD & BDD) I follow development standards Experienced with task-automation Working in an Agile development environment Utilising git version control on all projects

Updated on July 12, 2022

Comments

  • Dan Hanly
    Dan Hanly almost 2 years

    I have a website that allows a functionality for any user but each user is only allowed to use it a fixed amount of times.

    Allow me to go into some more detail, our "anonymous/guest" user is allowed to search on the database for entries only 3 times per 24 hours. Is there a way I can use the IP to track the users attempts at this, restricting them after 3 attempts and then get it to expire after 24 hours?

    The website is built in PHP but whatever language serves this functionality, I am open to it.

    EDIT:

    This idea comes from a client, they have a list of "stockists" stocking their products and they want to make this information available to users of the website. However, he doesn't want competitors taking advantage of his system and "undercutting" him on his stockists. Hence the restriction. If you can suggest a better way to achieve the same then that'd be amazing

    Cheers, Dan