Wordpress - Redirect based on IP address - php

I'm making a Wordpress function that redirects the user to a different page when they're on a certain IP address. The code however does not function properly and I can't get it to work.
function ip_based_login()
{
if ($_SERVER['REMOTE_ADDR'] == '95.81.51.134')
{
wp_redirect("examplewebsite.com/login2"(site_url($wp->request)));
}
else
{
exit;
}
}

you dont really need to write a code for that
The best thing about wordpress is that there are tons of stuff already available
You can use the following plugin for your requirements
https://wordpress.org/plugins/shortcode-redirect/

site_url expects a path to attach to the site url(eg: site_url('hello') => https://example.com/hello.
$wp->request contains the path of the request which means doing site_url($wp->request) will return you the url you are on.
here is a working snippet, just replace $url with the url you want to redirect to.
function ip_based_login() {
$visitor = $_SERVER['REMOTE_ADDR'];
$redirectTo = site_url('login2');
if (preg_match("/95.81.51.134/",$visitor)) {
wp_redirect($redirectTo);
}
exit;
}
keep in mind that placing this snippet in functions.php without hooking it to a specific action can cause an infinite redirect loop.

Related

How to create multi-regional website using wordpress

I'm trying to make a multi-regional website using WordPress. i'm working on url http://localhost/siteone I want when someone come from usa redirect to the localhost/siteone/usa/
I edit the function.php file of wordpress theme with code below, but getting error the url become localhost/siteone/usa/usa/usa/usa
// Detacting user location using ipstack
$json = file_get_contents('http://api.ipstack.com/check?access_key=ACCESSKEY&language=en');
// Converts it into a PHP object
$data = json_decode($json);
$loc = $data->country_code;
//NA = northamerica
//End of Decating user location
if($loc=="NA"){ header("Location: usa/"); }
This works very well sidealone but when I add in function.php in theme file not working and give me a error. what should I do. Should i use some session or anything eles.
It looks like it's trying to redirect multiple times, since it'll check the person's location, then redirect, then after redirecting it'll check again, and redirect again, etc.
What you could do is check whether "/usa" is already in the page URL, and if not, redirect, something like this could work:
if ($loc === "NA" && strpos($_SERVER['REQUEST_URI'],'usa/') === false) {
header("Location: usa/");
}
$_SERVER['REQUEST_URI'] is the URL of the current page, not including the domain.
For languages and create diferents regionals website, I'd recommend you this plugins (pro):
https://polylang.pro/ (just one paid)
enter link description here (anual fee)
Custom code based on language:
<?php
if(pll_current_language() == 'en') {
echo 'Only in english';
} else if(pll_current_language() == 'fr') {
echo 'Seulment en francais';
}
?>
If you prefer control language throught web server, use better: $_SERVER['HTTP_ACCEPT_LANGUAGE']
Link: https://www.php.net/manual/en/locale.acceptfromhttp.php
Regards!

Checking a dynamic referer URL in PHP to prevent access to a page

I am trying to prevent direct access to a webppage, I only want the visitors to be able to view the page if they got referred by a specific URL.
For example, visitor attempts to view the webpage https://example.com/restricted, if the visitor is not coming from https://example.com/redirect/***, the visitor should be redirected to the homepage.
Why am I using the asterix in my referrer URL? It's a dynamic(?) URL. By that I mean, the referrer URL could be https://example.com/redirect/514, but it could also be https://example.com/redirect/58613.
So basically, I would need to have a 'wildcard' to add to the end of the URL, instead of the number at the end. https://example.com/redirect/WILDCARDHERE? (That's what I think)
Note: I will use this code in my Wordpress functions file, I tried the Wordpress stack overflow, but didn't get any response, that's why I'm trying my luck here.
I've tried several things, but I'm pretty clueless.
add_action('template_redirect', function() {
if ( ! is_page(464)) {
return;
}
if (wp_get_referer() == 'https://example.com/redirect/') {
return;
}
wp_redirect( get_home_url() );
exit;
})
Hope someone can provide me with the correct value!
You can use strpos function to check If referer starts with your domain or redirect keyword.
Example usage
$referer = wp_get_referer();
if ($referrer !== false && strpos($referer, "domain") === 0) {
return;
}

Redirecting pages depending on location

Please help me, and be patient since i'm a php virgin.
I'm using Cloudflare and want to redirect every page from outside of Indonesia to a specific page. After a few tries, I can redirect from index.php to each separate destination page.
But the problem comes when I put this redirect code on the destination page. It seems like it loops indefinitely. I want to keep this functionality on, because I don't want a visitor that clicks on a Google search result to end up in the wrong page.
How can I properly check the IP on every page, and if they are from ID, then they will be redirected to index_id.php. And if they are not, they will go to index_ww.php. This without infinite loops, because this code is in both index_id.php and index_ww.php.
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
if ($country_code=="ID"){
$link = 'http://www.myweb.com/index_id.php';
} else {
$link = 'http://www.myweb.com/index_ww.php';
}
header("location:$link");
exit;
Try adding a query parameter onto the end of the destination URL, like ?redirected=1, and always check for that parameter before performing the redirect code. Here's an example:
<?php
if (empty($_GET['redirected'])) {
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
if ($country_code=="ID"){
$link = 'http://www.myweb.com/index_id.php?redirected=1';
}
else {
$link = 'http://www.myweb.com/index_ww.php?redirected=1';
}
header("location:$link");
exit;
}
?>

Successful Login AFTER Failed Login Redirects to wp-login.php Instead of Last Viewed Site Content Page

I am using wp-login with some modifications for a project.
Originally I was using this code in the theme's functions.php to have users redirected to the main page after login and everything worked like a charm:
/* redirect users to front page after login */
function redirect_to_front_page() {
global $redirect_to;
if (!isset($_GET['redirect_to'])) {
$redirect_to = get_option('siteurl');
}
}
add_action('login_form', 'redirect_to_front_page');
Then I began testing the site and realized it would be better if people were redirected to the last page they visited. That way if they were viewing content other than the main page and decided to log in to comment they wouldn't get booted back the main page.
I then altered the code to read like this:
/* redirect users to last page viewed after login */
function redirect_to_last_page() {
global $redirect_to;
if (!isset($_GET['redirect_to'])) {
$redirect_to = $_SERVER['HTTP_REFERER'];
}
}
add_action('login_form', 'redirect_to_last_page');
It works perfectly except in the case of a failed login. In that case they get sent back to wp-login with an error message, which is fine. But when they try to log in a second time and are successful, instead of redirecting back to the site content page they came from they are being redirected back to wp-login with no explanation.
I can see it remembers the instance of wp-login without the error as the referer and that this is creating my problem. But I don't have a good mental picture of how to make this situation conditional, nor has anything I've read made any sense in the context of my problem.
UPDATE:
I got it to work by starting a session and using the strstr() function. This code was added at the very top of the wp-login.php file:
session_start();
$lpage = $_SERVER['HTTP_REFERER'];
if(strstr($lpage, 'login.php') == false)
{
$_SESSION['referrer'] = $_SERVER['HTTP_REFERER'];
}
Then I changed the code in functions.php to this:
/* redirect users to last page viewed after login */
function redirect_to_last_page() {
global $redirect_to;
if (!isset($_GET['redirect_to'])) {
$redirect_to = $_SESSION['referrer'];
}
}
add_action('login_form', 'redirect_to_last_page');
However, I would rather not be making changes to Wordpress core files. So if anyone can suggest a way to move all this into functions.php it would be appreciated. I tried to just add the code into functions.php instead of wp-login but it throws an error.
If someone spots a potential security problem that would also be helpful.

if/else statement redirect not working

I have made this redirect depending on a condition.
I have a CMS, and I'm developing a mobile version of the site. The main CMS is linked to site_url.com while the mobile version is located on a subdomain m.site_url.com. Below function is an edited logout function in the mentioned CMS.
CodonModule is included as a php include in the index.php of the mobile site. This loads all of the CMS' functions basically.
Does the solution I've came up with allow such a redirect that I've done below, or do I require something else to find the subdomain, and based on that information, complete a redirect? At the moment, it will always redirect me to the else argument's link, regardless of where I trigger the script, whether on the subdomain, or the main domain. I'd like therefore to fix the script below, and for the condition to work.
Auth::LogOut triggers the logout process. I then add a redirect for the user to be redirected either to a desktop page (else argument) or mobile version (if they are on the subdomain).
When I did $die(subdomain) just below the $subdomain line, it would print out the name of the domain. Shouldn't it print out m instead for the subdomain, or have I made a mess of this code?
class Logout extends CodonModule
{
public function index()
{
$sub_domain = array_shift(explode(".",$_SERVER['HTTP_HOST']));
if($sub_domain == 'm')
{
Auth::LogOut();
header('Location: http://m.site_url.com/index.php');
}
else
{
Auth::LogOut();
header('Location: '.url('/'));
}
}
}
Try to add session_start(); at the top of the File right below <?php where u defined the index() function, If I'm Right the Sessions didn't even start (IDK), But Try to add it..
Maybe it will work..

Categories