Home > Articles > Programming > PHP

This chapter is from the book

This chapter is from the book

Authenticating Users Using HTTP Authentication

PHP has some built-in support for basic "HTTP Authentication." HTTP authentication is the type of authentication in which a small window pops up in front of the browser prompting you for a username and password. Figure 7-2 and Figure 7-3 show HTTP Authentication windows in Internet Explorer and Mozilla for Linux, respectively. HTTP authentication is server-dependent, the most common example of which is Apache's HTTP authentication method. The methods described here assume you are using an Apache server.

Figure 7-2Figure 7-2. HTTP Authentication Login Window in Internet Explorer

Figure 7-3Figure 7-3. HTTP Authentication Window in Mozilla on Linux

Typically, the HTTP Authentication method under Apache is defined in .htaccess files.1 A .htaccess file usually restricts an entire directory. However, PHP provides a way to use Apache based HTTP Authentication without having to define .htaccess files for the same type of authentication. Additionally, you can easily use PHP's HTTP Authentication method on a per page basis.

Using the PHP method, you can also use your own password scheme. Under Apache, you typically placed encrypted passwords in a password file (usually called .htpasswd). Using the PHP method, you can place your passwords in a file, in a database, or any other method. You can also use any encryption scheme you want, whereas Apache is restricted to UNIX crypted passwords, their own flavor of MD5 passwords, or plain text.

However, if users forget their passwords, you cannot send it to them, because you only know the encrypted version. You either have to reset the password or provide a hint for the password that may help the users remember what it is they used for the password. More on this later in the chapter.

The next script in this chapter details how to use PHP's method of HTTP Authentication with an Apache server. The script also allows you to use passwords encrypted with the crypt() function (which are portable and can be used with Apache's default HTTP Authentication method) or use the basic PHP md5() function to encrypt passwords. The latter option is useful if you already have several applications that use MD5 encryption for passwords.

Script 7-4 http_authentication.php

 1.  <?
 2.  function check_pass($login, $password, $mode) {
 3.    global $password_file;
 4.    if(!$fh = fopen($password_file, "r")) { die("<P>Could Not Open Password File"); }
 5.    $match = 0;
 6.    while(!feof($fh)) {
 7.      $line = fgets($fh, 4096);
 8.      $from_file = explode(":", $line);
 9.      if($from_file[0] == $login) {
10.        if($mode == "crypt"){
11.          $salt = substr($from_file[1],0,2);
12.          $user_pass = crypt($password,$salt);
13.        } elseif ($mode == "md5") {
14.          $user_pass = md5($password);
15.        }
16.        if(rtrim($from_file[1]) == $user_pass) {
17.          $match = 1;
18.          break;
19.       }
20.     }
21.   }
22.   if($match) {
23.     return 1;
24.   } else {
25.     return 0;
26.   }
27.   fclose($fh);
28.  }
29.  function authenticate() {
30.    Header("WWW-Authenticate: Basic realm=\"RESTRICTED ACCESS\"");
31.    Header("HTTP/1.0 401 Unauthorized");
32.    echo ("<h1>INVALID USERNAME OR PASSWORD. ACCESS DENIED<h1>");
33.    exit;
34.  }
35.  /*** MAIN ***/
36.  //select md5 or crypt for $mode. md5 is for md5 encoded passwords, crypt is for 
passwords encoded using apache's httpasswd
37.  $mode = "md5";
38.  $password_file = "C:/apache/passwords/pass.txt";
39.  if (!isset($PHP_AUTH_USER)) {
40.    authenticate();
41.  } else {
42.    if(check_pass($PHP_AUTH_USER, $PHP_AUTH_PW, $mode)) {
43.      ?>
44.      <h1>ACCEPTED</h1>
45.      <?
46.    } else {
47.    authenticate();
48.    }
49.  }
50.  ?>

Script 7-4. http_authentication.php Line-by-Line Explanation

LINE

DESCRIPTION

2

Define a function called check_pass() that takes three arguments:

  • $login—the user-entered username.

  • $password—the user-entered password.

  • $mode—the encryption mode used in the password file, "md5" or "crypt."

3

Allow $password_file to be used globally by this function.

4

Attempt to open the file in read mode and assign a file handle to it. If the file cannot be opened, then print an error and kill the script.

5

Define the variable $match and set it to false (0).

6–21

Create a for loop that loops through the file until the EOF is reached.

7

Read in one line from the file.

8

Explode the contents of the line into an array called $from_file. This should create an array with two items. The first is the username, and the second is the password.

9

If the first element in the array (the username) matches the user-entered username ($login), continue to line 10. Otherwise, go back to line 6 and loop again.

10

Check to see if the $mode variable that was passed to this function is "crypt." If it is, continue to line 11. Otherwise, go to line 13.

11

Define the salt required by the crypt() function. This script can be used with Apache htpasswd generated passwords, so it has to use Apache's method of using crypt()s, which is to use the first two characters of the encrypted password as the salt. This line uses the substr() function to pull out the first two characters from the password obtained from the file and place the value in the $salt variable.

12

Encrypt the user-entered password with the crypt() function using the salt obtained from the previous line. Continue to line 16.

13

Check to see if the $mode variable that was passed to this function is "md5". If it is, continue to line 14.

Note: The function assumes that $mode is either "crypt" or "md5". If it is neither, then the script loops through the entire file without checking anything and returns no matches, which in turn means that authentication fails. It may be useful to print an error message that $mode was not set to either of the required values, but that won't help a user who is trying to access your site. For debugging, you may want to optionally add another else statement that states that $mode was neither "crypt" nor "md5".

14

Encrypt the user-entered password with the md5() function. Continue to line 16.

16–17

Trim any whitespace from the password obtained from the file and compare it to the encrypted version of the user-entered password. If they match, then set the $match variable to true (1).

18

Break out of the loop, since you found a valid match.

19

Close the if statement that checks the password.

20

Close the if statement that checks the username.

21

Close the for loop.

22–23

If $match is true (1), then return true.

24–26

If $match is false(0), then return false.

27

Close the file.

28

End the function declaration.

29

Create a function called authenticate() to display the HTTP Authentication login screen to users if they have not been previously authenticated.

30–31

Use the header() function to send authentication headers to a user's browser.

Line 30 attempts to obtain the username/password from the user. Line 31 is executed if the users have already submitted their username/password combination and there was no corresponding match in the password file.

32

Print a message to the screen notifying the users that their username/password combination is invalid.

33

Exit from the script.

34

End the function declaration.

35

Begin the main program.

36

Include a comment in the script as to the nature of the $mode variable.

37

Assign the $mode variable the value "md5" (or "crypt" if your passwords are encrypted using the crypt() function).

38

Assign the location of the password file to the $password_file variable.

39

Check to see if the global variable $PHP_AUTH_USER has been set. $PHP_AUTH_USER is a special PHP variable that is used with HTTP Authentication. This is the variable that is obtained when the user logs in using the HTTP Authentication window.

40

If $PHP_AUTH_USER variable has not been set, then execute the authenticate() function.

41–42

If the $PHP_AUTH_USER variable has been set, then execute the check_pass() function using the $PHP_AUTH_USER, $PHP_AUTH_PW, and $mode variables as arguments. The $PHP_AUTH_PW variable is the special PHP global variable obtained from the HTTP Authentication login window.

43–45

If the check_pass() function returns true (1), then print out "ACCEPTED" to the screen. You would normally provide your protected content here.

46–48

If the check_pass() function returns false, execute the authenticate() function again. The users have three chances to correctly enter their username and password. After the third failure, the script returns lines 31 and 32.

49

Close the if statement started on line 39.

50

End the script.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020