ipinfo.io filter AS#### out? - php

I am using ipinfo.io for some simple lookups, but I have one little problem with echo $details->org; It outputs "AS15169 Google Inc.", but I want only the ISP part so "Google Inc.".
Example code:
<?
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
return $details;
}
$details = ip_details($_SERVER['REMOTE_ADDR']);
echo $details->org;
?>
Example output: http://ipinfo.io/8.8.8.8/org
Need some help, anyone?

If you just want the org field you can query http://ipinfo.io/{$ip}/org which will give you the org as a string, which will save you from having to parse any JSON:
$org = file_get_contents("http://ipinfo.io/{$ip}/org");
We can split the org string into the ASN and name by exploding on the first space:
list($asn, $name) = explode(" ", $org, 2);
Putting it all together we get:
function org_name($ip) {
$org = file_get_contents("http://ipinfo.io/{$ip}/org");
list($asn, $name) = explode(" ", $org, 2);
return $name;
}
echo org_name("8.8.8.8");
// => Google Inc.
echo org_name("189.154.55.170");
// => Uninet S.A. de C.V.
echo org_name("172.250.147.230");
// => Time Warner Cable Internet LLC
See http://ipinfo.io/developers for more details about the different endpoints, and rate limits.

Use regex to find anything between word boundaries that starts with AS and has one or more digits followed by a space and then replace it with a blank string.
I'm not great with regex so someone might come in with a better solution that this. But I tested it at PHP Live Regex and it worked for the few test cases I tried.
<?
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
return $details;
}
$details = ip_details($_SERVER['REMOTE_ADDR']);
$org = preg_replace('/\bAS\d+\s\b/i', '', $details->org);
echo $org;
?>

Related

simple currency converter script using php

I want to convert from dollars to Colombian pesos in PHP and that this is saved in a variable to use it in the paypal api, i have investigated and tested and I used this page https://free.currencyconverterapi.com/
Here's my code example:
<?php
function convertCurrency($amount, $from_currency, $to_currency)
{
$apikey = '*******';
$from_Currency = urlencode($from_currency);
$to_Currency = urlencode($to_currency);
$query = "{$from_Currency}_{$to_Currency}";
// URL para solicitar los datos
$json = file_get_contents("https://free.currconv.com/api/v7/convert?q={$query}&compact=ultra&apiKey={$apikey}");
$obj = json_decode($json, true);
$val = floatval($obj["$query"]);
$totalc = $val * $amount;
return number_format($totalc, 0, '', '');
}
//uncomment to test
echo "1 USD equivale a ";
echo convertCurrency(1, 'USD', 'COP');
echo " COP";
?>
but for some reason that i don't understand, the next day the server went down or something and now i have to use something else
Researching i also learned that google has an api but so many blogs that i have read it is not clear to me how to implement it, can someone please help me?
(I know that there are questions before this one with the same topic, but I feel that they are outdated...)

php: wanted to replace '\\\/' from string

I wanted to replace en/us with es/es:
<?php
$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$json = json_encode($str);
$str = str_replace('en\/us', 'es\/es', $json);
echo $str;
You need to 'double escape' the backslash, like so:
<?php
$str = array('url'=>'www.domain.com/data/en/us/data.gif');
$json = json_encode($str);
$str = str_replace('en\\/us', 'es\\/es', $json);
echo $str;
See http://php.net/manual/en/language.types.string.php (section 'Single quoted').
Would be easier to escape the string BEFORE feeding it to json_encode, but I'm assuming this is a test case and the data you want to replace in is already JSON.
JSON is a useful format for moving data between systems. Converting data to JSON and then trying to manipulate it without parsing it first is almost always a terrible (overly complicated and error prone) idea.
Do the replacement before you convert it to JSON.
<?php
function replace_country($value) {
echo $value;
echo "\n";
return str_replace('en\/us', 'es\/es', $value);
}
$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str = array_map("replace_country", $str);
$json = json_encode($str);
echo $json;
Try this
$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str['url']=str_replace('en\/us', 'es\/es', $str['url']);
$json = json_encode($str);
It produce out put as
It will work for you.

Preg_Match For YouTube Views

I'm new to php and i'm facing this problem. Need some help in matching the youtube views preg_match.
The below codes posted are the codes i made for the preg match but these are not working. Can anyone help me out.
if($row['type']=="Views"){
$data = $row['data'];
$type = "YouTube Views";
//INSTAGRAM
$file = #file_get_contents($data);
preg_match('/\"watch-view-count":(.*?)\,/',$file,$mfc);
$ccnt = $mfc[1];
//INSTAGRAM
}
if($row['type']=="Views"){
$data = $row['data'];
$type = "YouTube Views";
//Views
$file = #file_get_contents($data) or die("YouTube Offline ? :/");
preg_match('/\"watch-view-count":(.*?)\,/',$file,$mfc);
$ccnt = $mfc[1];
$data = http://www.youtube.com/watch?v=BPmhFrwDJTo
I need the preg_match to get the current count of views in the youtube video. I'm really sorry for the bad grammar.
Don't use regex for parsing HTML. Use a DOM Parser instead. It'll be more efficient.
In this case, you can simple use the Youtube API:
<?php
$video_ID = 'BPmhFrwDJTo';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views.' views';
?>
Output:
7 views

Extracting data from Wikipedia API

I would like to be able to extract a title and description from Wikipedia using json. So... wikipedia isn't my problem, I'm new to json and would like to know how to use it. Now I know there are hundreds of tutorials, but I've been working for hours and it just doesn't display anything, heres my code:
<?php
$url="http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$pageid = $data->query->pageids;
echo $data->query->pages->$pageid->title;
?>
Just so it easier to click:
http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids
I know I've probably just done a tiny thing wrong, but its really bugging me, and the code... I'm used to using xml, and I have pretty much just made the switch, so can you explain it a bit for me and for future visitors, because I'm very confused... Anything you need that I haven't said, just comment it, im sure I can get it, and thanks, in advance!
$pageid was returning an array with one element. If you only want to get the fist one, you should do this:
$pageid = $data->query->pageids[0];
You were probably getting this warning:
Array to string conversion
Full code:
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->title;
I'd do it like this. It supports there being multiple pages in the same call.
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$titles[] = $page['title'];
}
var_dump($titles);
/* var_dump returns
array(1) {
[0]=>
string(6) "Google"
}
*/
Try this it will help you 💯%
This code is to extract title and description with the help of Wikipedia api from Wikipedia
<?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
$title = $data->query->pages->$pageid->title;
echo "<b>Title:</b> ".$title."<br>";
$string=$data->query->pages->$pageid->extract;
// to short the length of the string
$description = mb_strimwidth($string, 0, 322, '...');
// if you don't want to trim the text use this
/*
echo "<b>Description:</b> ".$string;
*/
echo "<b>Description:</b> ".$description;
?>

Get keyword from a (search engine) referrer url using PHP

I am trying to get the search keyword from a referrer url. Currently, I am using the following code for Google urls. But sometimes it is not working...
$query_get = "(q|p)";
$referrer = "http://www.google.com/search?hl=en&q=learn+php+2&client=firefox";
preg_match('/[?&]'.$query_get.'=(.*?)[&]/',$referrer,$search_keyword);
Is there another/clean/working way to do this?
Thank you,
Prasad
If you're using PHP5 take a look at http://php.net/parse_url and http://php.net/parse_str
Example:
// The referrer
$referrer = 'http://www.google.com/search?hl=en&q=learn+php+2&client=firefox';
// Parse the URL into an array
$parsed = parse_url( $referrer, PHP_URL_QUERY );
// Parse the query string into an array
parse_str( $parsed, $query );
// Output the result
echo $query['q'];
There are different query strings on different search engines. After trying Wiliam's method, I have figured out my own method. (Because, Yahoo's is using 'p', but sometimes 'q')
$referrer = "http://search.yahoo.com/search?p=www.stack+overflow%2Ccom&ei=utf-8&fr=slv8-msgr&xargs=0&pstart=1&b=61&xa=nSFc5KjbV2gQCZejYJqWdQ--,1259335755";
$referrer_query = parse_url($referrer);
$referrer_query = $referrer_query['query'];
$q = "[q|p]"; //Yahoo uses both query strings, I am using switch() for each search engine
preg_match('/'.$q.'=(.*?)&/',$referrer,$keyword);
$keyword = urldecode($keyword[1]);
echo $keyword; //Outputs "www.stack overflow,com"
Thank you,
Prasad
To supplement the other answers, note that the query string parameter that contains the search terms varies by search provider. This snippet of PHP shows the correct parameter to use:
$search_engines = array(
'q' => 'alltheweb|aol|ask|ask|bing|google',
'p' => 'yahoo',
'wd' => 'baidu',
'text' => 'yandex'
);
Source: http://betterwp.net/wordpress-tips/get-search-keywords-from-referrer/
<?php
class GET_HOST_KEYWORD
{
public function get_host_and_keyword($_url) {
$p = $q = "";
$chunk_url = parse_url($_url);
$_data["host"] = ($chunk_url['host'])?$chunk_url['host']:'';
parse_str($chunk_url['query']);
$_data["keyword"] = ($p)?$p:(($q)?$q:'');
return $_data;
}
}
// Sample Example
$obj = new GET_HOST_KEYWORD();
print_r($obj->get_host_and_keyword('http://www.google.co.in/search?sourceid=chrome&ie=UTF-&q=hire php php programmer'));
// sample output
//Array
//(
// [host] => www.google.co.in
// [keyword] => hire php php programmer
//)
// $search_engines = array(
// 'q' => 'alltheweb|aol|ask|ask|bing|google',
// 'p' => 'yahoo',
// 'wd' => 'baidu',
// 'text' => 'yandex'
//);
?>
$query = parse_url($request, PHP_URL_QUERY);
This one should work For Google, Bing and sometimes, Yahoo Search:
if( isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']) {
$query = getSeQuery($_SERVER['HTTP_REFERER']);
echo $query;
} else {
echo "I think they spelled REFERER wrong? Anyways, your browser says you don't have one.";
}
function getSeQuery($url = false) {
$segments = parse_url($url);
$keywords = null;
if($query = isset($segments['query']) ? $segments['query'] : (isset($segments['fragment']) ? $segments['fragment'] : null)) {
parse_str($query, $segments);
$keywords = isset($segments['q']) ? $segments['q'] : (isset($segments['p']) ? $segments['p'] : null);
}
return $keywords;
}
I believe google and yahoo had updated their algorithm to exclude search keywords and other params in the url which cannot be received using http_referrer method.
Please let me know if above recommendations will still provide the search keywords.
What I am receiving now are below when using http referrer at my website end.
from google: https://www.google.co.in/
from yahoo: https://in.yahoo.com/
Ref: https://webmasters.googleblog.com/2012/03/upcoming-changes-in-googles-http.html

Categories