Board index   FAQ   Search  
Register  Login
Board index PHP PHP General

Check IP and Echo Different Variable

General discussions related to php

Moderators: macek, egami, gesf

Check IP and Echo Different Variable

Postby alkarnur » Wed Jan 30, 2013 4:17 pm

Hello everybody :) PHP amateur and enthusiast here.

I'm hoping you can help with a simple script.
What I want to do is check the IP address of my site's visitor, and if it is equal to a specific IP (e.g., then I want it to echo a link (maybe contained in a variable) and, if it is not equal to that specific IP, then I want to echo another link.

I got hold of a relevant script that checks the IP address of the visitor and echoes it. But where I'm having the most difficulty is checking / comparing the visitor's IP with my pre-determined IP.

Here's the code I got:
Code: Select all
 <title>What is my IP address?</title>
    if (getenv(HTTP_X_FORWARDED_FOR)) {
        $pipaddress = getenv(HTTP_X_FORWARDED_FOR);
        $ipaddress = getenv(REMOTE_ADDR);
echo "Your Proxy IPaddress is : ".$pipaddress. "(via $ipaddress)" ;
    } else {
        $ipaddress = getenv(REMOTE_ADDR);
        echo "Your IP address is : $ipaddress";

I have also found this script to compare a range of IPs
Code: Select all

    // IP Range: -
    // Provided IP:
    $IPStart = explode(".", "");
    $IPFinish = explode(".", "");
    $IPProv = explode(".", "");
    $Between = true;
    for($i = 0; $i < 4; $i++) {
        if($IPStart[$i] > $IPProv[$i] || $IPFinish[$i] < $IPProv[$i]) {
            $Between = false;
    if($Between !== false) {
        echo "Match";
    } else {
        echo "No Match!";


If you can please help that would be awesome :)
New php-forum User
New php-forum User
Posts: 1
Joined: Wed Jan 30, 2013 4:08 pm

Re: Check IP and Echo Different Variable

Postby seandisanti » Fri Feb 08, 2013 1:42 pm

just use a ternary operator...
Code: Select all
echo ($variableHoldingVisitorIP==$variableHoldingIPToMatch)?'<a href="../../UntoldRiches/YoureTheLuckyOne/Oops/IforgotToRestrictIndexingForThisDirectoryWithMyRobotsTxtAndAnyoneCanGoogleItImScrewed/secret.php">Top Secret Page for your eyes only</a>':'I know something you don\'t know';

you can break that up into lines too for readability if you're into that.

Code: Select all
echo (Boolean Condition)?
//true Response
: //or
//false response
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: Check IP and Echo Different Variable

Postby php9 » Fri Feb 22, 2013 2:31 am

Something like this would do it

Code: Select all
$link1= 'http://link1';
$link2 = 'http://link2';

$link = $ipAddress == '' ? $link1 : $link2;

echo '<a href="' . $link . '">My link</a>';
New php-forum User
New php-forum User
Posts: 13
Joined: Fri Feb 22, 2013 2:20 am

Return to PHP General

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.