If current URL equals rediectURL do nothing - php

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

Related

wp_redirect loop when using geoip

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();
}
}
}
}

Detect if URL equals to value and preforme action

I want to make action if the current url only equals to this: https://www.example.co.il/index.php?id=1000&2222
$url = 'https://www.example.co.il/index.php?id=1000';
if(strpos($url,'&2222'))
{
// Do something
echo "2222";
}
else
{
// Do Nothing
}
To exactly do what you are asked, try this
//actual link (http or https)
$actualUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url = 'https://www.example.co.il/index.php?id=1000';
if($actualUrl === $url) {
//do something
}
But if you just want to retrieve the id :
$id = $_GET('id');
//return 1000 in your case
You're able to read the parameters in the URL using the $_GET object. It lists the keys and values in the querystring, i.e. in your example,
https://www.example.co.il/index.php?id=1000
if you use:
print $_GET['id'];
you'll see 100.
so you could simply check for the existence of the key 2222:
if (isset($_GET['2222'])) { /** do something **/ }
bear in mind, this is only the case if you're actually reading a URL the script is running on.
your method of searching for a string within the URL is appropriate if you simply want to match a value in a string, whether its a URL or not.
USE THIS
// Assign your parameters here for restricted access
$valid_url = new stdClass();
$valid_url->scheme = 'https';
$valid_url->host = 'www.example.co.il';
$valid_url->ids = array(1000,2222);
$url = 'https://www.example.co.il/index.php?id=1000&2222';
$urlinfo = parse_url($url); // pass url here
$ids = [];
parse_str(str_replace('&', '&id1=', $urlinfo['query']), $ids);
if($urlinfo['scheme'] == $valid_url->scheme && $urlinfo['host'] == $valid_url->host && count(array_intersect($valid_url->ids, $ids)) == count($valid_url->ids)){
echo 'valid';
// Do something
}else{
echo 'in valid';
// error page
}

Storing Session data Fails, due to a following redirect

I want to store session data right before a 302 redirect occurs, to the same page, only without some of the original request parameters.
for example:
Visitor goes to domain.com/?ab_saveme=hey
hey value will get stored
Visitor will get redirected to domain.com/
Page will output hey
This is the code I came with, it does the redirect, but it doesn't manage to store the value (hey is not being outputed).
Without the redirect block, it does store it correct.
<?php
session_start();
session_name("hello");
$_SESSION['cache']=$_GET['ab_saveme']; // store the `saveme` value
// begin self redirect code
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass#" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = !empty($parsed_url['query']) ? '?' . trim($parsed_url['query'], '&') : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
function strip_query($url, $query_to_strip) {
$parsed = parse_url($url);
$parsed['query'] = preg_replace('/(^|&)'.$query_to_strip.'[^&]*/', '', $parsed['query']);
return unparse_url($parsed);
}
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$new_url = (strip_query($url, 'ab')); # or whatever query you want to strip/keep
$filtered = array_filter(array_keys($_GET), function($k) {
return strpos($k, 'ab') === 0;
});
if ( !empty($filtered) ) {
header ("Location: $new_url");
}
// end self redirect code
echo $_SESSION['cache']; // needs to echo original `saveme` value
echo session_id();
if (is_writable(session_save_path()))
{
echo "writable";
}
?>
Edit:
Thanks to Zimmi, I noticed I was re-storing a null value.
Is the best practice to handle this is change:
$_SESSION['cache']=$_GET['ab_saveme']; // store the `saveme` value
into:
if (!empty($_GET['ab_saveme'])) {
$_SESSION['cache']=$_GET['ab_saveme']; // store the `saveme` value
}
Or is there a better way? as I might have to do this for various parameters (such as ab_1,ab_2)

PHP Multi URL Redirector with Array

Im trying to create a php to redirect multiple urls with an specific ID for example
mysite.com/url.php?id=1
id=1 will automatically redirect to www.google.com
mysite.com/url.php?id=2
id = 2 will automatically redirect to www.bing.com
successively ...
I think that an array can simplify it
i will apreciate your answers.
Thanks
If you want to use a static array, then use the following code:
<?php
$sites = array(
1 => 'http://domain.tld';
2 => 'http://anotherdomain.tld';
);
if (isset($_GET['id']) && array_key_exists($_GET['id']), $sites) {
header('location: ' . $sites[$_GET['id']]);
} else {
// 404?
}
?>
You can use something like this:
<?php
$id = isset($_GET['id']) ? $_GET['id'] : '';
$id = (int)(trim($id));
switch($id){
case 1:
header("Location: http://www.google.com/");exit;
break;
case 2:
header("Location: http://www.bing.com/");exit;
break;
default:
header("Location: http://www.default.com/");exit;
break;
}
?>

$_SERVER['REQUEST_URI']

I discovered my own error, can't understand why some down voted. See first comment
SOLUTION:
if(!empty($_GET['lang']))
{
$uri = 'http'. ($_SERVER['HTTPS'] ? 's' : null) .'://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$lang_folder = $_GET['lang'];
$ses = $_COOKIE['ccUser'];
$query = mysql_query("UPDATE ".$glob['dbprefix']."CubeCart_sessions SET lang='".$lang_folder."' WHERE sessId='".$ses."'");
header("Location:".substr($uri, 0, -8));
die();
}
where a bit of code is creating "too_many_redirects":
if(!empty($_GET['lang']))
{
$uri = 'http'. ($_SERVER['HTTPS'] ? 's' : null) .'://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$lang_folder = $_GET['lang'];
$ses = $_COOKIE['ccUser'];
$query = mysql_query("UPDATE ".$glob['dbprefix']."CubeCart_sessions SET lang='".$lang_folder."' WHERE sessId='".$ses."'");
header("Location: $uri");
}
I need to GET the URL the visitor was and reload the page after changing the website language.
Any hints folks?
$_SERVER['REQUEST_URI'] includes ?lang=... which results in if statement being true everytime you redirect.

Categories