Home > Back-end >  PHP Calculate Long Integer Range of Subnet ip2long
PHP Calculate Long Integer Range of Subnet ip2long

Time:11-11

I am trying to determine whether a website visitor came from an EU country, and if so show them a cookie consent banner per their law.

I downloaded a table listing IPv4 of all EU countries (ie: 1.178.224.0/19) and uploaded it to mySQL. There are 107,000 rows in the table. I can get the users IP using $_SERVER['REMOTE_ADDR']. I'm looking for the most simplified and quickest approach to check using PHP if the user's ip address falls in the range.

One idea was to create 2 columns in a table with the starting and ending long integers of each IPv4. The website would change the users IP address to a long integer using ip2long() and then see if it falls within the range of the 2 columns of any IPv4. Not sure if this is possible. If that's a good idea, how do I get the starting and ending long integer of an IPv4 address?

I found several solutions to see if an IP falls within the range (ie: 1.178.224.0/19) listed in my table, but with 107,000 rows this would probably take a while to process. I'm looking for a solution that runs quick so not to slow down every user who's not in an EU country.

CodePudding user response:

Instead of trying to implement geolocation yourself, you could use a free online service for that. You can implement this quite quickly. Take for instance this service:

http://geolocation-db.com/documentation

I would use Javascript not PHP, and only when an user is in an EU country you pop up the cookie consent banner.

  • Related