Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Don't forget to make this file private (.htaccess)
- $file_path = "./users.txt";
- function auth_check($user, $pass) {
- $file = file($GLOBALS["file_path"]);
- // Find lines identifying the specified user
- $user_enc = base64_encode($user);
- $user_regex = "/^{$user_enc}::.*$/";
- $user_matches = preg_grep($user_regex, $file);
- foreach ($user_matches as $line) {
- // Extract password hash from line
- $parts = explode("::", $line);
- $hash = trim($parts[1]);
- // Return true if password matches
- if (password_verify($pass, $hash))
- return true;
- }
- // Password doesn't match, return false
- return false;
- }
- function auth_add($user, $pass) {
- // Compose new line
- $parts = array(
- base64_encode($user),
- password_hash($pass, PASSWORD_DEFAULT)
- );
- $line = implode("::", $parts) . "\n";
- // Write new line to file
- file_put_contents($GLOBALS["file_path"], $line, FILE_APPEND);
- }
- function auth_remove($user, $pass) {
- $file = file($GLOBALS["file_path"]);
- $new_lines = array();
- // Find lines identifying the specified user
- $user_enc = base64_encode($user);
- foreach ($file as $line) {
- // Extract user and password hash from line
- $parts = explode("::", $line);
- $line_user = $parts[0];
- $hash = trim($parts[1]);
- // Add line if user or password does not match
- if ($line_user !== $user_enc) {
- array_push($new_lines, $line);
- } else if (!password_verify($pass, $hash)) {
- array_push($new_lines, $line);
- }
- }
- file_put_contents($GLOBALS["file_path"], implode("\n", $new_lines));
- }
- // Lines below are for demo only
- // More secure code is needed in a production environment
- $user = $_POST["user"];
- $pass = $_POST["pass"];
- if ($_GET["action"] == "add") {
- // Method to add users
- // Make sure to protect this, so not everyone can add a user
- if (!auth_check($user, $pass)) { // Prevent creating duplicate entries
- auth_add($user, $pass);
- echo "Successfully added user: " . htmlspecialchars($user);
- } else {
- echo "User already exists";
- }
- } else if ($_GET["action"] == 'verify') {
- // Method to verify users
- if (empty($user) || empty($pass)) {
- // Missing POST parameters: user / pass
- echo "Missing parameters";
- } else if (auth_check($user, $pass)) {
- // Successful login
- echo "Valid credentials for: " . htmlspecialchars($user);
- // Remove used credentials
- auth_remove($user, $pass);
- } else {
- // Unsuccessful login
- echo "Invalid credentials for: " . htmlspecialchars($user);
- }
- } else {
- echo "No action specified";
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement