search
HomeBackend DevelopmentPHP Tutorial用php写wifidog的认证服务器

路由器上wifidog的设置

主要设置鉴权服务器主机名(域名或ip都可以)和加粗鉴权服务器路径

路由器会请求以下四个地址:

http://认证服务器/路径/login
http://认证服务器/路径/auth
http://认证服务器/路径/ping
http://认证服务器/路径/portal
http://认证服务器/路径/gw_message.php

所以我们需要每个请求建立一个文件夹下一个index.php

预备知识

客户端首次连接wifi,浏览器请求将被重定向到login并携带参数

login/?gw_address=路由器ip&gw_port=路由器wifidog的端口&gw_id=用户id&url=被重定向前用户浏览的地址

(2013版本的wifidog参数多了mac)

而login/index.php需要做的就是验证通过后再重定向到网关:

http://网关地址:网关端口/wifidog/auth?token=

之后wifidog会启动一个线程周期性报告用户状态:

/auth?stage=&ip=&mac=&token=&incoming=&outgoing=

/auth/index.php则需要返回是否让该用户继续上网,回复格式:Auth:状态码(0:拒绝, 1:验证通过)

验证成功后,路由器将请求/portal/?gw_id=%s

在/portal/index.php就可以写重定向到第一次请求的url参数或者重定向到自定义网址了

/ping/index.php的作用就是告诉路由器认证服务器还没有崩
/gw_message/index.php作用是当认证过程出现错误的时候,想用户显示错误信息

开工

我们将完成用户用账号密码方式认证
1.首先是重定向,在首次登陆时,用户访问的url会被重定向到如下的地址:

/login/index.php

<?php//获取url传递过来的参数parse_str($_SERVER['QUERY_STRING'], $parseUrl);//gw_address、gw_port、gw_id是必需参数,缺少不能认证成功.if( !array_key_exists('gw_address', $parseUrl) || !array_key_exists('gw_port', $parseUrl) || !array_key_exists('gw_id', $parseUrl)){    exit;}//如果提交了账号密码if(isset($_POST['name']) && isset($_POST['password'])){    $username = $_POST['name'];    $password = $_POST['password'];    $db = new mysqli('localhost', 'root', '', 'test');    if(mysqli_connect_errno()){        echo mysqli_connect_error();        die;    }    $db->query("set names 'utf8'");    $result = $db->query("SELECT * FROM user WHERE username='{$username}' AND password='{$password}'");    if($result && $result->num_rows != 0){        //数据库验证成功        $token = '';        $pattern="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ";        for($i=0;$i<32;$i++)            $token .= $pattern[ rand(0,35) ];        //把token放到数据库,用于后续验证(auth/index.php)        $time = time();        $sql = "UPDATE user SET token='{$token}',logintime='{$time}'";        $db->query($sql);        $db->close();        //登陆成功,跳转到路由网管指定的页面.        $url = "http://{$parseUrl['gw_address']}:{$parseUrl['gw_port']}/wifidog/auth?token={$token}";        header("Location: ".$url);    }else{        //认证失败        //直接重定向本页 请求变成get        $url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];        header("Location: ".$url);    }}else{    //get请求    //一个简单的表单页面    $html = <<< EOD    <html>        <head>            <title>portal login</title>        </head>        <body>            <form action="#" method="post">            username:<input type="text" name="username" />            password:<input type="password" name="password" />            <input type="submit" value="submit" />            </form>        </body>    </html>EOD;    echo $html;}

2.用户认证协议:
/auth/?stage=%s&ip=%s&mac=%s&token=%s&incoming=%s&outgoing=%s
参数解释:
stage: 认证阶段,就logoin和counters两种
token: login页面下发的token
incoming: 下载流量
outgoing: 上传流量

/auth/index.php

<?php//获取url传递过来的参数parse_str($_SERVER['QUERY_STRING'], $parseUrl);//需要多少参数用户可自己顶if( !array_key_exists('token', $parseUrl) ){    //拒绝    echo "Auth:0";    exit;}$db = new mysqli('localhost', 'root', '', 'test');$db->query("set names 'utf8'");$token = $parseUrl['token'];$sql = "SELECT * FROM user WHERE token='{$token}'";$result = $db->query($sql);if($result && $result->num_rows != 0){    //token匹配,验证通过    echo "Auth:1";}else{    echo "Auth:0";}

3.Ping协议

/ping/?gw_id=%s&sys_uptime=%lu&sys_memfree=%u&sys_load=%.2f&wifidog_uptime=%lu

wifidog会向认证服务器发送一些信息,来报告wifidog现在的情况,这些信息是通过Http协议发送的,如上的链接所示,参数大概如字面意思,没仔细研究过,而作为认证服务器,auth_server应回应一个"Pong"。
主要作用是路由确认认证服务器仍然存活,没有死机,另外一个功能是认证服务器可以收集路由的负载等的信息。路由器会定时访问这个脚本,脚本必须回复Pong,否则将认为认证服务器失效而出错。

/ping/index.php

<?phpecho "Pong";?>

4.认证成功后的跳转

portal/?gw_id=%s

在认证成功后,wifidog会将用户重定向至该页面。

/portal/index.php

<?php//认证前用户访问任意url,然后被重定向登录页面,session记录的是这个“任意url”.$url = $_SESSION["url"];//如果login参数url保存到session中//跳转到登陆前页面.header("Location: ".$url);

5.若验证失败,则会根据失败原因跳转至如下页面

gw_message.php?message=denied

gw_message.php?message=activate

gw_message.php?message=failed_validation

/gw_message.php

<?php    $message = null;    if(isset($_GET["message"])){        $message = $_GET["message"];    }    echo $message;?>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),