Client location in php

Определение местоположения посетителя по IP-адресу в PHP

Несколько способов определить примерное местоположение пользователя по IP-адресу.

Sypex Geo

Sypex Geo – продукт для определение местоположения посетителя по IP-адресу, распространяется по лицензии BSD, т. е. является абсолютно бесплатным. Получив IP-адрес, Sypex Geo выдает информацию о местоположении посетителя – страну, регион, город, географические координаты из локальной базы данных, которая периодически обновляется.

Пример использования:

getCityFull($_SERVER['REMOTE_ADDR']); print_r($res);

Результат:

Array ( [city] => Array ( [id] => 468902 [lat] => 5762987 [lon] => 3987368 [name_ru] => Ярославль [name_en] => Yaroslavl ) [region] => Array ( [id] => 468898 [name_ru] => Ярославская область [name_en] => Yaroslavskaya Oblast' [iso] => RU-YAR ) [country] => Array ( [id] => 185 [iso] => RU [lat] => 6000 [lon] => 10000 [name_ru] => Россия [name_en] => Russia ) )

ip-api.com

IP Geolocation API – бесплатен для некоммерческого использования, ключ к API не требуется. Сервис возвращает данные в формате JSON, XML, CSV, Newline, PHP (serialize) по GET-запросу.

Ограничения

45 запросов в минуту с одного IP-адреса, при превышении лимита будет отдаваться 429-я ошибка до тех пор, пока не будет сброшено ограничение. Если вы постоянно превышаете лимит, ваш IP-адрес будет заблокирован на 1 час.

Читайте также:  Код для круга css

Пример использования:

Результат:

Array ( [status] => success [country] => Россия [countryCode] => RU [region] => SPE [regionName] => Санкт-Петербург [city] => Санкт-Петербург [zip] => 191015 [lat] => 59,9417 [lon] => 30,3096 [timezone] => Europe/Moscow [isp] => OOO "Network of data-centers "Selectel" [org] => Selectel [as] => AS49505 OOO "Network of data-centers "Selectel" [query] => 95.143.190.109 )

DaData.ru

Среди разделов сайта «DaData.ru» есть сервис «Город по IP-адресу», после регистрации по ключу можно получить детальную информацию о городе, в том числе почтовый индекс.

Бесплатен до 10 000 запросов в сутки, максимум 20 запросов в секунду.

Результат:

Array ( [location] => Array ( [value] => г Ярославль [unrestricted_value] => 150000, Ярославская обл, г Ярославль [data] => Array ( [postal_code] => 150000 [country] => Россия [country_iso_code] => RU [federal_district] => Центральный [region_fias_id] => a84b2ef4-db03-474b-b552-6229e801ae9b [region_kladr_id] => 7600000000000 [region_iso_code] => RU-YAR [region_with_type] => Ярославская обл [region_type] => обл [region_type_full] => область [region] => Ярославская [area_fias_id] => [area_kladr_id] => [area_with_type] => [area_type] => [area_type_full] => [area] => [city_fias_id] => 6b1bab7d-ee45-4168-a2a6-4ce2880d90d3 [city_kladr_id] => 7600000100000 [city_with_type] => г Ярославль [city_type] => г [city_type_full] => город [city] => Ярославль [city_area] => [city_district_fias_id] => [city_district_kladr_id] => [city_district_with_type] => [city_district_type] => [city_district_type_full] => [city_district] => [settlement_fias_id] => [settlement_kladr_id] => [settlement_with_type] => [settlement_type] => [settlement_type_full] => [settlement] => [street_fias_id] => [street_kladr_id] => [street_with_type] => [street_type] => [street_type_full] => [street] => [stead_fias_id] => [stead_cadnum] => [stead_type] => [stead_type_full] => [stead] => [house_fias_id] => [house_kladr_id] => [house_cadnum] => [house_type] => [house_type_full] => [house] => [block_type] => [block_type_full] => [block] => [entrance] => [floor] => [flat_fias_id] => [flat_cadnum] => [flat_type] => [flat_type_full] => [flat] => [flat_area] => [square_meter_price] => [flat_price] => [room_fias_id] => [room_cadnum] => [room_type] => [room_type_full] => [room] => [postal_box] => [fias_id] => 6b1bab7d-ee45-4168-a2a6-4ce2880d90d3 [fias_code] => [fias_level] => 4 [fias_actuality_state] => 0 [kladr_id] => 7600000100000 [geoname_id] => 468902 [capital_marker] => 2 [okato] => 78401000000 [oktmo] => 78701000001 [tax_office] => 7600 [tax_office_legal] => 7600 [timezone] => [geo_lat] => 57.621562 [geo_lon] => 39.897822 [beltway_hit] => [beltway_distance] => [metro] => [divisions] => [qc_geo] => 4 [qc_complete] => [qc_house] => [history_values] => [unparsed_parts] => [source] => [qc] => ) ) )

Источник

Читайте также:  Letter spacing last letter css

Php get location in a request in php

Its cleaner and less messing around with string concatination You get to learn about and functions which can be very useful in certain situations. Solution 1: PHP doesn’t do calculations inside strings and doesn’t parse PHP tags inside strings.

Php get location header after post request

I eventually got it to work using curl like @frz3993 suggested (and after sending in a blank ‘cookies’ header, the server didn’t seem to like it without that)

here is the code that I use now:

 $url, 'op' => "Convert", 'form_build_id' => "form-" . $longid, 'form_id' => "videoconverter_convert_form" ))); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type:application/x-www-form-urlencoded", "Cookie:" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); $data = curl_exec($ch); if (0 === preg_match('/Location: (.*id=(\d+))/', $data, $matches)) exit("false"); $redirect = $matches[1]; $id = $matches[2]; echo $redirect; echo " - "; echo $longid; die(); ?> 

note that even tho the second suggestion from my OP gave me headers, it did not give me the location header which curl does now. (don’t ask me why :p)

Php — Get user’s current location, as PHP relies on server, the real-time location cant be provided only static location can be provided it is better to avoid to rely on the JS for location rather than using php. But there is a need to post the js data to php so that it can be easily be accesible to program on server Code sample$query = @unserialize (file_get_contents(‘http://ip-api.com/php/’));if ($query && $query[‘status’] == ‘success’) foreach ($query as $data)

How to use «request_contact» and «request_location» fields in «KeyboardButton» Object on Telegram Bot API

As Telegram Doc says: «Optional fields are mutually exclusive.» This means that you only can use request_contact field or request_location .You can NOT use both of them togeher.

Also , keyboard MUST be array of arrays of KeyboardButton object. This is a working sample replyMarkup you can use instead:

$replyMarkup3 =[ 'keyboard' =>[ [ [ 'text'=>'test', 'request_contact'=>true, ]]], 'resize_keyboard'=>true, 'one_time_keyboard'=>true, ]; 

Php get location header after post request, I need to get the location header the following request: This is what the request looks like from the chrome network dev tool when I execute it in chrome. here is the redirect request in chrome n

PHP GET method in <a href&gt

PHP doesn’t do calculations inside strings and doesn’t parse PHP tags inside strings. You are already in ‘PHP mode’, and opening another PHP tag inside the string just outputs that tag as you may have noticed when you inspected the link in your browser.

Instead, try closing the string, concatenating the next/previous month (using the dot operator), and concatenating the last part of the link:

You can also calculate the values into variables first, because simple variables can be used inside double-quoted strings:

On the first request, you may not have a month at all, so you may want to check for that too, for instance using isset.

$month = 1; if (isset($_GET['month']))

As you can see, I already did an (int) typecast there too. Combining this with the variables version, allows you to make the code a little more solid by performing some checks on the input, and only output the previous/next links if they make sense.

Oh, and a minor detail. Personally I don’t like to put ‘big’ chunks of HTML inside a string, so I’d rather use some template, or at least write it like this. As you can see, you can close and open PHP tags (just not inside strings), so you can output plain HTML from within your PHP code. The notation is a shorthand for .

Try doing something like the following:

echo sprintf('Previous', http_build_query(array('month' => $month - 1))); echo sprintf('Next', http_build_query(array('month' => $month + 1))); 

While it seems more convoluted, it serves two purposes.

  1. Its cleaner and less messing around with string concatination
  2. You get to learn about sprintf and http_build_query functions which can be very useful in certain situations. sprintf is a string formatting function which basically takes a string as its first parameter and substitutes certain tokens with the next n parameters. In this example, %s is a token which means replace it with a string, which is passed as the second function. http_build_query takes an associative array and builds a http query from it. So in the code above, the http_build_query function will return month=11 (assuming the month was 12) for the Previous link. You can also add multiple array parameters and it will build the query string with the ampersands.

While the other answers do what you need, its always wise to look at and understand other PHP functions.

The $_SERVER REQUEST METHOD when you click on a link is ‘GET’.

use the parse_str function and place your $_GET keys and variables into an array.

parse_str($_SERVER['QUERY_STRING'],$output); print_r($output); 

Maybe you can test for that. Is this what you are looking for?

Javascript — How to get location, I want to get the location of a client on my webpage. I can do it with either PHP or Javascript. I’m currently trying to get the location by the client’s IP address and by using geoip extension for PHP. But it requires a datgabase and I don’t want that. Is there any other way to find the client’s location?

Источник

Easy to use PHP class to detect client location

Here in this post, we are going to see a PHP class which can be used to detect client location. The class is so easy to use. It will return the city name, country name, country code, latitude and longitude of the client.

In our code, we have used IPInfoDb API to detect the location from the IP address. Below is the code of the PHP class:

appkey = $key; $this->userip = $this->get_client_ip(); if (strlen($this->userip) < 6) < echo "IP address cannot be detected offline or on localhost server or some other issue may occur."; exit(); > > private function get_client_ip() < $ipaddress = ''; if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP'); else if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); else $ipaddress = 'UNKNOWN'; return $ipaddress; >private function iiddecode() < $jsoncont = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=".$this->appkey."&ip=".$this->userip."&format=json"); $getdecoded = json_decode($jsoncont, true); return $getdecoded; > public function city() < return $this->iiddecode()['cityName']; > //country public function country() < return $this->iiddecode()['countryName']; > // country code public function countrycode() < return $this->iiddecode()['countryCode']; > // regiom name public function region() < return $this->iiddecode()['regionName']; > // let from IP public function latFromIp() < return $this->iiddecode()['latitude']; > // lon from IP public function longFromIp() < return $this->iiddecode()['longitude']; > > ?>

How to use the above PHP class to detect client location?

Using the above class you just need to write a line of code to create an object of the class and simply echo it to display on web page. For example, suppose you have created an object $obj. Now to show the city name, just use the code echo $obj->city();

Let’s create a new file ClientLocation.php and after that create another PHP file which will include ClientLocation.php in that file just like below:

The above code will display the city name. Similarly, we can show the country name, country code, region, latitude and longitude. Below is the list was given:

Here is another example to show the longitude and latitude:

latFromIp(); // Display the longitude echo $client_location->longFromIp(); ?>

So friends, Did you like this post? I hope you find this post interesting. Please comment below if you have to say anything related to this tutorial.

Источник

Оцените статью