maxmind / GeoIP2-php

PHP API for GeoIP2 webservice client and database reader
https://maxmind.github.io/GeoIP2-php/
Apache License 2.0
2.3k stars 274 forks source link

Is there a trick to put geoip2 everywhere on the dedicated server in a single source and call it everywhere (cPanel) #202

Closed Madriix closed 1 year ago

Madriix commented 1 year ago

Currently I install geoipphp in every folder where I want to use it, but I'd like to save ressource by installing geoip2 in one place and calling it everywhere from any user. Do you have an idea how to do it? Thanks in advance

Madriix commented 1 year ago

I found, I created this folder: /usr/local/share/GeoIP-php

the "/usr/local/share/" folder is shared by all users, all users have the right to go to this folder, so I created the geoip2 project here

inside I put the content of "php composer.phar require geoip2/geoip2:~2.0" but before I installed it in a folder of a user, then after I cut the folder and I put the content in /usr/local/share/GeoIP-php and i set root rights

Then in /usr/local/share/GeoIP-php I created an "api.php" file and in it I put for example:

<?php
error_reporting(0);

require 'vendor/autoload.php';
use GeoIp2\Database\Reader;

// countrycode
function func_geoip2_country($ip) {
    // This creates the Reader object, which should be reused across
    // lookups.
    $reader = new Reader('/usr/local/share/GeoIP/GeoIP2-City.mmdb');

    // Replace "city" with the appropriate method for your database, e.g.,
    // "country".
    $record = $reader->city(htmlentities($ip));

    //print($record->country->isoCode); // 'US'

    return $record->country->isoCode;

}

// here we can create other functions, like to retrieve the isp or the asn or other things

?>

And then in our website, in /home/<user>/public_html/ just put this at the very top of the php page:

@require("/usr/local/share/GeoIP-php/api.php");

And then to retrieve the country of an IP address I do:

echo @func_geoip2_country($address_ip);

All this code is ugly, but it works well, I can now retrieve the country code of an ip without going through file_get_contents or without having to put geoip2 in several accounts, because I am lost. Now there is only one place, it is: /usr/local/share/GeoIP-php If you have another better idea, I'm interested

oschwald commented 1 year ago

I don't have any suggestions in particular. This is more a question about project structure and code deployment generally. I would generally use Composer to manage the deps of each project individual. That said, you may get other suggestions on Stack Overflow or a PHP coding forum.

You could also use the maxminddb C extension and forgo this higher level library.