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

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);
}

Related

Doesn't save the image in the database Symfony 4

I'm writing applications in symfony and I would like to add an image to the article. I can't save the image to the database. I am trying to make an example from the documentation: https://symfony.com/doc/current/controller/upload_file.html
The image is uploaded to the directory on the server and isn't saved to the database.
$post->setThumbnail($fileName); sets the image name correctly
Entity
/**
* #Assert\Image(
* minWidth = 500,
* minHeight = 300,
* maxWidth = 1920,
* maxHeight = 1080,
* maxSize = "1M"
* )
*/
private $thumbnail;
/**
* Set thumbnail.
*
* #param string $thumbnail
*
* #return Post
*/
public function setThumbnail($thumbnail)
{
$this->thumbnail = $thumbnail;
return $this;
}
/**
* Get thumbnail.
*
* #return string
*/
public function getThumbnail()
{
return $this->thumbnail;
}
Action in Controller
/**
* Add and Edit page Post.
*
* #Route(
* {"pl": "/artykyl/{slug}"},
* name="panel_post",
* defaults={"slug"=NULL}
* )
*
* #param Request $request
* #param string|null $slug
* #param TranslatorInterface $translator
*
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function post(Request $request, string $slug = null, TranslatorInterface $translator, FileUploader $fileUploader)
{
if (null === $slug) {
$post = new Post();
$newPostForm = true;
} else {
$post = $this->getDoctrine()->getRepository('App\Entity\Post')->findOneBy(['slug' => $slug]);
}
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($post->getThumbnail()) {
$file = $post->getThumbnail();
$fileName = $fileUploader->upload($file);
$post->setThumbnail($fileName);
}
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
$this->addFlash('success', $translator->trans('Changes have been saved'));
return $this->redirectToRoute('panel_post', ['slug' => $post->getSlug()]);
} elseif ($form->isSubmitted() && false === $form->isValid()) {
$this->addFlash('danger', $translator->trans('Corrects form'));
}
return $this->render('backend/blog/post.html.twig', [
'currPage' => 'posts',
'form' => $form->createView(),
'post' => $post,
]);
}
File Uploader
class FileUploader
{
private $targetDirectory;
public function __construct($targetDirectory)
{
$this->targetDirectory = $targetDirectory;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
try {
$file->move($this->getTargetDirectory(), $fileName);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
return $fileName;
}
public function getTargetDirectory()
{
return $this->targetDirectory;
}
}
Listener ThumbnailUploadListener
class ThumbnailUploadListener
{
private $uploader;
public function __construct(FileUploader $uploader)
{
$this->uploader = $uploader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
private function uploadFile($entity)
{
// upload only works for Post entities
if (!$entity instanceof Post) {
return;
}
$file = $entity->getThumbnail();
// only upload new files
if ($file instanceof UploadedFile) {
$fileName = $this->uploader->upload($file);
$entity->setThumbnail($fileName);
} elseif ($file instanceof File) {
// prevents the full file path being saved on updates
// as the path is set on the postLoad listener
$entity->setThumbnail($file->getFilename());
}
}
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Post) {
return;
}
if ($fileName = $entity->getThumbnail()) {
$entity->setPost(new File($this->uploader->getTargetDirectory().'/'.$fileName));
}
}
}
services.yaml
App\EventListener\ThumbnailUploadListener:
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: preUpdate }
- { name: doctrine.event_listener, event: postLoad }
You forgot about mapping the thumbnail field
#ORM\Column(type="string")

SQL "VIEW" in codeigniter

I want to create an SQL view within the codeigniter model. What is the best way of doing this?
I use mutliple models depending on wich table i need to work
application/core/MY_model.php
<?php
/**
* CRUD Model
* A base model providing CRUD, pagination and validation.
*/
class MY_Model extends CI_Model
{
public $table;
public $primary_key;
public $default_limit = 15;
public $page_links;
public $query;
public $form_values = array();
protected $default_validation_rules = 'validation_rules';
protected $validation_rules;
public $validation_errors;
public $total_rows;
public $date_created_field;
public $date_modified_field;
public $native_methods = array(
'select', 'select_max', 'select_min', 'select_avg', 'select_sum', 'join',
'where', 'or_where', 'where_in', 'or_where_in', 'where_not_in', 'or_where_not_in',
'like', 'or_like', 'not_like', 'or_not_like', 'group_by', 'distinct', 'having',
'or_having', 'order_by', 'limit'
);
function __construct()
{
parent::__construct();
}
public function __call($name, $arguments)
{
call_user_func_array(array($this->db, $name), $arguments);
return $this;
}
/**
* Sets CI query object and automatically creates active record query
* based on methods in child model.
* $this->model_name->get()
*/
public function get($with = array(), $include_defaults = true)
{
if ($include_defaults) {
$this->set_defaults();
}
foreach ($with as $method) {
$this->$method();
}
$this->query = $this->db->get($this->table);
return $this;
}
/**
* Query builder which listens to methods in child model.
* #param type $exclude
*/
private function set_defaults($exclude = array())
{
$native_methods = $this->native_methods;
foreach ($exclude as $unset_method) {
unset($native_methods[array_search($unset_method, $native_methods)]);
}
foreach ($native_methods as $native_method) {
$native_method = 'default_' . $native_method;
if (method_exists($this, $native_method)) {
$this->$native_method();
}
}
}
/**
* Call when paginating results.
* $this->model_name->paginate()
*/
public function paginate($with = array())
{
$uri_segment = '';
$offset = 0;
$per_page = $this->default_limit;
$this->load->helper('url');
$this->load->library('pagination');
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->total_rows = $this->db->count_all_results($this->table);
$uri_segments = $this->uri->segment_array();
foreach ($uri_segments as $key => $segment) {
if ($segment == 'page') {
$uri_segment = $key + 1;
if (isset($uri_segments[$uri_segment])) {
$offset = $uri_segments[$uri_segment];
}
unset($uri_segments[$key], $uri_segments[$key + 1]);
$base_url = site_url(implode('/', $uri_segments) . '/page/');
}
}
if (!$uri_segment) {
$base_url = site_url($this->uri->uri_string() . '/page/');
}
$config = array(
'base_url' => $base_url,
'uri_segment' => $uri_segment,
'total_rows' => $this->total_rows,
'per_page' => $per_page
);
if ($this->config->item('pagination_style')) {
$config = array_merge($config, $this->config->item('pagination_style'));
}
$this->pagination->initialize($config);
$this->page_links = $this->pagination->create_links();
/**
* Done with pagination, now on to the paged results
*/
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->db->limit($per_page, $offset);
$this->query = $this->db->get($this->table);
return $this;
}
function paginate_api($limit, $offset)
{
$this->set_defaults();
if (empty($limit)) {
$limit = $this->default_limit;
}
if (empty($offset)) {
$offset = 0;
}
$this->db->limit($limit, $offset);
return $this->db->get($this->table)->result();
}
/**
* Retrieves a single record based on primary key value.
*/
public function get_by_id($id, $with = array())
{
foreach ($with as $method) {
$this->$method();
}
return $this->where($this->primary_key, $id)->get()->row();
}
public function save($id = NULL, $db_array = NULL)
{
if (!$db_array) {
$db_array = $this->db_array();
}
if (!$id) {
if ($this->date_created_field) {
$db_array[$this->date_created_field] = time();
}
$this->db->insert($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully created.');
return $this->db->insert_id();
} else {
if ($this->date_modified_field) {
$db_array[$this->date_modified_field] = time();
}
$this->db->where($this->primary_key, $id);
$this->db->update($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully updated.');
return $id;
}
}
/**
* Returns an array based on $_POST input matching the ruleset used to
* validate the form submission.
*/
public function db_array()
{
$db_array = array();
$validation_rules = $this->{$this->validation_rules}();
foreach ($this->input->post() as $key => $value) {
if (array_key_exists($key, $validation_rules)) {
$db_array[$key] = $value;
}
}
return $db_array;
}
/**
* Deletes a record based on primary key value.
* $this->model_name->delete(5);
*/
public function delete($id, $others = array())
{
if (!empty($others)) {
foreach ($others as $k => $v) {
$this->db->where($k, $v);
}
} else {
$this->db->where($this->primary_key, $id);
}
return $this->db->delete($this->table);
// $this->session->set_flashdata('alert_success', 'Record successfully deleted.');
}
/**
* Returns the CI query result object.
* $this->model_name->get()->result();
*/
public function result()
{
return $this->query->result();
}
/**
* Returns the CI query row object.
* $this->model_name->get()->row();
*/
public function row()
{
return $this->query->row();
}
/**
* Returns CI query result array.
* $this->model_name->get()->result_array();
*/
public function result_array()
{
return $this->query->result_array();
}
/**
* Returns CI query row array.
* $this->model_name->get()->row_array();
*/
public function row_array()
{
return $this->query->row_array();
}
/**
* Returns CI query num_rows().
* $this->model_name->get()->num_rows();
*/
public function num_rows()
{
return $this->query->num_rows();
}
/**
* Used to retrieve record by ID and populate $this->form_values.
* #param int $id
*/
public function prep_form($id = NULL)
{
if (!$_POST and ($id)) {
$this->db->where($this->primary_key, $id);
$row = $this->db->get($this->table)->row();
foreach ($row as $key => $value) {
$this->form_values[$key] = $value;
}
}
}
/**
* Performs validation on submitted form. By default, looks for method in
* child model called validation_rules, but can be forced to run validation
* on any method in child model which returns array of validation rules.
* #param string $validation_rules
* #return boolean
*/
public function run_validation($validation_rules = NULL)
{
if (!$validation_rules) {
$validation_rules = $this->default_validation_rules;
}
foreach (array_keys($_POST) as $key) {
$this->form_values[$key] = $this->input->post($key);
}
if (method_exists($this, $validation_rules)) {
$this->validation_rules = $validation_rules;
$this->load->library('form_validation');
$this->form_validation->set_rules($this->$validation_rules());
$run = $this->form_validation->run();
$this->validation_errors = validation_errors();
return $run;
}
}
/**
* Returns the assigned form value to a form input element.
* #param type $key
* #return type
*/
public function form_value($key)
{
return (isset($this->form_values[$key])) ? $this->form_values[$key] : '';
}
}
then when i need a model for a specific database i use class inside models
models/content.php
class content_types extends MY_Model
{
function __construct()
{
parent::__construct();
$this->curentuserdata = $this->session->userdata('lg_result');
$this->userprofile = $this->session->userdata('user_profile');
}
public $table = 'content_types';
public $primary_key = 'id';
public $default_limit = 50;
public function default_order_by()
{
$this->db->order_by('id asc');
}
}
then where i need to call the model
$this->modelname->save($id,array());
$this->modelname->where()->get()->row();
so create one for the 'view table' and the others for insert tables

login with different direct page

Please help me with this code here is the code for model for login(mlogin.php)
<?php if(! defined('BASEPATH')) exit (" No direct script access allowed");
class Mlogin extends CI_Model{
public function cek_db(){
$this->db->where('id_user', $this->input->post('username'));
$this->db->where('password', $this->input->post('pass'));
$query = $this->db->get('user');
if($query->num_rows == 1){
RETURN true;
}
}
function cek_page(){
$uname = $this->input->post('username');
$jenis_user = $this->db->select("`jenis_user` FROM `user` WHERE id_user = '".$uname."' ");
if($jenis_user == 'member'){
RETURN "1";
}else if($jenis_user == 'agen komunitas'){
RETURN "2";
}else if($jenis_user == 'agen non-komunitas'){
RETURN "3";
}else{
RETURN null;
}
}
}
?>
and this is the Login controller
<?php if(! defined('BASEPATH')) exit('No direct script access allowed');
class Login_control extends CI_Controller{
public function cek_user() {
$this->load->model('mlogin');
$query = $this->mlogin->cek_db();
if($query){
RETURN 'yes';
}else{
RETURN 'no';
}
}
public function user_masuk() {
if($this->cek_user() == 'yes'){
$data['id_user'] = $this->input->post('username');
$data['password'] = $this->input->post('pass');
$this->load->model('mlogin');
$ju = $this->mlogin->cek_page();
$data_session = array('id_user'=> $data['id_user'], 'jenis_user' => $ju);
$this->session->set_userdata($data_session);
if($ju == '1'){
$this->load->view('welcome_message1');
}else if($ju == '2'){
$this->load->view('welcome_message2');
}else if($ju == '3'){
$this->load->view('welcome_message3');
}else{
//ERROR
echo "ERROR";
}
}else if($this->cek_user() == 'no'){
echo "Anda belum terdaftar menjadi MEMBER / AGEN";
}else{
echo"LOGIN GAGAL....";
}
}
public function logout(){
$this->session->sess_destroy();
redirect('view/index');
echo "anda telah berhasil logout";
}
}
?>
The result is always "ERROR"

Applying a SQL function on Zend_Db_Table_Row::save()

Is it possible, when saving a Zend_Db_Table_Row, to make ZF apply a SQL function on one column?
For example, if $row->save() generates by default this SQL query:
UPDATE table SET field = ? WHERE id = ?;
I would like it to automatically apply the GeomFromText() function on this field:
UPDATE table SET field = GeomFromText(?) WHERE id = ?;
Thanks for any hint on how to do this with Zend_Db!
Define a custom update method in your class that inherits from Zend_Db_Table (not from the Zend_Db_Table_Row) and use a Zend_Db_Expr to set the column to the function return value.
See the docs here: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.extending.insert-update.
I am just guessing but you could try this:
<?php
class MyTable extends Zend_Db_Table_Abstract
{
protected $_name = 'my_table';
public function update(array $data, $where) {
/**
* Build "col = ?" pairs for the statement,
* except for Zend_Db_Expr which is treated literally.
*/
$set = array();
$i = 0;
foreach ($data as $col => $val) {
if ($val instanceof Zend_Db_Expr) {
$val = $val->__toString();
unset($data[$col]);
} else {
if ($this->_db->supportsParameters('positional')) {
$val = ($col == 'field') ? 'GeomFromText(?)' : '?';
} else {
if ($this->_db->supportsParameters('named')) {
unset($data[$col]);
$data[':col'.$i] = $val;
$val = ($col == 'field') ? 'GeomFromText(:col'.$i.')' : ':col'.$i;
$i++;
} else {
/** #see Zend_Db_Adapter_Exception */
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
}
}
}
$set[] = $this->_db->quoteIdentifier($col, true) . ' = ' . $val;
}
$where = $this->_whereExpr($where);
/**
* Build the UPDATE statement
*/
$sql = "UPDATE "
. $this->_db->quoteIdentifier($this->_name , true)
. ' SET ' . implode(', ', $set)
. (($where) ? " WHERE $where" : '');
/**
* Execute the statement and return the number of affected rows
*/
if ($this->_db->supportsParameters('positional')) {
$stmt = $this->_db->query($sql, array_values($data));
} else {
$stmt = $this->_db->query($sql, $data);
}
$result = $stmt->rowCount();
return $result;
}
protected function _whereExpr($where)
{
if (empty($where)) {
return $where;
}
if (!is_array($where)) {
$where = array($where);
}
foreach ($where as $cond => &$term) {
// is $cond an int? (i.e. Not a condition)
if (is_int($cond)) {
// $term is the full condition
if ($term instanceof Zend_Db_Expr) {
$term = $term->__toString();
}
} else {
// $cond is the condition with placeholder,
// and $term is quoted into the condition
$term = $this->quoteInto($cond, $term);
}
$term = '(' . $term . ')';
}
$where = implode(' AND ', $where);
return $where;
}
}
?>

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
}