RFID Door Access V2.0
 Page :   [ 1 ]    [ 2 ]    [ 3 ]    [ 4 ]    [ 5 ]    [ 6 ]  

Some PHP Code

More or less bare minimum code I am using to get this running.

The idea is to make some "master" cards.  To do this scan a couple cards when the database is empty.  These cards will automatically become "master" cards.  After that if you scan a "master" card then any card scanned for the next 10 seconds will be entered into the system as normal user cards.  Also they access is set for 24 hours a day for all 7 days of the week.  The access times for the cards can be edited in the database.

Directory structure in this example:

./
`-- html
    |-- inc
    |   |-- classes
    |   |   |-- Card.class.php
    |   |   |-- DB.class.php
    |   |   `-- Location.class.php
    |   `-- config.php
    |-- index.php
    `-- wiegand.php

Below is just going to be listings for the files above.  This is just an example of getting barebones functionality.  Some of thes classes have methods etc. that pertain to the web management interface I use.

 

wiegand.php

This file is called by /usr/local/bin/WD and provides the guts of the logic.  I wrote this in PHP because it's more comfortable for me as opposed to doing it in c/c++ :)

<?php 

$dir = __DIR__;
chdir($dir);

include './inc/config.php';

if (!(php_sapi_name() === 'cli')){
	die(1);
}

$rawCode = isset($argv[1]) ? intval($argv[1]) : 0;
$bits = isset($argv[2]) ? intval($argv[2]) : 0;
$locationName = isset($argv[3]) ? $argv[3] : '';
$masterMode = isset($argv[4]) ? intval($argv[4]) : 0;

if (intval($rawCode) && intval($bits) && strlen($locationName)){
		
	$location = Location::getByLocationName($locationName);

	if ($location){

		$card = Card::getByNumber($rawCode, $bits, $masterMode, $location);
	
		if ($card){

			if (intval($card->getIsMaster())){
				exit(5);
			}

			if ($card->openDoor($location)){

				$query  = " insert into " . DB::$DATABASE . ".history (locationCardId) values (";
				$query .= " (select locationCardId from " . DB::$DATABASE . ".locationcard ";
				$query .= " where cardId = " . intval($card->getCardId()) . " ";
				$query .= " and locationId = " . intval($location->getLocationId()) . ") ) ";
				
				$db = DB::Instance();
				
				$db->query($query);
				
				exit(4);
				
			}
		
		}
		
	}
	
}

exit(0);

?>

 

inc/config.php

Just some basic configuration stuff.  Pretty barebones.

<?php 

ini_set('display_errors',0);
error_reporting(0);

if (!(php_sapi_name() === 'cli')){

	if (get_magic_quotes_gpc()) {
		$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
		while (list($key, $val) = each($process)) {
			foreach ($val as $k => $v) {
				unset($process[$key][$k]);
				if (is_array($v)) {
					$process[$key][stripslashes($k)] = $v;
					$process[] = &$process[$key][stripslashes($k)];
				} else {
					$process[$key][stripslashes($k)] = stripslashes($v);
				}
			}
		}
		unset($process);
	}

}

if (!isset($_SERVER['REQUEST_METHOD'])){
	$_SERVER['REQUEST_METHOD'] = '';
}

if ($_SERVER['REQUEST_METHOD'] == 'GET'){
	$_POST = $_GET;
} else if ($_SERVER['REQUEST_METHOD'] != 'POST'){
	$_POST = array();
}

define('BASEDIR', dirname(dirname(__FILE__)));

function auto_loader($class) {
	include BASEDIR . '/inc/classes/' . $class . '.class.php';
}

spl_autoload_register('auto_loader');

if (!(php_sapi_name() === 'cli')){

	$act = isset($_POST['act']) ? $_POST['act'] : '';

	if (($_SERVER['SCRIPT_NAME'] == '/api.php')){
		header('Content-Type: application/json');
	} else {
		session_start();
		header('Content-Type: text/html; charset=utf-8');
	}

}
?>

 

inc/classes/DB.class.php

Simple singleton database class.

<?php

class DB extends mysqli {
	
	public static $DBHOST   = 'localhost';
	public static $DBUSER   = 'YourDBUser';
	public static $DBPASS   = 'YourDBUserPassword';
	public static $DATABASE = 'rfid';

	private static $instance;
	
	public static function Instance(){
	
		if (null === static::$instance) {
				
			static::$instance = new static();
	
			static::$instance->connect(self::$DBHOST, self::$DBUSER, self::$DBPASS, self::$DATABASE);
			
			if (mysqli_connect_error()) {
				die('Connect Error (' . mysqli_connect_errno() . ') '
						. mysqli_connect_error());
			}
			
			static::$instance->query("SET NAMES 'utf8'");
				
		}
	
		return static::$instance;
		
	}
	
	protected function __construct(){
	}
	
	private function __clone(){
	}
	
	private function __wakeup(){
	}

}	
	
?>

 

inc/classes/Location.php

<?php 

class Location{
	
	private $db;
	private $locationName;	
	private $cards;
	
	public function __construct($id = null){

		$this->db = DB::Instance();
		$this->load($id);
		
	}

	private function load($val){
	
		if (is_numeric($val)){
			
			$query = " select * ";
			$query .= " from " . DB::$DATABASE . ".location  ";
			$query .= " where locationId = " . intval($val);
				
			if ($result = $this->db->query($query)) {
				
				if ($result->num_rows > 0){
						
					$row = $result->fetch_assoc();

					$this->setLocationId($row['locationId']);
					$this->setLocationName($row['locationName']);
						
				}

			}		
			
		}	
	
	}
	
	public function setLocationId($val){
	
		$this->locationId = intval($val);
	
	}
	
	public function setLocationName($val){
		
		$this->locationName = $val;
		
	}

	public function getLocationId(){
	
		return $this->locationId;
	
	}
	
	public function getLocationName(){
	
		return $this->locationName;
	
	}
	
	public function getCards(){
	
		$ret = array();
	
		$query = " select lc.locationCardId,lc.cardId,lc.locationId ";
		$query .= " from " . DB::$DATABASE . ".locationcard lc  ";
		$query .= " where lc.locationId = " . intval($this->getLocationId()) . "  ";
		$query .= " order by lc.locationCardId asc ";
		
		if ($result = $this->db->query($query)) {
			if ($result->num_rows > 0){
	
				while($row = $result->fetch_assoc()){
						
					$card = new Card($row['cardId']);
					$card->setLocationCardId($row['locationCardId']);
					$card->setDays(); // this uses the locationcardid to populate an array in the object
								
					$ret[] = $card;
						
				}
	
			}
	
		}
	
		return $ret;
	
	}
	
	public static function getByLocationName($val){
		$locationId = self::locationId($val);
		if(intval($locationId)){
			return new Location($locationId);
		}else{
			return false;
		}
	}
	
	private static function locationId($val){
	
		$db = DB::Instance();
	
		$record = false;
	
		$query  = " select * ";
		$query .= " from " . DB::$DATABASE . ".location ";
		$query .= " where locationName = '" . $db->real_escape_string($val) . "' limit 1 ";

		if ($result = $db->query($query)) {
			if ($result->num_rows > 0){
				$record = $result->fetch_assoc();
				return $record['locationId'];
			}
		}

		$query = " insert into " . DB::$DATABASE . ".location (locationName) values(";
		$query .= " '" . $db->real_escape_string($val) . "') ";
		
		$db->query($query);
		
		$id = $db->insert_id;
		
		if (intval($id)){
			
			return $id;
			
		}
	
		return false;
	
	}	
	
}
?>

 

inc/classes/Card.class.php

<?php 

class Card{
	
	private $db;
	
	private $facility;
	private $number;	
	private $isMaster;
	private $label;
	private $cardId;
	private $person;
	private $days;

	function __construct($id){
	
		$this->db = DB::Instance();
		$this->load($id);
	
	}
	
	
	private function load($val){
	
		if (is_numeric($val)){
				
			$query = " select * ";
			$query .= " from " . DB::$DATABASE . ".card  ";
			$query .= " where cardId = " . intval($val);

			if ($result = $this->db->query($query)) {
				if ($result->num_rows > 0){
	
					$row = $result->fetch_assoc();
					$this->setCardId($row['cardId']);
					$this->setFacility($row['facility']);
					$this->setNumber($row['number']);
					$this->setIsMaster($row['isMaster']);
					$this->setLabel($row['label']);						
					$this->setPerson($row['person']);
					
				}
	
			}
			
		}
	
	}
	
	
	function isBetween($from, $till, $input) {
		$f = DateTime::createFromFormat('!H:i', $from);
		$t = DateTime::createFromFormat('!H:i', $till);
		$i = DateTime::createFromFormat('!H:i', $input);
		if ($f > $t) $t->modify('+1 day');
		return ($f <= $i && $i <= $t) || ($f <= $i->modify('+1 day') && $i <= $t);
	}
	
	
	public function openDoor($location){
	
		$enter = false;
		
		$dow = date("N");
		
		if (intval($dow)){
			
			$query  = " select lc.*,lcdt.begin,lcdt.end  ";
			$query .= " from " . DB::$DATABASE . ".locationCard lc  ";
			$query .= " join " . DB::$DATABASE . ".locationCardDayTime lcdt on lc.locationCardId = lcdt.locationCardId ";
			$query .= " where lc.cardId = " . intval($this->getCardId()) . " ";
			$query .= " and lc.locationId = " . intval($location->getLocationId()) . " ";
			$query .= " and lcdt.day = " . intval($dow);			

			$row = false;
				
			if ($result = $this->db->query($query)) {
			
				if ($result->num_rows > 0){
						
					$row = $result->fetch_assoc();

				}
			
			}
			
			if ($row){
			
				$begin = trim($row['begin']);
				$end = trim($row['end']);

				if (strlen($begin) && strlen($end)){
			
					if ($this->isBetween($begin, $end, date('H:i'))){
			
						$enter = true;
			
					} else {
			
						$enter = false;
			
					}
						
				}
			
			}			
			
		}
	
		return $enter;
	
	}
	
	
	public function setCardId($val){
		$this->cardId = intval($val);
	}
	
	public function setFacility($val){
		$this->facility = intval($val);
	}
	
	public function setNumber($val){
		$this->number = intval($val);
	}
	
	public function setIsMaster($val){
		$this->isMaster = intval($val);
	}
	
	public function setLabel($val){
		$val = trim($val);
		$val = substr($val, 0, 16);
		$this->label = $val;
	}
		
	public function setPerson($val){
		$val = trim($val);
		$val = substr($val, 0, 32);
		$this->person = $val;
	}

	public function setLocationCardId($val){
		$this->locationCardId = intval($val);
	}

	public function setDays(){

		$this->days = array();
		
		$query = " select lcdt.* ";
		$query .= " from " . DB::$DATABASE . ".locationcarddaytime lcdt  ";
		$query .= " where lcdt.locationCardId = " . intval($this->getLocationCardId()) . "  ";
		$query .= " order by lcdt.day asc ";
		
		if ($result = $this->db->query($query)) {
			if ($result->num_rows > 0){
		
				while($row = $result->fetch_assoc()){
		
					$this->days[] = $row;
		
				}
		
			}
		
		}
		
	}
	
	public function getCardId(){
		return $this->cardId;
	}
	
	public function getFacility(){
		return $this->facility;
	}

	public function getNumber(){
		return $this->number;
	}
	
	public function getIsMaster(){
		return $this->isMaster;
	}
	public function getLabel(){
		return $this->label;
	}
	
	public function getPerson(){
		return $this->person;
	}	
	
	public function getDays(){
		return $this->days;
	}
	
	public function getLocationCardId(){
		return $this->locationCardId;
	}	
	
	
	public static function wiegandDecode($rawCode, $bits){
	
		$string = decbin($rawCode);
	
		$string = str_pad ($string , $bits , "0" ,  STR_PAD_LEFT);
	
		$string = substr($string, 1);
		$string = substr($string, 0, (strlen($string) - 1));
	
		$number = substr($string, -16);
		$facility = substr($string, (strlen($string) * -1),-16);
	
		return array('facility' => bindec($facility), 'number' => bindec($number));
	
	}
	
	
	public static function getByNumber($rawCode, $bits, $masterMode,$location){
		$cardId = self::wiegand($rawCode, $bits, $masterMode, $location);
		if(intval($cardId)){
			return new Card($cardId);
		}else{
			return false;
		}
	}
	
	
	private static function wiegand($rawCode, $bits, $masterMode,$location){
	
		$db = DB::Instance();

		$decode = self::wiegandDecode($rawCode, $bits);
		
		if (is_array($decode)){
			
			if (count($decode) == 2){
				
				if (isset($decode['facility']) && isset($decode['number'])){
					
					if (intval($decode['facility']) && intval($decode['number'])){
						
						$facility = intval($decode['facility']);
						$number = intval($decode['number']);
						
						
						///////////////////////////
						///////////////////////////
						// logic for inserting a master card if there are currently no cards
						$query  = " select count(*) as rowcount ";
						$query .= " from " . DB::$DATABASE . ".card  ";

						if ($result = $db->query($query)) {						
						
							if ($result->num_rows > 0){
					
								$row = $result->fetch_assoc();
					
								if (isset($row['rowcount'])){
					
									if (is_numeric($row['rowcount'])){
					
										if ($row['rowcount'] == 0){
												
											$query  = " insert into " . DB::$DATABASE . ".card (facility,number,isMaster) values (";
											$query .= " " . intval($facility) . " ";
											$query .= " ," . intval($number) . " ";
											$query .= " ,1) ";
					
											$db->query($query);
					
										}
											
									}
					
								}
					
							}
						
						}
						///////////////////////////
						///////////////////////////
						
						$id = 0;
						
						if (intval($masterMode)){
					
							$query  = " insert into " . DB::$DATABASE . ".card (facility,number,isMaster) values (";
							$query .= " " . intval($facility) . " ";
							$query .= " ," . intval($number) . " ";
							$query .= " ,0) ";
							
							$db->query($query);
							
						}
						
						$query  = " select * ";
						$query .= " from " . DB::$DATABASE . ".card ";
						$query .= " where facility = " . intval($facility) . " ";
						$query .= " and number = " . intval($number) . " ";
					
						if ($result = $db->query($query)) {
							if ($result->num_rows > 0){
								$row = $result->fetch_assoc();
								$id = $row['cardId'];
							}
						}
						
						if (intval($id) && intval($masterMode)){
			
							$query  = " insert into " . DB::$DATABASE . ".locationCard (cardId,locationId) values (";
							$query .= " " . intval($id) . " ";
							$query .= " ," . intval($location->getLocationId()) . " ";
							$query .= " ) ";
					
							$db->query($query);
							
							$locationCardId = $db->insert_id;
							
							if (intval($locationCardId)){
								for ($i = 1; $i < 8; $i++){
									$query = " insert into " . DB::$DATABASE . ".locationCardDayTime (locationCardId,day, begin, end) values (";
									$query .= " " . intval($locationCardId) . " ";
									$query .= " ," . intval($i) . " ";
									$query .= " ,'00:00' ";
									$query .= " ,'24:00') ";
									$db->query($query);
	
								}
								
							}
							
						}

						return $id;
						
					}
					
				}
				
			}
			
		}
	
		return false;
	
	}	
		
}

?>

 

(Page 6 of 6)