Monday, June 13, 2016

Restricting admin page to be accessed from only certain ip addresses

If you want to apply someting more secure than just a password to access your admin page you can restrict your admin page to be accessed from only one ip address.

First you should know your ip address. If you dont know you can run this script: 
  <?php
  echo "IP anda : " . $HTTP_SERVER_VARS[REMOTE_ADDR];
?>

Then in the admin area, for example in "administrator/index.php", insert this script on the topmost:

<?php
  $ip = "127.0.0.1" // your ip
  if($HTTP_SERVER_VARS[REMOTE_ADDR] != $ip) {
  header("location: ../index.php");
  } else {
  Setcookie("ip",$ip); }
?>

Then for each file in the admin area, insert this script:

<?php
  $ip = $_COOKIE[ip]; // call cookie ip
  if($HTTP_SERVER_VARS[REMOTE_ADDR] != $ip) {
  echo "You dont have right to access this page!";
  } else {
  // your menu here
  }
?>

Please remember to call cookies or session for your admin username and pasword as well. The example above only call cookie for ip address. 

You may want to apply more than one ip address and store the ip address list in database as following:

CREATE TABLE `web`.`tb_admin` (
  `id` BIGINT( 20 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `ip` VARCHAR( 30 ) NOT NULL
  ) 
 
  INSERT INTO `web`.`tb_admin` (  `id` ,  `ip`  )
  VALUES (1 , 127.0.0.1);

Config.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$konek = mysql_connect($host,$user,$pass) or die("Check host,user,or password");
$select_db = mysql_select_db("web");
?>

Then in the index.php in the admin folder, you can insert this script:

index.php

<?php
  include("config.php");
  $ip = $HTTP_SERVER_VARS[REMOTE_ADDR];
  $valid_ip = mysql_query("SELECT * FROM tb_admin WHERE ip=$ip");
  if (!= $valid_ip) {
  echo "You dont have permission to access this page!";
  } else {
  // your menu goes here...
  }
?>