Redirect to current URL, but replace string? - php

So I have a working redirect that currently sends customers to my homepage if they select a different city from a drop-down select. This changes some custom user meta data and uses that to determine when a redirect should occur. Simple enough.
if ( is_user_logged_in() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com');
}
if ( is_user_logged_in() && $metalocation_display == 'chicago' && strpos($url,'chicago') == false) {
header('Location: example.com/chicago/');
}
What I would like to achieve is, if the customer is on the shop page, the I can redirect them to the CURRENT page they are on (not the homepage), but simply replace the city name with strpos or something similar... basically call the current URL and only replace the name of the city, regardless of where in the URL that string is.
Something like:
if ( is_user_logged_in() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com');
}
if ( is_user_logged_in() && $metalocation_display == 'chicago' && strpos($url,'chicago') == false) {
header('Location: GET CURRENT URL & REPLACE CURRENT CITY (using a list of cities) OR ADD 'CHICAGO' AFTER DOMAIN IF ONE DOESN'T EXIST ');
}
Any advice?

Something like this should work (remove type declarations if using < PHP 7+):
function get_current_url( array $cities, string $target_city ): string {
// Get protocol.
$url = ( $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://' );
// Get URL parts.
$port = $_SERVER['SERVER_PORT'];
$name = $_SERVER['SERVER_NAME'];
$uri = $_SERVER['REQUEST_URI'];
// Check all cities in the array and replace if found.
foreach ( $cities as $city ) {
$uri = str_replace( $city, $target_city, $uri );
}
// Build URL with matching port.
$url .= ( $port !== '80' ? $name . ':' . $port . $uri : $name . $uri );
// Return escaped URL.
return esc_url( $url );
}
And then in your code:
if ( is_user_logged_in() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com');
}
// Fill array with possible cities.
$cities = array( 'london', 'new-york', );
if ( is_user_logged_in() && $metalocation_display == 'chicago' && strpos($url,'chicago') == false) {
header('Location: ' . get_current_url( $cities, 'chicago' ) );
}
Obviously be sure to prefix the function though.

Related

ERR TOO MANY REDIRECTS - When redirecting user based on their selected city

So I have a drop-down select that changes a custom field's value in their user profile based on their selected city. If a user chooses 'Detroit' for example, Detroit is then stored in their profile and that data is then used to redirect the customer based on their selection.
An issue I am running into seems to be if the customer selects a NEW different city on the homepage, or on a page deeper in the directory they get met with the TOO MANY REDIRECTS loop.
I understand WHY, I just can't seem to see where my issues are that are causing it.
Any help appreciated. Even if there is an easier, cleaner way to accomplish this.
add_action('wp_footer' , 'city_redirects');
function city_redirects() {
global $current_user;
global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) );
wp_get_current_user(); // wordpress global variable to fetch logged in user info
$userID = $current_user->ID; // logged in user's ID
$metalocation_display = get_user_meta($userID, 'location_select', true); // stores the value of logged in user's meta data for 'test'.
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
//chicago REDIRECTS
if ( is_user_logged_in() && $metalocation_display == 'chicago' && strpos($url,'chicago') == false) {
header('Location: example.com/chicago/' . $_SERVER['REQUEST_URI']);
}
if ( is_user_logged_in() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com/' . str_replace('chicago', '', 'example.com/chicago') . $_SERVER['REQUEST_URI']);
}
if ( is_user_logged_in() && is_front_page() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com/');
}
//detroit REDIRECTS
if ( is_user_logged_in() && $metalocation_display == 'detroit' && strpos($url,'detroit') == false) {
header('Location: example.com/detroit/' . $_SERVER['REQUEST_URI']);
}
if ( is_user_logged_in() && $metalocation_display !== 'detroit' && strpos($url,'detroit') == true) {
header('Location: example.com/' . str_replace('detroit', '', 'example.com/detroit') . $_SERVER['REQUEST_URI']);
}
if ( is_user_logged_in() && is_front_page() && $metalocation_display !== 'detroit' && strpos($url,'detroit') == true) {
header('Location: example.com/');
}
//philadelphia REDIRECTS
if ( is_user_logged_in() && $metalocation_display == 'philadelphia' && strpos($url,'philadelphia') == false) {
header('Location: example.com/philadelphia/' . $_SERVER['REQUEST_URI']);
}
if ( is_user_logged_in() && $metalocation_display !== 'philadelphia' && strpos($url,'philadelphia') == true) {
header('Location: example.com/' . str_replace('philadelphia', '', 'example.com/philadelphia') . $_SERVER['REQUEST_URI']);
}
if ( is_user_logged_in() && is_front_page() && $metalocation_display !== 'philadelphia' && strpos($url,'philadelphia') == true) {
header('Location: example.com/');
}
}

GET URL from pages that access my Image

Imagine any webpage ex: example1.com/something... using this html:
<img src="http://www.example2.com/controller/showImage" >
My controller in web2.com is something like:
function showImage() {
getIP(); //return USER IP (working)
getURL(); //return example1.com/something... (not working it returns always 'http://www.example2.com/controller/showImage')
addMetricsSQL($ip, $url); //add ip and url in database (working)
header('Content-Type: image/jpeg'); //headers
readfile($this->$path_img); //a path
}
My current function is:
public function getURL() {
$ssl = ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' );
$sp = strtolower( $_SERVER['SERVER_PROTOCOL'] );
$protocol = substr( $sp, 0, strpos( $sp, '/' ) ) . ( ( $ssl ) ? 's' : '' );
$port = $_SERVER['SERVER_PORT'];
$port = ( ( ! $ssl && $port=='80' ) || ( $ssl && $port=='443' ) ) ? '' : ':'.$port;
$host = ( false && isset( $_SERVER['HTTP_X_FORWARDED_HOST'] ) ) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : ( isset( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : null );
$host = isset( $host ) ? $host : $_SERVER['SERVER_NAME'] . $port;
return $protocol . '://' . $host . $_SERVER['REQUEST_URI'];
}
But like I said, it only returns example2.com/controller/showImage
My questions:
Is posible to get the right URL(in this case
example1.com/something...) using PHP?
How the getURL() function should be?
Thanks in advance
It was painfull but the answer to my question is:
public function getURL() {
return getenv('HTTP_REFERER', true) ?: getenv('HTTP_REFERER');
}
HTTP_REFERER Makes all the magic.

Protect under-developpement Website / Custom URL per user and store IP

I want to protect a page under developpement. The problem is that people are sharing that link. I'd like to manually give a custom link to the users, store the IP they use and then prevent the link being reused on a different IP. I'm using wordpress, and It's the entire site i'd like to protect. Also, is there a way to track who shared the URL?
Exemple :
I'd give a friend this http://exemple.com/abc, that link works as long as the user is on the IP that was first used. If that user shares that link to someone else or another IP tries to access the site using the URL I'd like to log it somehow.
I'll give you some basic advises, since this is relatively complicated and I don't have the time to write all of the code :) .
First you need to add a plain admin page - on this page initially you want to have a <form> with a text field and a submit field. The text field will be where you enter the page URL that you want to share.
You will also have an option stored in the database(we will create that later). It should be an array, to which you will later add the URL's.
Once you submit the URL you will create a nonce for this URL - it must be unique for it(you can use uniqid() for instance). You will then store the URL in an array like this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$urls = get_option( 'my_custom_links', array() );
$id = uniqid();
$urls[ $id ] = array(
'url' => $_POST['my_url'],
'ip' => '',
);
// Update the links.
update_option( 'my_custom_links', $urls );
}
$urls = get_option( 'my_custom_links', array() );
// Display the form here...
// Display the URL's data
foreach ($urls as $id => $data) {
echo '<p>URL: <strong>' . $data['url'] . '</strong><br />Share URL: <strong>' . add_query_arg( 'n', $id, home_url( '/' ) ) . '</strong>' . ( $data['ip'] ? '<br />Accessed from IP: <strong>' . $data['ip'] . '</strong>' : '' ) . '</p>';
}
Then you just need to add a function that will check if a user is allowed to view a specific URL, like so(add the code to your functions.php):
function my_site_protection() {
global $pagenow;
// If we're not on admin or login page and the user is not logged-in
if ( ! is_admin() && 'wp-login.php' != $pagenow ) {
$login_redirect = true;
if ( isset( $_GET['n'] ) && $_GET['n'] ) {
$n = $_GET['n'];
$urls = get_option( 'my_custom_links', array() );
$data = isset( $urls[ $n ] ) ? $urls[ $n ] : false;
if ( $data ) {
if ( ! $data['ip'] || $data['ip'] == $_SERVER['REMOTE_ADDR'] ) {
// If no IP is set, set it and update the option
if ( ! $data['ip'] ) {
$urls[ $id ]['ip'] = $_SERVER['REMOTE_ADDR'];
update_option( 'my_custom_links', $urls );
}
if ( add_query_arg( 'n', $id, $data['url'] ) == curPageURL() ) {
// Don't redirect if we're on the correct page
$login_redirect = false;
} else {
// Redirect the user to the proper URL
wp_redirect( add_query_arg( 'n', $id, $data['url'] ) );
exit;
}
}
}
}
// Redirect user to log-in screen
$login_redirect && auth_redirect();
}
}
add_action('init', 'my_site_protection', 1);
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
You'll have to figure-out the rest on your own, but I gave you most of the stuff, so if you look around a bit, you'll be able to accomplish that.
PP: I haven't tested the code, but in theory it should work - tell me if some part of it doesn't work.

PHP Get URL with Parameter

I want to get a URL and its parameters. Example:
www.someweb.com/somepage.php?id=10
How to get only somepage.php?id=10?
I'm already tried REQUEST_URI and PHP_SELF but it only gives me www.someweb.com/somepage.php or somepage.php. What I want to is just the page name and its parameter(s).
basename($_SERVER['REQUEST_URI']);
This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10).
for complette URL with protocol, servername and parameters:
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'];
$url = $base_url . $_SERVER["REQUEST_URI"];
$_SERVER['PHP_SELF'] for the page name and $_GET['id'] for a specific parameter.
try print_r($_GET); to print out all the parameters.
for your request echo $_SERVER['PHP_SELF']."?id=".$_GET['id'];
return all the parameters echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
echo "The current page is ".curPageName()."?".$_SERVER['QUERY_STRING'];
This will get you page name , it will get the string after the last slash
Here's probably what you are looking for: php-get-url-query-string. You can combine it with other suggested $_SERVER parameters.
Here's a very thorough function I use to get the full URL:
function get_full_url( bool $include_query = true ) {
$protocol = ( ! empty( $_SERVER['HTTPS'] ) && strtolower( $_SERVER['HTTPS'] ) !== 'off' )
|| ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && strtolower( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) === 'https' )
|| ( ! empty( $_SERVER['HTTP_FRONT_END_HTTPS'] ) && strtolower( $_SERVER['HTTP_FRONT_END_HTTPS'] ) !== 'off' )
|| ( isset( $_SERVER['SERVER_PORT'] ) && intval( $_SERVER['SERVER_PORT'] ) === 443 ) ? 'https' : 'http';
$uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return $include_query ? $uri : str_replace( '?' . $_SERVER['QUERY_STRING'], '', $uri );
}

PHP error page problem

I can't figure out why this script isn't working.
<?php
if (($_GET['p'] != 'index') &&
($_GET['p'] != 'reg') &&
($_GET['p'] != 'login') &&
($_GET['p'] != 'ad') &&
(!isset($_GET['p']))):
?>
<?php endif; ?>
I want to not display the error page if the $_GET is not set, which in my experience (!isset($_GET['p'])) should do.
If $_GET['p'] is not set, you can't check $_GET['p'] != 'index' and all the others. You'll have to check if it's set first:
<?php if(
! isset( $_GET['p'] ) ||
($_GET['p'] != 'index' &&
$_GET['p'] != 'reg' &&
$_GET['p'] != 'login' &&
$_GET['p'] != 'ad')
): ?>
A better solution would be to put all those values in an array, and check if $_GET['p'] is in the array:
<?php if(
! isset( $_GET['p'] ) ||
! in_array(
$_GET['p'],
array('index', 'reg', 'login', 'ad')
)
): ?>
EDIT:
Now that you provided some more info, here's what you should do:
if ( ! isset($_GET['p']) )
{
// We're at the index page, so don't display anything
}
else
{
if ( in_array( $_GET['p'], array('index', 'reg', 'login', 'ad') ) )
{
// Display your content window
}
else
{
// $_GET['p'] is not a valid value, display error
}
}
Your condition makes no sense. You're checking for 3 possible values of $_GET['p'] and then checking if $_GET['p'] is even set. Reverse your logic:
<?php
if(isset($_GET['p']))
{
// display error page
}
else
{
// do something else
}
You can check if $_GET['p'] is set by
if(isset($_GET['p']) {...}
If it's set and not empty then you can check for values that you need to check.
Try this:
<?php
$defaultvalue=0; // for example 0
$p=isset($_GET["p"]) ? $_GET["p"] : $defaultvalue;
if(($p != 'index') && ($p != 'reg') && ($p != 'login') && ($p != 'ad')):
?>

Categories