how fex eror in regestration laravel 8 - laravel-8

public_html/core/app/Http/Controllers/Advertiser/Auth/RegisterController.php (line 64)
public function showRegistrationForm()
{
$page_title = "Advertiser Sign Up";
$info = json_decode(json_encode(getIpInfo()), true);
$country_code = #implode(',', $info['code']);
return view($this->activeTemplate . 'advertiser.auth.register', compact('page_title','country_code'));
}

Related

PDO: My DELETE statement in the User->logout() is not executing

my errors:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* FROM tbl_usersession WHERE BenutzerID = ?' at line 1 in C:\xampp7-4-3\htdocs\Corona\classes\db.php:52 Stack trace: #0 C:\xampp7-4-3\htdocs\Corona\classes\db.php(52): PDO->prepare('DELETE * FROM t...') #1 C:\xampp7-4-3\htdocs\Corona\classes\db.php(94): DB->query('DELETE * FROM t...', Array) #2 C:\xampp7-4-3\htdocs\Corona\classes\db.php(111): DB->action('DELETE *', 'tbl_usersession', Array) #3 C:\xampp7-4-3\htdocs\Corona\classes\user.php(135): DB->delete('tbl_usersession', Array) #4 C:\xampp7-4-3\htdocs\Corona\logout.php(5): User->logout() #5 {main} thrown in C:\xampp7-4-3\htdocs\Corona\classes\db.php on line 52
the code:
<?php
require_once 'core/init.php';
$user = new User();
$user->logout();
// Redirect::to('index.php');
?>
my user class:
<?php
class User
{
private $_db,
$_data,
$_sessionName,
$_cookieName,
$_isLoggedIn;
public function __construct($user = null)
{
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
if(!$user)
{
if(Session::exists($this->_sessionName))
{
$user = Session::get($this->_sessionName);
if($this->find($user))
{
$this->_isLoggedIn = true;
}
else
{
//process logout
}
}
}
else
{
$this->find($user);
}
}
public function create($fields = array())
{
if
(
$this->_db->insert('tbl_benutzer', $fields)
)
{
throw new Exception('Es gab einen Fehler bei der Erstellung Ihres Kontos.');
}
echo "Ihr Benutzerkonto wurde erfolgreich angelegt. Sie können sich jetzt anmelden.";
}
public function find($email = null)
{
if($email)
{
$field = (is_numeric($email)) ? 'id' : 'Email';
$data = $this->_db->get('tbl_benutzer', array($field, '=', $email));
if($data->count())
{
$this->_data = $data->first();
return true;
}
return false;
}
}
public function login($email = null, $password = null, $remember = false)
{
// echo "Remember=" . $remember . "<br>";
$user = $this->find($email);
if(!$email && !$password && $this->exists())
{
Session::put($this->_sessionName, $this->data()->ID);
}
else
{
$user = $this->find($email);
if($user)
{
if(password_verify($password, $this->data()->Hash))
{
Session::put($this->_sessionName, $this->data()->ID);
echo "Remember=" . $remember . "<br>";
if($remember)
{
$hash = Hash::unique();
echo "Hash=" . $hash . "<br>";
echo "id=" . $this->data()->ID . "<br>";
$hashCheck = $this->_db->get('tbl_usersession', array('BenutzerID', "=", $this->data()->ID));
echo "HashCheckCount= " . $hashCheck->count() . "<br>";
if(!$hashCheck->count())
{
$this->_db->insert
(
'tbl_usersession',
array
(
'BenutzerID' => $this->data()->ID,
'Hash' => $hash
)
);
}
else
{
$hash = $hashCheck->first()->Hash;
}
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
return true;
}
else return false;
}
}
return false;
}
public function exists()
{
return (!empty($this->data)) ? true : false;
}
public function logout()
{
$this->_db->delete('tbl_usersession', array('BenutzerID', '=', $this->data()->ID));
print_r($this->data());
// Wieso geht das delete nicht?
Session::delete($this->_sessionName);
Cookie::delete($this->_cookieName);
}
public function data()
{
return $this->_data;
}
public function isLoggedIn()
{
return $this->_isLoggedIn;
}
}
?>
my db class:
<?php
class DB
{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct()
{
try
{
$this->_pdo = new PDO
(
'mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'),
Config::get('mysql/username'),
Config::get('mysql/password')
);
// Error tracking:
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch
(
PDOException $e
)
{
die($e->getMessage());
}
}
public static function getInstance()
{
if
(
!isset(self::$_instance)
)
{
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$x = 1;
if(count($params))
{
foreach($params as $param)
{
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array())
{
if(count($where) === 3)
{
$operators = array('=', '<', '>', '<=', '>=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators))
{
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if($this->query($sql, array($value)))
{
return $this;
}
}
}
return false;
}
public function get($table, $where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where)
{
return $this->action('DELETE *', $table, $where);
}
public function insert($table, $fields = array())
{
if
(
count($fields)
)
{
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field)
{
$values .= '?';
if
(
$x < count($fields)
)
{
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO " . $table . " (" . implode(", ", $keys) . ") VALUES ({$values})";
if
(
$this->query($sql, $fields)->error()
)
{
return true;
}
}
}
public function update($table, $id, $fields = array())
{
$set = ' ';
$x = 1;
foreach
(
$fields as $name => $value
)
{
$set .= "{$name} = ?";
if
(
$x < count($fields)
)
{
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE ID = {$id}";
if
(
$this->query($sql, $fields)->error()
)
{
return true;
}
return false;
}
public function results()
{
return $this->_results;
}
public function first()
{
return $this->results()[0];
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
}
?>
It just basic syntax error for DELETE Statement shown as below:
The correct syntax is
DELETE FROM table
But your wrong syntax is
DELETE * FROM table
So debug your delete function will be solved your syntax error
public function delete($table, $where)
{
return $this->action('DELETE', $table, $where);
}

yii2 : how to return image with response->data

public function actionFind()
{
$response = Yii::$app->response;
\Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
\Yii::$app->response->headers->add('content-type', 'image/jpg');
$img_url = file_get_contents('images/ab.jpg');
Yii::$app->response->data($img_url);
return \Yii::$app->response;
}
why this code has error??
error is :
cannot be displayed because it contains errors
data is property, not function http://www.yiiframework.com/doc-2.0/yii-web-response.html#$data-detail
public function actionFind()
{
$response = \Yii::$app->response;
$response->format = yii\web\Response::FORMAT_RAW;
$response->headers->add('content-type', 'image/jpg');
$img_data = file_get_contents('images/ab.jpg');
$response->data = $img_data;
return $response;
}

Php Problem with mysql_query()

I've been having problems with my php code. I seem to be getting an error from #mysql_query().
Here's my code for php:
<?php
// A simple PHP script demonstrating how to connect to MySQL.
// Press the 'Run' button on the top to start the web server,
// then click the URL that is emitted to the Output tab of the console.
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
Here's my code for C#:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LoginScript : MonoBehaviour {
#region Variables
//Static Variables
public static string Email = "";
public static string Password = "";
//Private Variables
private string createAccountUrl = "https://credmanager-rowanharley.c9.io/createaccount.php";
private string loginUrl = "https://credmanager-rowanharley.c9.io/loginaccount.php";
private string ConfirmPass= "";
private string CreateEmail = "";
private string CreatePassword = "";
//Public Variables
public string currentMenu = "Login";
//GUI test section
public float X;
public float Y;
public float Width;
public float Height;
#endregion
// Use this for initialization
void Start () {
}
void OnGUI(){
//If current menu is = login call login screen
if (currentMenu == "Login"){
LoginGUI();
}
//If current menu is = Create Account call CreateAccount screen
else if(currentMenu == "CreateAccount"){
CreateAccountGUI();
}
}
//This method will login to accounts
void LoginGUI(){
GUI.Box (new Rect (210, 15, 300, 300), "Login");
if (GUI.Button (new Rect (250, 275, 105, 35), "Register Now!!!")) {
currentMenu = "CreateAccount";
}
if (GUI.Button (new Rect (370, 275, 105, 35), "Login!")) {
StartCoroutine(LoginAccount());
}
GUI.Label(new Rect(225, 55, 290, 100), "Before Continuing you need to login or register.");
GUI.Label(new Rect(215, 102, 100, 100), "Email:");
Email = GUI.TextField (new Rect (330, 100, 150, 25), Email);
GUI.Label(new Rect(215, 150, 100, 100), "Password:");
Password = GUI.TextField (new Rect (330, 147, 150, 25), Password);
}
void CreateAccountGUI(){
GUI.Box (new Rect (210, 15, 300, 300), "Register to save progress");
if (GUI.Button (new Rect (250, 275, 105, 35), "Back")) {
currentMenu = "Login";
}
GUI.Label(new Rect(225, 55, 290, 100), "Register NOW!!!");
GUI.Label(new Rect(215, 102, 100, 100), "Email:");
CreateEmail = GUI.TextField (new Rect (330, 100, 150, 25), CreateEmail);
GUI.Label(new Rect(215, 150, 100, 100), "Password:");
CreatePassword = GUI.TextField (new Rect (330, 147, 150, 25), CreatePassword);
GUI.Label(new Rect(215, 198, 122, 100), "Confirm Password:");
ConfirmPass = GUI.TextField (new Rect (330, 194, 150, 25), ConfirmPass);
GUI.Box (new Rect (210, 15, 300, 300), "Register to save progress");
if (GUI.Button (new Rect (250, 275, 105, 35), "Back")) {
currentMenu = "Login";
}
if (GUI.Button (new Rect (370, 275, 105, 35), "Create Account")) {
if (CreatePassword == ConfirmPass){
StartCoroutine("CreateAccount");
}
else{
Debug.Log("Both Passwords are not the same");
}
}
}
IEnumerator CreateAccount(){
//this sends info to php form
WWWForm CreateAccountForm = new WWWForm ();
CreateAccountForm.AddField ("Email", CreateEmail);
CreateAccountForm.AddField ("Password", CreatePassword);
WWW CreateAccountWWW = new WWW (createAccountUrl, CreateAccountForm);
yield return CreateAccountWWW;
if (CreateAccountWWW.error != null) {
Debug.LogError ("Failed to Create Account. Is Internet On? Is URL Correct? Error Message: " + CreateAccountWWW.error);
} else {
string CreateAccountReturn = CreateAccountWWW.text;
Debug.Log("Successfully Created Account " + CreateEmail);
Application.LoadLevel("MainScene");
}
}
IEnumerator LoginAccount(){
Debug.Log ("Attempting to login...");
WWWForm Form = new WWWForm ();
Form.AddField ("Email", Email);
Form.AddField ("Password", Password);
WWW LoginAccountWWW = new WWW (loginUrl, Form);
yield return LoginAccountWWW;
if (LoginAccountWWW.error != null) {
Debug.LogError("Problem with Database. Error Message: " + LoginAccountWWW.error);
}
else {
string LogText = LoginAccountWWW.text;
Debug.Log(LogText);
string[] LogTextSplit = LogText.Split(':');
if (LogTextSplit[1] == "Success"){
Application.LoadLevel("MainScene");
}
}
}
}
When I press play from unity editor I get error: "Database Error" from #mysql_query() on $result_id.
use query string as format like this
"SELECT m.name FROM test.members WHERE name=%s OR id=%d OR sex IN (%a)", "Evil 'injection'", 'NaN', array('male', 'female', 'both', 'other', "Alien quote'man"));

LDAP on XAMPP localhost

I am using windows XP with XAMPP 1.6.4 - php 5.2.4 with LDAP enabled
trying this script :
$server = "ldap://127.0.0.1/";
$user = "Salman";
$pass = "123";
$con = ldap_connect($server);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
var_dump(ldap_bind($con, $user, $pass));
but ldap_bind always returns this error :
Warning: ldap_bind() [function.ldap-bind]: Unable to bind to server: Can't contact LDAP server in D:\xampp\htdocs\test.php on line 11
bool(false)
Hi i put a class together for this a while back:
<?php
/* USAGE:
* $ldapObj= new Ldap("HOST","PORT","USERNAME","PASSWORD","Distinguished Name"," (mailnickname=USERNAME)",array("*"));
*/
class Ldap {
enter code here
public $ldaphost;
public $ldapport;
public $ldaprdn;
public $ldappass;
public $dn;
public $filter;
public $attributes;
public $ad;
public $ldapbind;
public $ldapresults;
public $ldapentries;
public $ldaperror;
public $ldapstatus;
function __construct($ldaphost, $ldapport, $ldaprdn, $ldappass, $dn, $filter, $attributes) {
$this->ldaphost = $ldaphost;
$this->ldapport = $ldapport;
$this->ldaprdn = $ldaprdn;
$this->ldappass = $ldappass;
$this->dn = $dn;
$this->filter = $filter;
$this->attributes = $attributes;
$this->ad = ldap_connect($this->ldaphost);
if ($this->ad) {
$this->ldapbind = ldap_bind($this->ad, $this->ldaprdn, $this->ldappass);
if ($this->ldapbind) {
$this->ldapresults = ldap_search($this->ad, $this->dn, $this->filter, $this->attributes);
$this->ldapentries = ldap_get_entries($this->ad, $this->ldapresults);
$this->getSid();
$this->ldapstatus = 1;
} else {
$this->ldaperror = "Unable to authenticate user";
$this->ldapstatus = 0;
}
ldap_unbind($this->ad);
} else {
$this->ldaperror = "Could not connect to {$this->ldaphost}";
$this->ldapstatus = 0;
}
}
function getLdapEntry($entry) {
return $this->ldapentries[0][$entry][0];
}
function getLdapEntries() {
return $this->ldapentries;
}
function ldapError() {
return $this->ldaperror;
}
function getSid() {
$sid = "S-";
$entries = $this->ldapentries;
// Convert Bin to Hex and split into byte chunks
$sidinhex = str_split(bin2hex($entries[0]['objectsid'][0]), 2);
// Byte 0 = Revision Level
$sid = $sid . hexdec($sidinhex[0]) . "-";
// Byte 1-7 = 48 Bit Authority
$sid = $sid . hexdec($sidinhex[6] . $sidinhex[5] . $sidinhex[4] . $sidinhex[3] . $sidinhex[2] . $sidinhex[1]);
// Byte 8 count of sub authorities - Get number of sub-authorities
$subauths = hexdec($sidinhex[7]);
//Loop through Sub Authorities
for ($i = 0; $i < $subauths; $i++) {
$start = 8 + (4 * $i);
// X amount of 32Bit (4 Byte) Sub Authorities
$sid = $sid . "-" . hexdec($sidinhex[$start + 3] . $sidinhex[$start + 2] . $sidinhex[$start + 1] . $sidinhex[$start]);
}
$this->sid = $sid;
}
}
?>

how to edit .htpasswd using php?

i have a protected directory where only user on .htpasswd can access, but sometimes it requires the user to change password or username, edit a specific username password to his username him self
sample users
kevien : kka
mike : mike
And let say i want to change kevien to XYZ
And same thing goes to password
I have modified function to use all types of crypt alghoritms. Someone may find it useful:
/*
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;
}
Function for generating Apache like MD5:
/**
* #param string $password
* #param string|null $salt
* #ref https://stackoverflow.com/a/8786956
*/
function crypt_apr1_md5($password, $salt = null)
{
if (!$salt) {
$salt = substr(base_convert(bin2hex(random_bytes(6)), 16, 36), 1, 8);
}
$len = strlen($password);
$text = $password . '$apr1$' . $salt;
$bin = pack("H32", md5($password . $salt . $password));
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) : $password[0];
}
$bin = pack("H32", md5($text));
for ($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $password : $bin;
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $password;
}
$new .= ($i & 1) ? $bin : $password;
$bin = pack("H32", md5($new));
}
$tmp = '';
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)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
);
return "$" . "apr1" . "$" . $salt . "$" . $tmp;
}
Demo of crypt_apr1_md5() is available here.
Note that as of Apache 2.4, bcrypt is supported, so you can (and SHOULD) just use password_hash() on newer versions of Apache for this purpose.
Ofc this is just a sample, that will read your current file, find the given username and change either it is password of username.
Please keep in mind that this code is not safe and you would still need to parse the username and password so it does not break your 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);
Don't. Store your authdb in a database instead, via e.g. mod_auth_mysql.
Googled "php generate htpasswd", got this article: How to create a password for a .htpasswd file using PHP.
The key line seems to be:
$password = crypt($clearTextPassword, base64_encode($clearTextPassword));
So I imagine you'd read in the file contents with file_get_contents, parse it into an associative array, modify the relevant entries (encrypting the password as shown above), write the array back into a string, and use file_put_contents to write the file back out.
This is most definitely not standard practice, however. Sounds like the job for a database. If you feel weird about setting up a whole database server, and your host supports it, SQLite might be a good choice.
Just in case someone is just looking for a working script, here is a solution.
It is the script published here by Kavoir with a minor change: 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;
}
}
}
You can use this script like:
$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
}