i'm losing my mind a little bit with this one. I'm new here so please tell me if there's anything else I can provide to help explain myself.
I want to restrict certain pages based on user IP, but the users I want to allow are different in different pages, so I created different functions using the plugin Code Snippets.
The function I'm using is:
function whitelist_ip_PAGE1() {
// Whitelist
$whitelist = array(
'0.0.0.0', //User 1
'0.0.0.0' //User 2
);
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//to check ip is pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
if(!in_array($ip, $whitelist)){
wp_redirect( 'noaccess' );
exit;
}
}
add_shortcode('ip_PAGE1', 'whitelist_ip_PAGE1');
So for different pages, I just clone the Code Snippet, rename the function, change the IP array and the shortcode at the end. I'm then adding each shortcode in the corresponding page. I also created the "noaccess" page displaying user's IP and telling them this IP is not allowed to access the page they requested.
I've tested this in another wordpress site and everything works fine.
But for some reason, in this site I'm trying to implement it, the result is the following:
If user's IP is in the array, they can visit the page. If it's not, they still can access the page but the content is not displayed for them. The redirection just doesn't happen, and I checked the error code, it's this one:
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/mysite.com/httpdocs/wp-includes/class-wp-styles.php:214) in /var/www/vhosts/mysite.com/httpdocs/wp-content/plugins/code-snippets/php/snippet-ops.php(505) : eval()'d code on line 102
So I looked around and I believe the problem is that some content is sent to the browser before the redirection happens, but I can't find what it is. As mentioned, the code itself works fine in another site, so I don't know if it's the theme... (i'm running a basic twenty-twenty-one) or what. Any ideas?
PS: I'm not good at programming, I found and adapted the code with great struggle, so I would like to keep as much of it as possible, cause I don't know if I'll be able to redo the whole thing in a different way. Thank you!