1

i am trying to restrict particular web page using php which should be displayed only to the allowed Ip Addresses and for remaining all IP Address it should not be accessible.

Requirement:

1.The page will be in sub menu list.

2.It should be displayed only to the allowed ip address only

Thank You in advance....

1
  • How are you trying that? Show us your code.
    – fuxia
    Commented Feb 28, 2017 at 12:54

2 Answers 2

1

Haven't specifically done this yet but something similar

In the theme page/post template files you can get post id of current post/page by doing

$currentID = get_the_ID();

Then redirect all traffic not from the specified IPs

$ipArr = array('xx.xxx.xxx.xxx', 'xx.xxx.xxx.xxx');

 if (!in_array(@$_SERVER['REMOTE_ADDR'], $ipArr))
{
    header("Location: http://example.com/myhomepage");
    die();
}
2
  • Thanks for the suggestion... can you tell me why you have used @ in (@$_SERVER['REMOTE_ADDR'], $ipArr)
    – Praveen
    Commented Feb 28, 2017 at 13:02
  • The @ sign is used to suppress error messages and warnings in PHP when prepended. I'm sorry but it shouldn't have been there since it is not always that good of an idea to use. It might cause some frustrations when debugging a piece of code.
    – marwyk87
    Commented Feb 28, 2017 at 18:27
1

You can block the access page for all IPs, but a whitelist.

function page_ip_restriction() {
    if(is_page('yourpage'))
    {
        // Whitelist
        $whitelist = array(
            '127.0.0.1',
            '127.0.0.2',
            '127.0.0.3',
        );

        // Check if current user IP is out of the whitelist, then redirect to home
        if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist))
        {
            wp_redirect(home_url(), 403); // 403 -> Forbiden access
            exit();
        }
    }
}
add_action('init', 'page_ip_restriction', 10);

For your submenu, you have two ways, the wordpress one, or a css exclusion. But IMO, WordPress menus are really heavy to use.

If you want better IP address tracking, use a librairy.

Hope it's help you !

4
  • thanks... but i want block all ip addresses and wanted to allow only some ip address to access
    – Praveen
    Commented Feb 28, 2017 at 13:03
  • '127.0.0.1', '127.0.0.2', '127.0.0.3' are the only allowed here.
    – Elex
    Commented Feb 28, 2017 at 13:07
  • i tried and used the above code but it didn't worked i kept the above code in functions.php @Jean-Rémi LARCELET
    – Praveen
    Commented Mar 2, 2017 at 6:48
  • What do you get, something like a blank page ?
    – Elex
    Commented Mar 2, 2017 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.