wp_redirect loop when using geoip - php

I'm getting an endless redirect loop that results in a too many redirects error when trying to redirect a user when detecting a specific country.
What I'm trying to achieve is to add to the end of the request url a param that is the language and redirect to the same page that will result in them viewing the site in their own language.
Here's what I've done:
add_action('template_redirect', 'geoip_redirect');
function geoip_redirect()
{
if (function_exists('geoip_detect2_get_info_from_current_ip')) {
$user_info = geoip_detect2_get_info_from_current_ip();
$country_code = $user_info->country->isoCode;
$request_url = $_SERVER['REQUEST_URI'].'?lang=he';
$url = get_site_url(null, $request_url);
if ($country_code == 'IL') {
wp_redirect($url);
exit();
}
}
}

You need to add a condition like checking for the lang parameter before executing the code otherwise It will keep executing forever.
add_action('template_redirect', 'geoip_redirect');
function geoip_redirect()
{
if (function_exists('geoip_detect2_get_info_from_current_ip')) {
if ( ! isset( $_GET['lang'] ) ) {
$user_info = geoip_detect2_get_info_from_current_ip();
$country_code = $user_info->country->isoCode;
$request_url = $_SERVER['REQUEST_URI'].'?lang=he';
$url = get_site_url(null, $request_url);
if ($country_code == 'IL') {
wp_redirect($url);
exit();
}
}
}
}

Related

How can I redirect without infinite loop in PHP code?

I have two WordPress sites using the multi-site function, the URLs are below:
A: sample.com
B: sample.com/en
I tried to write a code in PHP following these conditions, but when I access the RUL of A:sample.com, a browser(chrome) shows an error.
So would you mind telling me how should I solve this problem?
Thank you in advance.
the conditions for access
The first access is only to [A: sample.com]
Users whose browser language is set to Japanese access to [A:
sample.com]
All users whose browser language setting is not set to Japanese
access [B: sample.com/en]
The errors messages in the browser(chrome)
This page isn’t working
sample.com redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
The code for adding in functions.php
<?php
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang == 'ja') {
$url = get_site_url();
}
header("Location: $url");
exit();
}
?>
Development environment
CentOS (7 x86_64)
Apache (2.4.6 CentOS)
PHP (7.1.33)
wordpress(5.2.5)
Just make below change in your code:
if ($lang != 'ja') {
header("Location: $url");
exit();
}
Edited:
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang != 'ja') {
header("Location: $url");
exit();
}
}

How to add Buy Now button in cs-cart

I'm creating a buy-now button cs-cart add-on. I've created an add-on and I've made the add-to-cart functionality work. But cant redirect it to checkout page. I have used "fn_redirect("checkout")" function for the redirection. And used this function below this:
"fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);"
What should I do for redirection?
Edit:
My controller (buy_now.php)
if ($mode == 'add') {
if (empty($auth['user_id']) && Registry::get('settings.General.allow_anonymous_shopping') != 'allow_shopping')
{
return array(CONTROLLER_STATUS_REDIRECT, "auth.login_form?return_url=" . urlencode($_REQUEST['return_url']));
}
// Add to cart button was pressed for single product on advanced list
if (!empty($dispatch_extra)) {
if (empty($_REQUEST['product_data'][$dispatch_extra]['amount'])) {
$_REQUEST['product_data'][$dispatch_extra]['amount'] = 1;
}
foreach ($_REQUEST['product_data'] as $key => $data) {
if ($key != $dispatch_extra && $key != 'custom_files') {
unset($_REQUEST['product_data'][$key]);
}
}
}
$prev_cart_products = empty($cart['products']) ? array() : $cart['products'];
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
fn_save_cart_content($cart, $auth['user_id']);
$previous_state = md5(serialize($cart['products']));
$cart['change_cart_products'] = true;
fn_calculate_cart_content($cart, $auth, 'S', true, 'F', true);
if (md5(serialize($cart['products'])) != $previous_state && empty($cart['skip_notification'])) {
$product_cnt = 0;
$added_products = array();
if (!empty($added_products)) {
Registry::get('view')->assign('added_products', $added_products);
if (Registry::get('config.tweaks.disable_dhtml') && Registry::get('config.tweaks.redirect_to_cart')) {
Registry::get('view')->assign('continue_url', (!empty($_REQUEST['redirect_url']) && empty($_REQUEST['appearance']['details_page'])) ? $_REQUEST['redirect_url'] : $_SESSION['continue_url']);
}
fn_redirect(Registry::get('config.https_location') . "/checkout");
// $msg = Registry::get('view')->fetch('views/checkout/components/product_notification.tpl');
//fn_set_notification('I', __($product_cnt > 1 ? 'products_added_to_cart' : 'product_added_to_cart'), $msg, 'I');
$cart['recalculate'] = true;
} else {
fn_set_notification('N', __('notice'), __('product_in_cart'));
}
}
unset($cart['skip_notification']);
$_suffix = '.checkout';
}
`
hook template : add_to_cart.post.tpl
{$id = "buy_now_{$product.product_id}"}
<button id="opener_{$id}" name="dispatch[buy_now.add..{$product.product_id}]" class=" vs-button buynow_btn_">Buy Now</button>
I'd consider putting your fn_redirect("checkout") code into an if/else statement to see what's happening with it.
If you have this code:
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
Then surely you can put the redirection to the checkout page underneath it?
$redirect_url = "http://testcheckout.com?test=test"; //change this!
$errorMessage = "I should have redirected already....";
if (!empty($redirect_url)) {
//if it's not empty then it should redirect.
fn_redirect($redirect_url);
//Then put a die statement in here just to check it's not executing
//anything else and you can see if the redirect has a problem:
die(print_r($errorMessage, true ));
}
else {
//otherwise there is a problem with the supplied redirect url (empty)
die(print_r($redirect_url, true ));
}
I'd also take a look at this page which might help more:
http://forum.cs-cart.com/topic/6873-direct-buy-button/
Hope that helps!

unable to redirect on wp-admin page

I m facing a problem while implementing my captcha code on the wp-login.php.
I want to redirect on wp-admin page of my website when the captcha code maches. Is there a way to redirect on wp-admin page??
my code is :
function captcha_login_check($url) {
if (isset($_POST["security_check"]))
{
$code = str_decrypt($_POST["security_check"]);
if (!( $code == $_POST['security_code'] && !empty($code) ))
{
wp_clear_auth_cookie();
return $_SERVER["REQUEST_URI"];
?>
<span style="color:red">
Error, the Security Code does not match. Please Try Again.
</span>
<br>
<?php
}
else
{
$url = $_SERVER['HTTP_HOST']."/wp-admin/";
return $url;
}
}
}
Use like
else
{
$url = $_SERVER['HTTP_HOST']."/wp-admin/";
header('Location:'.$url);
}
Also You can use this
else
{
$url = $_SERVER['HTTP_HOST']."/wp-admin/";
echo ("<script>location.href='$url'</script>");
}

If current URL equals rediectURL do nothing

Hey guys I am trying to build a redirect script in my header.
It contains a variable called $redirect that either equals 0 or 1.
What I want to do is if the variable equals 1 to redirect the user to a specified page.
That works.
The problem I am having is when it reaches the redirected URL it creates a loop.
I tried writing the following code but it does not work. What have I done wrong?
<?php
$redirect = 1;
$host = $_SERVER['HTTP_HOST'];
$self = $_SERVER['PHP_SELF'];
$query = !empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null;
$url = !empty($query) ? "http://$host$self?$query" : "http://$host$self";
$redirectURL = '/protest/cispa.php';
if ( $redirect === 1 ) {
if ( $url === $redirectURL ) {
die();
}
else {
header("Location: $redirectURL");
exit;
}}
?>
As suggested by andrewsi I updated my code to the following at it works:
<?php
$redirect = 0;
$host = $_SERVER['HTTP_HOST'];
$self = $_SERVER['PHP_SELF'];
$query = !empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null;
$url = $self;
$redirectURL = '/protest/cispa.php';
if ( $redirect === 1 ) {
if ( $url === $redirectURL ) {
}
else {
header("Location: $redirectURL");
exit;
}
}
?>
$url = !empty($query) ? "http://$host$self?$query" : "http://$host$self";
$redirectURL = '/protest/cispa.php';
Your $url contains a fully qualified domain name; the redirectURL is just a path. The two are never going to be equal. Try setting :
$url = $self;
(If I'm reading your code correctly)
You could stick a flag in the query string of your redirect. Then, if the flag is present, don't add the redirect.
ex;
http://www.yoursite.com/redirectedto.php?red=1
Now, if red is set, I would not add the redirect.
lee

Redirect is giving me 2 address in the browser bar. So I am getting an error. Can't figure it out

I am getting 2 address in the browser window so I am getting an error. This is on GoDaddy. I'm thinking maybe a change in the php might fix it because it seems to be bringing up the domain the redirect is coming from.
Example:
my site.com - trying to redirect to an external site after the submit button in the form is submitted.
It redirects me to:
http://www.mysite/ http://external_site
instead of just: external_site.com
Any help would be great as I am totally lost on this…
The redirect is in a hidden field in a form. It is using GoDaddy's php which is below:
<?php
$request_method = $_SERVER["REQUEST_METHOD"];
if($request_method == "GET"){
$query_vars = $_GET;
} elseif ($request_method == "POST"){
$query_vars = $_POST;
}
reset($query_vars);
$t = date("U");
$file = $_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t;
$fp = fopen($file,"w");
while (list ($key, $val) = each ($query_vars)) {
fputs($fp,"<GDFORM_VARIABLE NAME=$key START>\n");
fputs($fp,"$val\n");
fputs($fp,"<GDFORM_VARIABLE NAME=$key END>\n");
if ($key == "redirect") { $landing_page = $val;}
}
fclose($fp);
if ($landing_page != ""){
header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
} else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
?>
Remove $_SERVER["HTTP_HOST"] in the first header ...
<?php
/* above your code */
if ($landing_page != ""){
header("Location: $landing_page"); // If the http:// is missing don't forget to add it
} else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
?>

Categories