1.导入第三方类库:
<?php /** * FILE_NAME : Macaddr.php * linux平台获取服务器mac地址 * @filesource */ class Macaddr { private static $return_array = array(); //返回带有MAC地址的字串数组 private static $mac_addr; //MAC 地址 public function __construct() { echo 1; } /** * 获取当前机器的MAC地址 */ public static function getMac() { $os_type = PHP_OS; switch ( strtolower($os_type) ) { case "linux": self::forLinux(); break; case "solaris": break; case "unix": break; case "aix": break; default: self::forWindows(); break; } $temp_array = array(); foreach (self::$return_array as $row) { foreach ($row as $value) { if (preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i", $value, $temp_array) ) { self::$mac_addr = $temp_array[0]; break; } } if (!empty(self::$mac_addr)) { break; } } unset($temp_array); return self::$mac_addr; } private static function forWindows(){ @exec("ipconfig /all", $macInfo); if ( $macInfo ) { self::$return_array[] = $macInfo; } else { $ipconfig = $_SERVER["WINDIR"]."system32ipconfig.exe"; if ( is_file($ipconfig) ) { @exec($ipconfig." /all", $macInfo); }else { @exec($_SERVER["WINDIR"]."systemipconfig.exe /all", $macInfo); } self::$return_array[] = $macInfo; } return self::$return_array; } private static function forLinux(){ @exec("/sbin/ifconfig", $macInfo); if ( $macInfo ) { self::$return_array[] = $macInfo; } else { $file_arr = array('ifcfg-eth0', 'ifcfg-eth1', 'ifcfg-eth2', 'ifcfg-eth3', 'ifcfg-em1', 'ifcfg-em2', 'ifcfg-em3', 'ifcfg-em4'); foreach ($file_arr as $file) { if (file_exists('/etc/sysconfig/network-scripts/'.$file)) { self::$return_array[] = file('/etc/sysconfig/network-scripts/'.$file); } } } return self::$return_array; } } /* End of file config.php */ /* Location: ./system/application/config/config.php */ ?>
2.CI中使用示例:
<?php
class A extends CI_Controller {
public function checkMac()
{
$this->load->library('Macaddr');//导入类库
$currentMac = Macaddr::getMac();
$macList = array();//在配置文件中写死
if( !empty($currentMac) && !in_array($currentMac, $macList) ) {
exit();
}
}
}