2010-06-08 15 views
6

ho una directory protetta dove solo utente su .htpasswd può accedere, ma a volte richiede all'utente di cambiare la password o nome utente, modificare una password nome utente specifico per il proprio nome utente lui stessocome modificare .htpasswd usando php?

sample users 
kevien : kka 
mike : mike 

E lasciatemi dire che voglio cambiare kevien a XYZ

E stessa cosa vale per la password

risposta

4

Di questo è solo un esempio, che leggerà il file corrente, troverà il nome utente indicato e cambierà sia la password del nome utente.

Si prega di tenere presente che questo codice non è sicuro e sarebbe comunque necessario analizzare il nome utente e la password in modo che non si rompa il file.

$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

Questo codice funziona davvero correttamente?Non dice "se l'utente memorizzato nel file non corrisponde all'utente fornito dall'input di aggiungere l'utente e la password al file"? – Qullbrune

+0

Se l'utente non corrisponde a quello già nel file non cambierà nulla e dice in alto 'Ofc questo è solo un campione 'significa che non è stato testato, ma la logica è lì e puoi sempre creare un file di test e testare il tuo se stesso. – Prix

4

non lo fanno. Memorizza il tuo authdb in un database, invece, tramite ad es. mod_auth_mysql.

+0

Vazquez-Abrams hai qualche tutorial su come implementare it – Mahmoud

3

Cerca su google "php generate htpasswd", ha ottenuto questo articolo: How to create a password for a .htpasswd file using PHP.

La linea chiave sembra essere:

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

quindi immagino che ci si legge nel contenuto del file con file_get_contents, analizza in un array associativo, modificare le voci rilevanti (cifrare la password come indicato sopra), scrivere di nuovo l'array in una stringa e utilizzare file_put_contents per riscrivere il file.

Questa non è assolutamente la pratica standard, tuttavia. Sembra il lavoro per un database. Se ti senti strano nell'impostare un intero server database e il tuo host lo supporta, lo SQLite potrebbe essere una buona scelta.

+0

ho trovato una classe completamente funzionale ma il problema con esso è che se l'utente esiste non lo scrive oltre, aggiunge un'altra riga, io sto avendo lo stesso utente ma più password 'http: // www .weberdev.com/get_example-4178 .html' – Mahmoud

+0

@Mahmoud: che interessante. Vi auguro buona fortuna sia nel modificare il codice per soddisfare le vostre esigenze, sia nello scrivere la vostra soluzione. – Matchu

+0

sto solo usando l'idea, non il codice stesso, voglio creare una soluzione ma sono bloccato dopo aver codificato la password, è possibile cercare e sovrascrivere il testo – Mahmoud

6

ho funzione modificati per utilizzare tutti i tipi di algoritmi cripta. Qualcuno potrebbe trovare utile:

/* 
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; 
} 

funzione per la generazione di Apache come 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

Il codice è molto buono, solo un suggerimento per mettere $ tmp = ""; before: for ($ i = 0; $ i <5; $ i ++) {// in modo che il messaggio di avviso non definito non si verifichi. –

-1

in caso qualcuno è solo in cerca di uno script di lavoro, ecco una soluzione.

E 'lo script pubblicato qui da Kavoir con una piccola modifica: 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; 
    } 
} 

} 

È possibile utilizzare questo script come:

$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 
} 
Problemi correlati