2010-06-08 4 views
6

내가 .htpasswd에만 사용자가 액세스 할 수있는 보호 된 디렉토리를 가지고 있지만, 때로는 비밀 번호 또는 이름을 변경하도록 요구, 자신의 이름 그 자체PHP를 사용하여 .htpasswd를 편집하는 방법은 무엇입니까?

sample users 
kevien : kka 
mike : mike 

에 특정 사용자 이름 암호를 편집 그리고 내가 원하는 가정 해 봅시다 XYZ

에 kevien을 변경하고 같은 일이 암호

답변

4

Ofc 이것은 현재 샘플 파일을 읽고, 주어진 사용자 이름을 찾고, 사용자 이름의 암호를 변경합니다.

이 코드는 안전하지 않으며 파일을 손상시키지 않도록 사용자 이름과 암호를 구문 분석해야합니다.

$username = $_POST['user']; 
    $password = $_POST['pass']; 
    $new_username = $_POST['newuser']; 
    $new_password = $_POST['newpass']; 
    $action = $_POST['action']; 
    //read the file into an array 
    $lines = explode("\n", file_get_contents('.htpasswd')); 

    //read the array and change the data if found 
    $new_file = ""; 
    foreach($lines as $line) 
    { 
     $line = preg_replace('/\s+/','',$line); // remove spaces 
     if ($line) { 
      list($user, $pass) = split(":", $line, 2); 
      if ($user == $username) { 
       if ($action == "password") { 
        $new_file .= $user.':'.$new_password."\n"; 
       } else { 
        $new_file .= $new_username.':'.$pass."\n"; 
       } 
      } else { 
       $new_file .= $user.':'.$pass."\n"; 
      } 
     } 
    } 

    //save the information 
    $f=fopen(".htpasswd","w") or die("couldn't open the file"); 
    fwrite($f,$new_file); 
    fclose($f); 
+0

이 코드가 실제로 올바르게 동작 하는가?"파일에 저장된 사용자가 입력 한 사용자와 일치하지 않는 경우 사용자에게 암호를 추가하는 것"이라고 말하지 않습니까? – Qullbrune

+0

사용자가 이미 파일에있는 파일과 일치하지 않는 경우 아무 것도 변경하지 않고 맨 위의 'Ofc this is just sample'은 테스트하지 않은 것을 의미하지만 논리가 있으므로 테스트 파일을 만들고 테스트 할 수 있습니다. 본인. – Prix

4

가 안 간다. 대신 authdb를 데이터베이스에 저장하십시오. mod_auth_mysql.

+0

바스케스 - 에이 브람스가 어떻게 구현 그것 – Mahmoud

3

Google에서 검색 한 "php generate htpasswd"은 (가) How to create a password for a .htpasswd file using PHP입니다. 위 그림과 같이

$password = crypt($clearTextPassword, base64_encode($clearTextPassword)); 

그래서 난 당신이 (관련 항목을 수정 암호를 암호화, file_get_contents로 파일 내용 읽어 연관 배열로 구문 분석 거라고 상상 :

핵심 라인이 될 것으로 보인다), 배열에 다시 문자열을 쓰고, file_put_contents을 사용하여 파일을 다시 써주십시오.

그러나 이것은 가장 일반적인 방법은 아닙니다. 데이터베이스 작업과 비슷합니다. 전체 데이터베이스 서버를 설정하는 데 별난 생각이 들며 호스트가이를 지원하면 SQLite이 좋은 선택 일 수 있습니다.

+0

나는 완전한 기능을 가진 클래스를 찾았지만 문제는 사용자가 존재한다면 그것을 쓰지 않고 또 다른 라인을 추가한다. 거기에는 동일한 사용자이지만 여러 개의 비밀번호가있다. 'http : // www .weberdev.com/get_example-4178 .html' – Mahmoud

+0

@ 마흐무드 - 얼마나 재미 있어요. 귀하의 필요에 맞게 코드를 수정하거나 직접 솔루션을 작성하는 것이 좋을 것입니다. – Matchu

+0

나는 아이디어만을 사용하고 코드 자체는 아니지만 솔루션을 만들고 싶지만 패스워드를 인코딩 한 후에 막혀있다. 검색하고 텍스트를 덮어 쓸 수있다. – Mahmoud

6

모든 유형의 토굴 alghoritms를 사용하도록 수정되었습니다. 누군가는 유용하게 사용할 수 :

/* 
Function change password in htpasswd. 
Arguments: 
$user > User name we want to change password to. 
$newpass > New password 
$type > Type of cryptogrphy: DES, SHA, MD5. 
$salt > Option: Add your custom salt (hashing string). 
      Salt is applied to DES and MD5 and must be in range 0-9A-Za-z 
$oldpass > Option: Add more security, user must known old password to change it. 
      This option is not supported for DES and MD5 without salt!!! 
$path > Path to .htaccess file which contain the password protection. 
      Path to password file is obtained from this .htaccess file. 
*/ 

function changePass($user,$newpass,$type="SHA",$salt="",$oldpass="",$path=".htaccess") { 
    switch ($type) { 
    case "DES" : 
    $salt = substr($salt,0,2); //Salt must be 2 char range 0-9A-Za-z 
    $newpass = crypt($newpass,$salt); 
    if ($oldpass != null) $oldpass = crypt($oldpass,$salt); 
    break; 

    case "SHA" : 
    $newpass = '{SHA}'.base64_encode(sha1($newpass, TRUE)); 
    if ($oldpass != null) $oldpass = '{SHA}'.base64_encode(sha1($oldpass, TRUE)); 
    break; 

    case "MD5" : 
    $salt = substr($salt,0,8); //Salt must be max 8 char range 0-9A-Za-z 
    $newpass = crypt_apr1_md5($newpass, $salt); 
    if ($oldpass != null) $oldpass = crypt_apr1_md5($oldpass, $salt); 
    break; 

    default : 
    return false; 
    break; 
    } 

    $hta_arr = explode("\n", file_get_contents($path)); 

    foreach($hta_arr as $line) { 
    $line = preg_replace('/\s+/','',$line); // remove spaces 
    if ($line) { 
     $line_arr = explode('"', $line); 
     if (strcmp($line_arr[0],"AuthUserFile") == 0) { 
     $path_htaccess = $line_arr[1]; 
     } 
    } 
    } 
    $htp_arr = explode("\n", file_get_contents($path_htaccess)); 

    $new_file = ""; 
    foreach($htp_arr as $line) { 
    $line = preg_replace('/\s+/','',$line); // remove spaces 
    if ($line) { 
     list($usr, $pass) = explode(":", $line, 2); 
     if (strcmp($user,$usr) == 0) { 
     if ($oldpass != null) { 
      if ($oldpass == $pass) { 
      $new_file .= $user.':'.$newpass."\n"; 
      } else { 
      return false; 
      } 
     } else { 
      $new_file .= $user.':'.$newpass."\n"; 
     } 
     } else { 
     $new_file .= $user.':'.$pass."\n"; 
     } 
    } 
    } 
    $f=fopen($path_htaccess,"w") or die("couldn't open the file"); 
    fwrite($f,$new_file); 
    fclose($f); 
    return true; 
} 

기능을 MD5처럼 아파치를 생성 : 그냥 경우에 누군가가 단지 작업 스크립트를 찾고 있습니다

function crypt_apr1_md5($plainpasswd,$salt=null) { 
    $tmp = ""; 
    if ($salt == null) $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 8); 
    $len = strlen($plainpasswd); 
    $text = $plainpasswd.'$apr1$'.$salt; 
    $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd)); 
    for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); } 
    for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; } 
    $bin = pack("H32", md5($text)); 
    for($i = 0; $i < 1000; $i++) { 
     $new = ($i & 1) ? $plainpasswd : $bin; 
     if ($i % 3) $new .= $salt; 
     if ($i % 7) $new .= $plainpasswd; 
     $new .= ($i & 1) ? $bin : $plainpasswd; 
     $bin = pack("H32", md5($new)); 
    } 
    for ($i = 0; $i < 5; $i++) { 
     $k = $i + 6; 
     $j = $i + 12; 
     if ($j == 16) $j = 5; 
     $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp; 
    } 
    $tmp = chr(0).chr(0).$bin[11].$tmp; 
    $tmp = strtr(strrev(substr(base64_encode($tmp), 2)), 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/", 
    "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); 
    return "$"."apr1"."$".$salt."$".$tmp; 
} 
+0

코드는 매우 훌륭합니다. $ tmp = ""; before : for ($ i = 0; $ i <5; $ i ++) {// 그래서 정의되지 않은주의 메시지가 발생하지 않도록하십시오. –

-1

, 여기에 솔루션입니다.

그것은 사소한 변화에 Kavoir에 의해 여기에 명시된 스크립트입니다처럼 당신이 스크립트를 사용할 수 http://www.kavoir.com/backyard/showthread.php?28-Use-PHP-to-generate-edit-and-update-htpasswd-and-htgroup-authentication-files

<?php 
/* 
$pairs = array(
    'username' = 'password', 
); 
*/ 

// Algorithm: SHA1 

class Htpasswd { 

private $file = ''; 

public function __construct($file) { 
    if (file_exists($file)) { 
     $this -> file = $file; 
    } else { 
     return false; 
    } 
} 

private function write($pairs = array()) { 
    $str = ''; 
    foreach ($pairs as $username => $password) { 
     $str .= "$username:{SHA}$password\n"; 
    } 
    file_put_contents($this -> file, $str); 
} 

private function read() { 
    $pairs = array(); 
    $fh = fopen($this -> file, 'r'); 
    while (!feof($fh)) { 
     $pair_str = str_replace("\n", '', fgets($fh)); 
     $pair_array = explode(':{SHA}', $pair_str); 
     if (count($pair_array) == 2) { 
      $pairs[$pair_array[0]] = $pair_array[1]; 
     } 
    } 
    return $pairs; 
} 

public function addUser($username = '', $clear_password = '') { 
    if (!empty($username) && !empty($clear_password)) { 
     $all = $this -> read(); 
     // if (!array_key_exists($username, $all)) { 
      $all[$username] = $this -> getHash($clear_password); 
      $this -> write($all); 
    // } 
    } else { 
     return false; 
    } 
} 

public function deleteUser($username = '') { 
    $all = $this -> read(); 
    if (array_key_exists($username, $all)) { 
     unset($all[$username]); 
     $this -> write($all); 
    } else { 
     return false; 
    } 
} 

public function doesUserExist($username = '') { 
    $all = $this -> read(); 
    if (array_key_exists($username, $all)) { 
     return true; 
    } else { 
     return false; 
    } 
} 

private function getHash($clear_password = '') { 
    if (!empty($clear_password)) { 
     return base64_encode(sha1($clear_password, true)); 
    } else { 
     return false; 
    } 
} 

} 

: 당신이 어떤 자습서가 있습니까

$htp = new Htpasswd('.htpasswd'); 
$htp -> addUser('username1', 'clearpassword1'); // this will add or edit the user 
$htp -> deleteUser('username1'); 
// check if a certain username exists 
if ($htp -> doesUserExist('username1')) { 
// user exists 
} 
관련 문제