PHP User Authentication by IP Address

In this article, you will learn how to authenticate a user by IP address using PHP.

If you want to restrict the website or page to certain IP addresses. It might be on the grounds that you have an inner system that has a freely perceptible webpage. You may wish to have certain pages be visible just by a specific machine on the inner system or you want to restrict the page to some static IP. You can easily do it by reading this article.

This process works on determining the IP address of the user. Suppose you want to allow the website to the IP addresses in the range of 123.121.0.1 to 123.121.0.255. In the given example, we have defined an array of the allowed IP addresses that can view the page for this, we have taken three array elements. The array("123", "121", "0") limits the users who can view the page to the users with an IP address in the range of 123.121.0.1 to 123.121.0.255. The current user's IP address is taken by using a global variable '$_SERVER' and stored in a variable '$REMOTE_ADDR'.


<?php
	$allowed_ip = array("123", "121", "0");
	$REMOTE_ADDR = $_SERVER["REMOTE_ADDR"];
	$remote_ip = explode(".", $REMOTE_ADDR);
	$permitted = 1;
	for($i = 0; $i < sizeof($allowed_ip); $i++) {
		if($remote_ip[$i] != $allowed_ip[$i]) {
			$permitted = 0;
		}
	}
	if($permitted == 1) {
		echo 'Welcome, You are authorized to access this page.';
	}
	else{
		echo 'Access Denied';
	}
?>

In the above example, replace the $allowed_ip array values with your allowed IP address. If you want to restrict the page to only one IP address, then pass all the four values of IP address as four elements in $allowed_ip array.





Related Articles

PHP reverse a string without predefined function
PHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP get IP address of visitor
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
JavaScript display PDF in the browser using Ajax call
jQuery loop over JSON result after AJAX Success
PHP review and rating script
jQuery File upload progress bar with file size validation
Print section of page using javascript
Submit a form data without page refresh using PHP, Ajax and Javascript
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP




Read more articles


General Knowledge



Learn Popular Language