Friday, November 5, 2021

PHP Redirect based on geolocation and use Proxy for location detection

 As we discussed how to use proxy with http requests made, here is a complete solution to make a dynamic request redirection based on client's country.

 <?php  
 try {  
   if (session_status() === PHP_SESSION_NONE) {  
     session_start();  
   }   
 $q='';  
 $redirectUrl='';  
 $country = '';  
 $country = $_SESSION["country"];  
 if (isset($_GET['q'])) {  
   $q = $_GET['q'];  
 } else {  
   header("https://yoursite.com");   
 }  
 if($country=='' || $country == null){  
   $url="http://ip-api.com/json/".getUserIP();  
   $auth = base64_encode('username:password');  
   $aContext = array(  
     'http' => array(  
       'proxy'      => 'tcp://yourproxyserver.io:31112',  
       'request_fulluri' => true,  
       'header'     => "Proxy-Authorization: Basic ".$auth,  
     ),  
   );  
   $cxContext = stream_context_create($aContext);  
   $sFile = file_get_contents($url, False, $cxContext);  
   $arrIpInfo=json_decode($sFile);  
   $country = strtolower($arrIpInfo->country);  
   $_SESSION["country"] = $country;  
 }  
   if($country=="argentina") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="armenia") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="australia") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="austria") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="azerbaijan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="belarus") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="belgium") $redirectUrl = "https://redirectionsite.com/s706?q=".$q;  
   else if($country=="brazil") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="canada") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="chile") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="columbia") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="denmark") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="finland") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="france") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="georgia") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="germany") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="hong kong") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="india") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="indonesia") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="ireland") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="italy") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="japan") $redirectUrl = "https://redirectionsite.com/s706?q=".$q;  
   else if($country=="kazakhstan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="kyrgyzstan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="luxemburg") $redirectUrl = "https://redirectionsite.com/s706?q=".$q;  
   else if($country=="malaysia") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="mexico") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="moldova") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="netherlands") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="new zealand") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="norway") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="peru philippines") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="russia") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="singapore") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="spain") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="sweden") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="switzerland") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="taiwan") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="tajikistan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="thailand") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="turkmenistan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="uk") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="united kingdom") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="united states") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="uzbekistan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="venezuela") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="vietnam") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else $redirectUrl = "https://redirectionsite.com/s901?q=".$q;  
      header("Location: ".$redirectUrl);    
 }  
 catch(Exception $e) {  
   echo 'Message: ' .$e->getMessage();  
  }  
 function getUserIP() {  
   $ipaddress = '';  
   if (isset($_SERVER['HTTP_CLIENT_IP']))  
     $ipaddress = $_SERVER['HTTP_CLIENT_IP'];  
   else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))  
     $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];  
   else if(isset($_SERVER['HTTP_X_FORWARDED']))  
     $ipaddress = $_SERVER['HTTP_X_FORWARDED'];  
   else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))  
     $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];  
   else if(isset($_SERVER['HTTP_FORWARDED_FOR']))  
     $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];  
   else if(isset($_SERVER['HTTP_FORWARDED']))  
     $ipaddress = $_SERVER['HTTP_FORWARDED'];  
   else if(isset($_SERVER['REMOTE_ADDR']))  
     $ipaddress = $_SERVER['REMOTE_ADDR'];  
   else  
     $ipaddress = 'UNKNOWN';  
   return $ipaddress;  
 }  
 ?>  
redirectionsite.com

This is where the actual redirection happens. based on it's s code (ex: s564) it redirects to the country specific location.

Happy coding....


Wednesday, November 3, 2021

PHP - How to use proxy to send http requests

 Sometimes we send http requests and need to send it through a proxy server. Here is the way how we can do it in PHP

 $url="http://ip-api.com/json/1.1.1.1";  
 $auth = base64_encode('username:password');  
 $aContext = array(  
   'http' => array(  
     'proxy'      => 'tcp://proxy.server.io:31112',  
     'request_fulluri' => true,  
     'header'     => "Proxy-Authorization: Basic ".$auth,  
   ),  
 );  
 $cxContext = stream_context_create($aContext);  
 $sFile = file_get_contents($url, False, $cxContext);  
 echo $sFile;  

Happy coding...


Thursday, October 28, 2021

Getting Geo Location free of charge.. in C# ASP.

 Sometimes we need to check the users geolocation from server side for various purposes. Such as link building for region wise. 

This is a free service that you can use for your application which isn't commercial.

you can browse more info here http://ip-api.com

lets see how we implement it.


 string jsonCountry = Session["country"] != null ? Session["country"].ToString() : string.Empty;  
         if (!string.IsNullOrEmpty(jsonCountry))  
         {  
           location = new JavaScriptSerializer().Deserialize<Location>(jsonCountry);  
         }  
         else  
         {  
           string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
           if (string.IsNullOrEmpty(ipAddress))  
           {  
             ipAddress = Request.ServerVariables["REMOTE_ADDR"];  
           }  
           string urlLocation = "http://ip-api.com/json/" + ipAddress;  
           using (WebClient client = new WebClient())  
           {   
             string json = client.DownloadString(urlLocation);  
             Session["country"] = json;  
             location = new JavaScriptSerializer().Deserialize<Location>(json);              
           }  
         }  


Here you can see we use session to store location data to prevent unwanted http calls to the service provider. Location is a class that we use to deserialize the object.

   public class Location  
   {  
     public string status { get; set; }  
     public string country { get; set; }  
     public string countryCode { get; set; }  
     public string region { get; set; }  
     public string regionName { get; set; }  
     public string city { get; set; }  
     public string zip { get; set; }  
     public double lat { get; set; }  
     public double lon { get; set; }  
     public string timezone { get; set; }  
     public string isp { get; set; }  
     public string org { get; set; }  
     public string @as { get; set; }  
     public string query { get; set; }  
   }  

If you want you can add a proxy to your webclient as below

             WebProxy wp = new WebProxy();
             wp.Address = new Uri(string.Format("{0}:{1}", "http://proxy.something.io", "22222"));  
             wp.Credentials = new NetworkCredential("username", "password");  
             client.Proxy = wp;  

Hopefully this works.

Happy coding.

Thursday, September 9, 2021

Wordpress Rest API and C#

Wordpress has introduced it's rest API for developers to create posts and many more... you can visit their documentation from here.

https://developer.wordpress.org/rest-api/

Today let's see how we can work with it. We use postman to do the work. 

First we need to install the JSON Basic Authentication plugin. (https://github.com/WP-API/Basic-Auth)

And then we can call the API normally. The authentication has to be provided with the format of username:password and it has to be base64 encrypted.

Lets see how we can list posts.


 var client = new RestClient("https://wordpress-ASDASD90809.com/wp-json/wp/v2/posts");  
 client.Timeout = -1;  
 var request = new RestRequest(Method.GET);  
 request.AddHeader("Authorization", "Basic BASE64ENC(UNAME:PASSWORD)");  
 request.AddHeader("Content-Type", "application/x-www-form-urlencoded");  
 request.AddParameter("page", "1");  
 request.AddParameter("per_page", "100");  
 IRestResponse response = client.Execute(request);  
 Console.WriteLine(response.Content);  

You can get the results as follows.


Also you can create categories, create posts list posts and do many more things with the API.

Let's see a bit more details in next post. 

Until that, happy coding...



Friday, July 9, 2021

Blazor cache management using IMemoryCache

Hi Guys, In depth article about Blazor caching can be found here. We here, will look how to implement it.

Suppose you have a service called CardService that delivers a set of card objects as requested. So we need to cache the data on that methods. Let's see how we can do it.

Here we use the IMemoryCache interface in CardService constructor.

     private IMemoryCache _memoryCache;  
     public CardService(IMemoryCache memoryCache)  
     {  
       _memoryCache = memoryCache;        
     }  

Now we can use the _memoryCache to deal with the cache as below;

     public Task<Keyword[]> GetCardSimilarAskKeywords(string url,string tablePrefix)  
     {  
       string key = "GetCardSimilarAskKeyword"+ url;  //cache key
       var encodedCache = _memoryCache.Get(key);  //get value 
       if (encodedCache == null)  // if value null then get it from DB
       {  
         var options = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(365)).SetAbsoluteExpiration(TimeSpan.FromDays(365));  
         List<Keyword> caList = new List<Keyword>();  
         //Get Keyword list from the data of yours.  
         _memoryCache.Set(key, caList, options);  
         GC.Collect();  
         return Task.FromResult(caList.ToArray());  
       }  
       else  
       {  //if value is in cache, convert and return
         var o = _memoryCache.Get(key);  
         IEnumerable e = o as IEnumerable;  
         var ka = e.OfType<Keyword>().ToList();  
         GC.Collect();  
         return Task.FromResult(ka.ToArray());  
       }  
     }  

In your razor page, inject the service on top

 @inject CardService service  

And now we use the method,

 var kwd = await service.GetCardSimilarAskKeywords("url","prefix");  

Now you need to add the following code to the startup.cs

 services.AddSingleton<CardService>();  

It's done. Lets look at some important options of "MemoryCacheEntryOptions"

We can set the expiration of cache as below;

// keep item in cache as long as it is requested at least
// once every 5 minutes...
// but in any case make sure to refresh it every hour
new MemoryCacheEntryOptions()
  .SetSlidingExpiration(TimeSpan.FromMinutes(5))
  .SetAbsoluteExpiration(TimeSpan.FromHours(1))

In above example, I have set the cache expiration to 365 days. Which means it will recycle once a year. 

Hope you can enjoy the coding...

Anything to know? Post a comment. Thanks.

Tuesday, July 6, 2021

Getting country of the user without navigator object

 Getting the country in browser require user to approve. But what if the user doesn't approve. Here is a way to get users location using JQuery.

       $.ajax({          
         url: "https://geolocation-db.com/jsonp/ee33e930-db78-11eb-9218-377a93e0222e",  
         jsonpCallback: "callback",  
         dataType: "jsonp",  
         success: function (location) {  
           $('#country').html(location.country_name);  
           $('#state').html(location.state);  
           $('#city').html(location.city);  
           $('#latitude').html(location.latitude);  
           $('#longitude').html(location.longitude);  
           $('#ip').html(location.IPv4);  
         }  
       });  

More details : https://geolocation-db.com/documentation

Happy coding..

Friday, July 2, 2021

C# ASP.Net Playing with HTML - Automatic Tag Closer

 When we have to deal with HTML strings and sometimes have to split it for Read More text. So, there is a posibility to have open tags which result the total page to collapse. Therefore we might need an automatic tag closer for a splitted HTML string. The following class would do the needful.


   public class TagCloser  
   {  
     private Stack<string> _openTags = new Stack<string>();  
     private string _html;  
     private int _currentCharIndex;  
     private bool Eof  
     {  
       get { return _currentCharIndex == _html.Length - 1; }  
     }  
     private int _pendingTagNameStartIndex;  
     private string _pendingTagName;  
     private int _currentEndTagStartIndex;  
     private State _state;  
     public string CloseTags(string html)  
     {  
       if (string.IsNullOrEmpty(html))  
         return html;  
       _html = html;  
       _currentCharIndex = -1;  
       while (!Eof)  
       {  
         var ch = ReadNext();  
         if (_state == State.InTagName)  
         {  
           // Self closing  
           if (ch == '/' && PeekNext() == '>')  
           {  
             ReadNext();  
             _state = _openTags.Count > 0 ? State.InsideTag : State.None;  
             continue;  
           }  
           if (ch == ' ' || ch == '>')  
           {  
             _pendingTagName = _html.Substring(_pendingTagNameStartIndex, _currentCharIndex - _pendingTagNameStartIndex);  
           }  
           if (ch == ' ')  
           {  
             _state = State.InAttributes;  
           }  
           else if (ch == '>')  
           {  
             _openTags.Push(_pendingTagName);  
             _state = State.InsideTag;  
           }  
         }  
         else if (_state == State.InsideTag)  
         {  
           if (ch == '<' && PeekNext() == '/')  
           {  
             _currentEndTagStartIndex = _currentCharIndex;  
             ReadNext();  
             _state = State.InEndTag;  
             continue;  
           }  
           if (ch == '<')  
           {  
             _state = State.InTagName;  
             _pendingTagNameStartIndex = _currentCharIndex + 1;  
             continue;  
           }  
         }  
         else if (_state == State.InEndTag)  
         {  
           if (ch == '>')  
           {  
             _openTags.Pop();  
             _state = _openTags.Count > 0 ? State.InsideTag : State.None;  
           }  
         }  
         else  
         {  
           if (ch == '<')  
           {  
             _state = State.InTagName;  
             _pendingTagNameStartIndex = _currentCharIndex + 1;  
             continue;  
           }  
         }  
       }  
       // Broken start tag  
       if (_state == State.InTagName || _state == State.InAttributes)  
       {  
         _html = _html.Substring(0, _pendingTagNameStartIndex - 1);  
       }  
       // Broken end tag  
       else if (_state == State.InEndTag)  
       {  
         _html = _html.Substring(0, _currentEndTagStartIndex);  
       }  
       var sb = new StringBuilder();  
       sb.Append(_html);  
       while (_openTags.Count > 0)  
       {  
         var tag = _openTags.Pop();  
         sb.Append("</" + tag + ">");  
       }  
       return sb.ToString();  
     }  
     private char ReadNext()  
     {  
       return Eof ? '\0' : _html[++_currentCharIndex];  
     }  
     private char PeekNext()  
     {  
       return Eof ? '\0' : _html[_currentCharIndex + 1];  
     }  
     enum State  
     {  
       None, InTagName, InAttributes, InsideTag, InEndTag  
     }  
   }  

And you may refer it as below;

 new TagCloser().CloseTags(c.headerLinkDisplay160.Trim())  

Happy coding...