search
HomeBackend DevelopmentPHP TutorialDooDigestAuth php (backend) authorization management class web browser authorization

<span>  1</span> <span>php
</span><span>  2</span><span>/*</span><span>*
</span><span>  3</span><span> * DooDigestAuth class file.
</span><span>  4</span><span> *
</span><span>  5</span><span> * @author Leng Sheng Hong <darkredz>
</darkredz></span><span>  6</span><span> * @link http://www.doophp.com/
</span><span>  7</span><span> * @copyright Copyright © 2009 Leng Sheng Hong
</span><span>  8</span><span> * @license http://www.doophp.com/license
</span><span>  9</span><span>*/</span><span> 10</span><span> 11</span><span>/*</span><span>*
</span><span> 12</span><span> * Handles HTTP digest authentication
</span><span> 13</span><span> *
</span><span> 14</span><span> * <p>HTTP digest authentication can be used with the URI router.
</p></span><span> 15</span><span> * HTTP digest is much more recommended over the use of HTTP Basic auth which doesn't provide any encryption.
</span><span> 16</span><span> * If you are running PHP on Apache in CGI/FastCGI mode, you would need to
</span><span> 17</span><span> * add the following line to your .htaccess for digest auth to work correctly.
</span><span> 18</span><span> * <code>RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]</code>
</span><span> 19</span><span> *
</span><span> 20</span><span> * <p>This class is tested under Apache 2.2 and Cherokee web server. It should work in both mod_php and cgi mode.</p>
</span><span> 21</span><span> *
</span><span> 22</span><span> * @author Leng Sheng Hong <darkredz>
</darkredz></span><span> 23</span><span> * @version $Id: DooDigestAuth.php 1000 2009-07-7 18:27:22
</span><span> 24</span><span> * @package doo.auth
</span><span> 25</span><span> * @since 1.0
</span><span> 26</span><span>*/</span><span> 27</span><span>class</span><span> DooDigestAuth{
</span><span> 28</span><span> 29</span><span>/*</span><span>*
</span><span> 30</span><span>     * Authenticate against a list of username and passwords.
</span><span> 31</span><span>     *
</span><span> 32</span><span>     * <p>HTTP Digest Authentication doesn't work with PHP in CGI mode,
</p></span><span> 33</span><span>     * you have to add this into your .htaccess <code>RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]</code>
</span><span> 34</span><span>     *
</span><span> 35</span><span>     * @param string $realm Name of the authentication session
</span><span> 36</span><span>     * @param array $users An assoc array of username and password: array('uname1'=>'pwd1', 'uname2'=>'pwd2')
</span><span> 37</span><span>     * @param string $fail_msg Message to be displayed if the User cancel the login
</span><span> 38</span><span>     * @param string $fail_url URL to be redirect if the User cancel the login
</span><span> 39</span><span>     * @return string The username if login success.
</span><span> 40</span><span>*/</span><span> 41</span><span>public</span><span>static</span><span>function</span> http_auth(<span>$realm</span>, <span>$users</span>, <span>$fail_msg</span>=<span>NULL</span>, <span>$fail_url</span>=<span>NULL</span><span>){
</span><span> 42</span><span>$realm</span> = "Restricted area - <span>$realm</span>"<span>;
</span><span> 43</span><span> 44</span><span>//</span><span>user => password
</span><span> 45</span><span>        //$users = array('admin' => '1234', 'guest' => 'guest');</span><span> 46</span><span>if</span>(!<span>empty</span>(<span>$_SERVER</span>['REDIRECT_HTTP_AUTHORIZATION']) && <span>strpos</span>(<span>$_SERVER</span>['REDIRECT_HTTP_AUTHORIZATION'], 'Digest')===0<span>){
</span><span> 47</span><span>$_SERVER</span>['PHP_AUTH_DIGEST'] = <span>$_SERVER</span>['REDIRECT_HTTP_AUTHORIZATION'<span>];
</span><span> 48</span><span>        }
</span><span> 49</span><span> 50</span><span>if</span> (<span>empty</span>(<span>$_SERVER</span>['PHP_AUTH_DIGEST'<span>])) {
</span><span> 51</span><span>header</span>('WWW-Authenticate: Digest realm="'.<span>$realm</span>.
<span> 52</span>                    '",qop="auth",n>uniqid().'",opaque="'.<span>md5</span>(<span>$realm</span>).'"'<span>);
</span><span> 53</span><span>header</span>('HTTP/1.1 401 Unauthorized'<span>);
</span><span> 54</span><span>if</span>(<span>$fail_msg</span>!=<span>NULL</span><span>)
</span><span> 55</span><span>die</span>(<span>$fail_msg</span><span>);
</span><span> 56</span><span>if</span>(<span>$fail_url</span>!=<span>NULL</span><span>)
</span><span> 57</span><span>die</span>("<script>window.location.href = '<span>$fail_url'</script>"<span>);
</span><span> 58</span><span>exit</span><span>;
</span><span> 59</span><span>        }
</span><span> 60</span><span> 61</span><span>//</span><span> analyze the PHP_AUTH_DIGEST variable</span><span> 62</span><span>if</span> (!(<span>$data</span> = self::http_digest_parse(<span>$_SERVER</span>['PHP_AUTH_DIGEST'])) || !<span>isset</span>(<span>$users</span>[<span>$data</span>['username'<span>]])){
</span><span> 63</span><span>header</span>('WWW-Authenticate: Digest realm="'.<span>$realm</span>.
<span> 64</span>                    '",qop="auth",n>uniqid().'",opaque="'.<span>md5</span>(<span>$realm</span>).'"'<span>);
</span><span> 65</span><span>header</span>('HTTP/1.1 401 Unauthorized'<span>);
</span><span> 66</span><span>if</span>(<span>$fail_msg</span>!=<span>NULL</span><span>)
</span><span> 67</span><span>die</span>(<span>$fail_msg</span><span>);
</span><span> 68</span><span>if</span>(<span>$fail_url</span>!=<span>NULL</span><span>)
</span><span> 69</span><span>die</span>("<script>window.location.href = '<span>$fail_url'</script>"<span>);
</span><span> 70</span><span>exit</span><span>;
</span><span> 71</span><span>        }
</span><span> 72</span><span> 73</span><span>//</span><span> generate the valid response</span><span> 74</span><span>$A1</span> = <span>md5</span>(<span>$data</span>['username'] . ':' . <span>$realm</span> . ':' . <span>$users</span>[<span>$data</span>['username'<span>]]);
</span><span> 75</span><span>$A2</span> = <span>md5</span>(<span>$_SERVER</span>['REQUEST_METHOD'].':'.<span>$data</span>['uri'<span>]);
</span><span> 76</span><span>$valid_response</span> = <span>md5</span>(<span>$A1</span>.':'.<span>$data</span>['nonce'].':'.<span>$data</span>['nc'].':'.<span>$data</span>['cnonce'].':'.<span>$data</span>['qop'].':'.<span>$A2</span><span>);
</span><span> 77</span><span> 78</span><span>if</span> (<span>$data</span>['response'] != <span>$valid_response</span><span>){
</span><span> 79</span><span>header</span>('HTTP/1.1 401 Unauthorized'<span>);
</span><span> 80</span><span>header</span>('WWW-Authenticate: Digest realm="'.<span>$realm</span>.
<span> 81</span>                    '",qop="auth",n>uniqid().'",opaque="'.<span>md5</span>(<span>$realm</span>).'"'<span>);
</span><span> 82</span><span>if</span>(<span>$fail_msg</span>!=<span>NULL</span><span>)
</span><span> 83</span><span>die</span>(<span>$fail_msg</span><span>);
</span><span> 84</span><span>if</span>(<span>$fail_url</span>!=<span>NULL</span><span>)
</span><span> 85</span><span>die</span>("<script>window.location.href = '<span>$fail_url'</script>"<span>);
</span><span> 86</span><span>exit</span><span>;
</span><span> 87</span><span>        }
</span><span> 88</span><span> 89</span><span>//</span><span> ok, valid username & password</span><span> 90</span><span>return</span><span>$data</span>['username'<span>];
</span><span> 91</span><span>    }
</span><span> 92</span><span> 93</span><span>/*</span><span>*
</span><span> 94</span><span>     * Method to parse the http auth header, works with IE.
</span><span> 95</span><span>     *
</span><span> 96</span><span>     * Internet Explorer returns a qop="xxxxxxxxxxx" in the header instead of qop=xxxxxxxxxxx as most browsers do.
</span><span> 97</span><span>     *
</span><span> 98</span><span>     * @param string $txt header string to parse
</span><span> 99</span><span>     * @return array An assoc array of the digest auth session
</span><span>100</span><span>*/</span><span>101</span><span>private</span><span>static</span><span>function</span> http_digest_parse(<span>$txt</span><span>)
</span><span>102</span><span>    {
</span><span>103</span><span>$res</span> = <span>preg_match</span>("/username=\"([^\"]+)\"/i", <span>$txt</span>, <span>$match</span><span>);
</span><span>104</span><span>$data</span>['username'] = (<span>isset</span>(<span>$match</span>[1]))?<span>$match</span>[1]:<span>null</span><span>;
</span><span>105</span><span>$res</span> = <span>preg_match</span>('/n/i', <span>$txt</span>, <span>$match</span><span>);
</span><span>106</span><span>$data</span>['nonce'] = <span>$match</span>[1<span>];
</span><span>107</span><span>$res</span> = <span>preg_match</span>('/nc=([0-9]+)/i', <span>$txt</span>, <span>$match</span><span>);
</span><span>108</span><span>$data</span>['nc'] = <span>$match</span>[1<span>];
</span><span>109</span><span>$res</span> = <span>preg_match</span>('/cn/i', <span>$txt</span>, <span>$match</span><span>);
</span><span>110</span><span>$data</span>['cnonce'] = <span>$match</span>[1<span>];
</span><span>111</span><span>$res</span> = <span>preg_match</span>('/qop=([^,]+)/i', <span>$txt</span>, <span>$match</span><span>);
</span><span>112</span><span>$data</span>['qop'] = <span>str_replace</span>('"','',<span>$match</span>[1<span>]);
</span><span>113</span><span>$res</span> = <span>preg_match</span>('/uri=\"([^\"]+)\"/i', <span>$txt</span>, <span>$match</span><span>);
</span><span>114</span><span>$data</span>['uri'] = <span>$match</span>[1<span>];
</span><span>115</span><span>$res</span> = <span>preg_match</span>('/resp/i', <span>$txt</span>, <span>$match</span><span>);
</span><span>116</span><span>$data</span>['response'] = <span>$match</span>[1<span>];
</span><span>117</span><span>return</span><span>$data</span><span>;
</span><span>118</span><span>    }
</span><span>119</span><span>120</span><span>121</span> }

Calling method:

<span>1</span><span>require_once</span>(<span>dirname</span>(<span>__FILE__</span>)."/DooDigestAuth.php"<span>);
</span><span>2</span> DooDigestAuth::http_auth('example.com', <span>array</span>('admin'=>"123456789"));

phpweb authorization login can effectively prevent background brute force cracking

Download address: http://files.cnblogs.com/files/func/DooDigestAuth.zip

The above introduces the DooDigestAuth php (backend) authorization management class web browser authorization, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

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 Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.