Infinite loop on Geo Redirect - infinite-loop

I have 3 websites for different regions having their own location specific content:
French website: http://dev.logichub.net/demo/fr/
German website: http://dev.logichub.net/demo/de/
Default website: http://dev.logichub.net/demo/
I would like to redirect the visitors to the respective website on the basis of their IP address. For example, if a user lands on http://dev.logichub.net/demo/fr/ from Germany, then he/she must be redirected to German website i.e. http://dev.logichub.net/demo/de/. I would like to implement this same behaviour on all the 3 websites.
I put the following code on the homepage on these 3 websites:
// get visitor IP address and process
$geo_data = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
if ( ! empty( $geo_data ) ) {
switch ( $geo_data['geoplugin_countryCode'] ) {
// redirect French visitors to FR website
case "FR":
echo '<script>window.location.replace( "http://dev.logichub.net/demo/fr/" );</script>';
break;
// redirect German visitors to DE website
case "DE":
echo '<script>window.location.replace( "http://dev.logichub.net/demo/de/" );</script>';
break;
// redirect all others to international website
default:
echo '<script>window.location.replace( "http://dev.logichub.net/demo/" );</script>';
}
}
It works fine exactly like I want except the infinite loop on the redirected website. The visitor is redirected perfectly, but the new website load forever. How can I stop the infinite loop so once visitor redirected to the correct website, no more redirection occurs?

You have to check if the user is on the right domain before trying to redirect. Here's a solution fully made in PHP:
<?php
session_start();
$currentUrl = explode('/', "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
$currentCountry = isset($currentUrl[4]) ? $currentUrl[4] : '';
if(empty($_SESSION['country'])) {
$geo_data = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
if(!empty($geo_data)) {
$country = $geo_data['geoplugin_countryCode'];
$_SESSION['country'] = $country = ($country != 'FR' || $country != 'DE') ? '' : $country;
}
}
if($currentCountry != $_SESSION['country'])
header('Location: http://dev.logichub.net/demo/'.$country);
You could improve this code by getting the current country without searching it in the URL (by defining it in the file, for example), but actually, it should work better.

Related

Redirect to login page if user not logged in but don't redirect googlebot

How can i this? You cannot access the site without a member, but google bot can enter. How can I do this? You cannot access the site without a member, but Google bot can enter. I tried to create a variable and exclude the IP number, but I failed.
It would be best to test by using reverse DNS lookup since User Agent can be spoofed. PHP makes it pretty easy, here's a sample test:
// $ip = $_SERVER['REMOTE_ADDR']; // Use to check the visitor IP
$ip = '66.249.66.1'; // Sample Google IP from their docs
$host_name = gethostbyaddr($ip);
$is_google = strpos($host_name, 'google') !== false ? 'is' : 'is <b>NOT</b>';
echo "<p>$host_name</p>";
echo "<p>IP Address $is_google Google</p>";
Now we can check if the user is logged in and if they are not a google bot. Using the WordPress template_redirect hook is recommended. Add this to your functions.php theme file:
/**
* Redirect the user to login if they are not logged in and not a google bot
*/
function redirect_not_logged_in_not_google() {
$host_name = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if( strpos($host_name, 'google') === false && !is_user_logged_in() ) {
wp_redirect( home_url( '/login/' ) );
die;
}
}
add_action( 'template_redirect', 'redirect_not_logged_in_not_google' );

Redirect to referring url after login in wordpress sub-directory install

I've read couple of previous post here but none of them is working in my case.. Basically, my blogging site is installed in a sub-directory of main website.. Main website in plain php and sub-directory is wordpress.. I allow users to read my blogs only after logged in. So, the thing is I frequently share the blog links in facebook where lots of new users come in from the link.
Main website is installed in => example.com
wordpress sub-directory in => example.com/blog
As I'm using the custom template login page (login.php), whenever the non-logged in users comes- first they are redirected to example.com/blog/login. I'm using this function to redirect to login page:
function redirect_user() {
if ( ! is_user_logged_in() && !is_page( 'login' ) ) {
$return_url = esc_url('http://www.example.com/blog/login');
wp_redirect( $return_url );
exit;
}
}
add_action( 'template_redirect', 'redirect_user' );
It redirect fine, without problem.. Then the main task of redirecting to the referrer url, I'm using the similar code above to direct to every logged in users to the referring url irrespective or post or page.. Again in the functions.php
if(is_user_logged_in())
wp_redirect('' . $_SERVER["REQUEST_URI"]);
I thought they would work but can't seems to understand that referring url is appending the sub-directory name... For example; the above code show result as:
example.com/blog/blog/blabla-blahblah.. You see the directory name is doubling..
Anyone's advice would be highly appreciated..
Having your WordPress website in a subdirectory will have no impact on what you are trying to do. Why? Because WordPress knows where it's located at, as you set the home and site URLs either in your wp-config.php file like this:
define('WP_HOME','http://example.com/blog');
define('WP_SITEURL','http://example.com/blog');
or by setting both in the Settings > General admin page:
Therefore, all of the rewrites and URLs will be relative to these URLs.
Handling the Referer Capture
When someone comes to one of the pages on your site, you want to capture that original request and add it as a redirect_to= query arg. Then you can send them to the login page.
add_action( 'wp', 'redirect_to_login_if_unauthorized', 3 );
/**
* Redirect the user to the login, but capture the original
* referer and add to the query arg.
*
* #since 1.0.0
*
* #param WP $wp_environment Current WordPress environment instance (passed by reference).
*
* #return void
*/
function redirect_to_login_if_unauthorized( WP $wp_environment ) {
if ( is_user_logged_in() ) {
return;
}
if ( $wp_environment->request ) {
$request = home_url( add_query_arg( array(), $wp_environment->request ) );
} else {
$request = home_url();
}
$redirect = home_url() . '/wp-login.php?redirect_to=' . $request;
wp_redirect( $redirect );
die();
}
How it Works
The event wp fires in wp-includes/class-wp.php. It passes the object instance of the WordPress environment setup. Here is the code from WordPress Core:
do_action_ref_array( 'wp', array( &$this ) );
This environment object has a property that we want called request. That property has the URL request (minus the blog's home URL).
If the $wp_environment->request has a value, we'll add it to the home URL as a query arg; else, we just want the home URL. Now we have the referer.
Next, you create the redirect URL, which has the path to the login page and the redirect_to query arg.
An Example
Let's say you have a post called Why I Love WordPress and the path to that post is http://example.com/blog/why-i-love-wordpress.
The value in the $request would be:
http://example.com/blog/why-i-love-wordpress
and the redirect URL would be:
http://example.com/blog/wp-login.php?redirect_to=http://example.com/why-i-love-wordpress
Upon logging in, the user is then redirected to the original page request.
Tip - Handle Logout Too
You'll want to think about the pathing after a user logs out and then build a proper request to it too.

User authentication through wp_signon(); help needed

I use form to send POST request to a page and to login user with wp_signon() in order to authenticate user to my wordpress installation as described in WP documentation:
$creds = array();
$creds['user_login'] = $_POST["user-login"];
$creds['user_password'] = $_POST["user-password"];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
After this little piece of code I'm checking if user was logged in:
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }
But I got FAIL! all the time. Then after sniffing around I found this little trick:
wp_set_current_user( $user );
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }
I've got SUCCESS on this one but when I leave this page I got FAIL again and again.
Can anyone explain me how to login user with wp_signon() without logging her out after page is changed or reloaded or whatever.
I've got desirable result when I go to /wp_admin and login with WP's default login form. I can navigate through every page of my WP site remaining logged-in all the time. But when I try to do this outside the default form with wp_signon(); I FAIL!.
Maybe I use it wrong? Guide me! PLEASE!
It was my mistake. I used the whole structure on my localhost server which for some reason didn't allow wordpress to work correctly. After I've uploaded the template into an external server I've got this working.
Sorry for bothering! It won't happen again ...

URL redirection not working properly: genetates the url http://domain.com/domain.com/

I have a WordPress site in two languages (Hebrew and English) and I need it to redirect according to browser language. I'm using qTranslate plugin to create the content in both languages. This plugin also has a redirection functionality but it creates a redirection only for the homepage and I need the redirection to happen for internal pages as well as the homepage.
Another developer wrote this code for me to create the redirection, but for some reason it creates a funny redirect. It happens only when switching language to Hebrew, then leaving the site and trying to enter directly to http://domain.com/en/ and it redirects you to http://domain.com/domain.com/ (Does not happen when switching to english).
I tried playing with the "header (Location: )" that creates the redirection for Hebrew, but couldn't figure out how to make it work - I tried using the full path instead of relative path, or removing the "/" between $_SERVER['SERVER_NAME'] and $_SERVER['REQUEST_URI'] but got recursive url or url with double "/" (http://domain.com// and also for internal pages http://domain.com//page).
The url structure is:
domain.com/ for Hebrew
domain.com/en/ for English
and when switching language then the parameter $lang=en or $lang=he is being added.
Hope this makes sense, and thanks a lot!
this is the code that is responsible for the redirection:
<?php
if (!isset($_COOKIE["uln"])) :
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
setcookie('uln', $lang, time()+86400*365, '/', '.domain.com'); // cookie stored for a year
$_COOKIE['uln'] = $lang;
endif;
//if lang=(value) is not empty
if(isset($_GET['lang'])) {
$lang = $_GET['lang'];
setcookie('uln', $lang, time()-1, '/', '.domain.com'); //this unsets the cookie for random language selection
//set the cookie "uln" again with the selected language.
setcookie('uln', $lang, time()+86400*365, '/', '.domain.com'); // cookie stored for a year
$_COOKIE['uln'] = $lang;
}
if(($_COOKIE["uln"]) == "en") {
$matched = strncmp("/en/", $_SERVER['REDIRECT_URL'], 3);
if ($matched !== 0) :
header('Location: /en'.$_SERVER['REQUEST_URI']);
endif;
} elseif(($_COOKIE["uln"]) == "he") {
$matched = strncmp("/en/", $_SERVER['REDIRECT_URL'], 3);
if ($matched === 0) :
header('Location: '.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);
endif;
}
?>
instead of
header('Location: '.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);
try
header("Location: http://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}");
URLs, especially those in Location headers, should include a protocol and domain name. I believe relative URLs in Location headers are a violation of the HTTP RFCs.
By omitting a protocol, you're unintentionally specifying a relative url instead of an absolute one.
Edit: REQUEST_URI is already prefixed with a / so including one in the concat is unnecessary.
You're missing an http:// somewhere, probably in the English -> Hebrew redirect code.
Change
header('Location: '.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);
to
header('Location: http://'.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);

Configuring IIS to pass POST data through 301 redirect

I am currently working on a site hosted on IIS 7 for a client, and the site is configured to redirect any naked domain requests to redirect to the 'www' subdomain. However, this is causing a problem with some of the forms on the site, which point to the naked domain. When the form is submitted, it forwards to the correct page on the 'www'subdomain, but the POST parameters are lost - the page on the 'www' subdomain is requested with an HTTP GET request regardless of the request type of the original request.
I am very unfamiliar with IIS and its configuration, so I imagine that this is something simple to fix, but how can I ensure that POST requests are preserved over a 301 redirect on IIS?
If you post via 301 the post data will be removed. You need create eq php script that re-parse data and send again
/* FOR test */
$_POST['value'] = 123;
$_POST['key'] = 888;
# Online $_POST check
$_GET['redirect'] = 'https://posttestserver.com/post.php';
/* END: FOR test */
if( filter_var($_GET['redirect'], FILTER_VALIDATE_URL) ) {
if ( is_array($_POST) ) :
echo '<form method="post" action="'. $_GET['redirect'] .'" name="f">';
foreach($_POST as $i => $v){
echo '<input type="hidden" name="'. $i .'" value="'. $v .'">';
}
echo '</form> <script> document.f.submit(); </script>';
else : // IF _GET
$tmp = $_GET['redirect'];
unset($_GET['redirect']);
$ur = http_build_query($_GET);
header("Location: " . $tmp . '?' . $ur);
endif;
}

Resources