Mega Code Archive

 
Categories / Php / Email
 

HTTP Basic Authentication via POP3

<? /* HTTP Basic Authentication using POP3 POP servers should be RFC 1939 Compliant and return '+OK <whatever>' on success and '-ERR <whatever>' on failure. YMMV of course. I don't support this, don't ask me questions, yadda yadda All this script does is authenticate - what you do from there is up to you. I just really didn't want system password files used for web authentication - which is a "Really Bad Idea". */ $REALM = "My Realm"; $POPSERVER = 'pop3.yourdomain.com'; // Change this, please. $LOGERRORS = 1; // Comment this line out to NOT log // Authentication errors. // Logs to STDERR - could use syslog // with minor tweaking. if(!isset($PHP_AUTH_USER)) { Header("WWW-Authenticate: Basic realm=\"$REALM\""); Header("HTTP/1.0 401 Unauthorized"); echo "<H1>Authorization Required</H1>\n"; exit; } else { $fp = fsockopen("$POPSERVER", 110, &$errno, &$errstr); if(!$fp) { if (isset($LOGERRORS)) { error_log("AUTH ERROR ($PHP_AUTH_USER/$PHP_AUTH_PW) Connection Failure",0); error_log("POP3 ERROR [$errno] [$errstr]",0); } Header("WWW-Authenticate: Basic realm=\"$REALM\""); Header("HTTP/1.0 401 Auth Required"); echo "<H1>Authorization Required</H1>\n"; exit; } else { set_socket_blocking($fp,-1); // Turn off blocking /* Clear the POP server's Banner Text. eg.. '+OK Welcome to <server name> etc etc' */ $trash = fgets($fp,128); // Trash to hold the banner fwrite($fp,"USER $PHP_AUTH_USER\r\n"); // POP3 USER CMD $user = fgets($fp,128); $user = ereg_replace("\n","",$user); if ( ereg ("^\+OK(.+)", $user ) ) { fwrite($fp,"PASS $PHP_AUTH_PW\r\n"); // POP3 PASS CMD $pass = fgets($fp,128); $pass = ereg_replace("\n","",$pass); if ( ereg ("^\+OK(.+)", $pass ) ) { // User has successfully authenticated echo "<BR>Authenticated: $pass<BR>\n"; if (isset($LOGERRORS)) { error_log("AUTH OK: $PHP_AUTH_USER",0); } } else { if (isset($LOGERRORS)) { error_log("AUTH ERROR ($PHP_AUTH_USER/$PHP_AUTH_PW)",0); error_log("POP3 ERROR $pass",0); } Header("WWW-Authenticate: Basic realm=\"$REALM\""); Header("HTTP/1.0 401 Auth Required"); echo "<H1>Authorization Required</H1>\n"; exit; } } else { if (isset($LOGERRORS)) { error_log("AUTH ERROR ($PHP_AUTH_USER/$PHP_AUTH_PW)",0); error_log("POP3 ERROR [$user]",0); } Header("WWW-Authenticate: Basic realm=\"$REALM\""); Header("HTTP/1.0 401 Auth Required"); echo "<H1>Authorization Required</H1>\n"; exit; } fwrite($fp,"QUIT\r\n"); fclose($fp); } } ?>