Limit by IP Address

Another method of protecting sensitive data is to limit the display to users accessing from a specific IP or IP range. Although this is a very simple process, it's not the most effective. Most users do not have static IP addresses, and those who do are usually behind a firewall and access the Web via a proxy. When you access via a proxy, a kind of gateway that filters traffic out to the Internet, the remote address is always the same value because it belongs to the proxy and not the specific user attempting to access a Web site.

However, if you're creating a site in a closed environment, adding the following few lines at the beginning of your PHP script will determine the remote IP address and will limit access based on the result it finds:

 <?php //limitbyIP.php $userIP - $_SERVER[REMOTE_ADDR]; if ($userIP != "") {              echo "It's not me, it's $userIP!"; } else {              echo "User is authorized, it's me!"; } ?> 

You can use regular expressions to match a block of IP addresses, in this case, any IP address that begins with 63.196.7. This script actually looks for something that does not match 63.196.7., as evidenced by the use of the ! before the function name.

 <?php //limitbyIPrange.php $userIP = $_SERVER[REMOTE_ADDR]; if (!preg_match("/63.196.7./", "$userIP")) {              echo "You're not in my neighborhood..."; } else {              echo "Welcome, neighbor!"; } ?> 

$_SERVER[REMOTE_ADDR] contains a standard environment variable that is always sent by the machine making the request. The limitbyIP.php script uses, or the default value for localhost, as the only authorized IP address. In that script, if the remote address is not or localhost, the user is not shown any content, and instead the message "It's not me, it's [some IP]" is displayed in the browser.

Although this is a neat trick-and quite speedy, as the script doesn't connect to a database to validate specific users-it loses its value in a production environment given the prevalence of non-static IPs and proxy servers.

In the next chapter, you'll learn how to store information in cookies and sessions, and retrieve that information to provide customized user environments.

PHP Essentials
PHP Essentials, 2nd Edition
ISBN: 1931841349
EAN: 2147483647
Year: 2002
Pages: 74 © 2008-2017.
If you may any questions please contact us: