HTPASSWD Automatic - php

quick question. I setup a timecard and PO system for a family business. The employees enter their username and password to enter the system. Every time the family hired someone though they send me the info. I use htpasswd generator, and open the file up, add it, and then re-upload use ftp. My wife enter's their info into the db using a php page i setup though and i'm wondering if there is a way to allow her a txt field that can she can copy and past the generated pw into the htpasswd file. Without having me to always change it.
To summarize: is there a form command that when i put in the txt field and push submit it automatically puts the txt into the htpasswd file

You'll need to create a php page. This answer has an example of the code you need:
$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);
Here is also a slightly more complete solution. Or just look it up on Google.

Related

How to change passwords using PHP

I want to allow users to change their password and their password is stored in a file called user_data.txt. How can I allow them to edit their password using solely php? I do not use have MySQL or Java.. just PHP.. This is the code that I have for verifying login.
if ($username == $users[$x]['username'] && $_POST['password'] == $users[$x]['password']){
$name = $_POST['username'];
/////this is the code to read the file
$userdata = "user_data.txt";
function arrayfile_to_array($filepath){
$fsize = filesize($filepath);
if ($fsize > 0) {
$fp = fopen($filepath, "r");
$encoded = fread($fp, $fsize);
fclose($fp);
return unserialize($encoded);
}
}
}
this is the code to save the information into $users variable
$users = arrayfile_to_array ($userdata);
Basically I will be creating an account page that allows them to change their password.
Thank you!

Creating a log in page sourcing from a CSV

I am attempting to create a login page for my website. I have it set up so the user can create an account and these credentials are saved to a csv, saved on my ftp. (All the HTML and CSS is functional) I would like the system to work as follows:
1. From login page the user enters their credentials.
2. The CSV is searched, when the email is found the inputted password is compared with the corresponding password in the CSV.
3. If they match then another page is opened/If they don't match an error is displayed.
Here is the CSV:
Test#gmail.com,password1
Test2#gmail.com.password2
Here is the php which writes to the CSV:
<?php
$filename = $_POST['filename'];
foreach($_POST as $name => $value)
{
IF ($value != "Submit" and $value !=$filename)
{
$messagedisplay = $messagedisplay . $name. ": " . $value . "<BR>";
$filedata = $filedata . $value . ",";
}
}
$filedata = rtrim($filedata,",");
$filedata = $filedata . PHP_EOL;
$fs = fopen($filename,a);
fwrite($fs,$filedata);
fclose($fs);
$messagedisplay = "Your account has been created, please return to the main website and login.";
print $messagedisplay;
?>
Any ideas on how I would check the CSV to see if a) the email exists in the CSV and b) check the passwords match, subsequently redirecting to another page. Thanks.
In your case you could slurp the csv into an array. Then it's as simple as iterating through the array until you find a match.
<?php
$credentials = [
['foo', 'jubblies'],
['bar', 'jangles']
];
$check_credentials = function($username, $password) use ($credentials) {
foreach($credentials as $credential)
if($credential[0] == $username && $credential[1] == $password)
return true;
return false;
};
var_dump($check_credentials('foo', 'jiblets'));
var_dump($check_credentials('foo', 'jubblies'));
var_dump($check_credentials('ace', 'detective'));
Output
boolean false
boolean true
boolean false
Reading your credentials from a csv file into an array (similar format as above) could be accomplished something like this:
function get_credentials_from_file($path) {
$fp = fopen($path, 'r');
while ($line = fgetcsv($fp)) {
$lines[] = $line;
}
fclose($fp);
return $lines;
}
$credentials = get_credentials_from_file('/tmp/file.csv');
See also fputcsv, for csv writing.
Take care when storing user data.
If you end up reading and writing from/to a csv or text file, you'll have to manage file locks etc. It could well be easier to use a database.
See: Php's password_hash and password_verify to avoid storing plain text passwords.

Check value exists or not before wriring it into textfile php

I am adding username and userid into a text file onload of a page as follows:
$.post("addusersonload.php", {userid:chatusrid,username:chatusrname}, function (data) {
});
addusersonload.php
$name = $_REQUEST['username'];
$usrid = $_REQUEST['userid'];
fwrite(fopen('addusersonload.txt', 'a'), "$usrid,$name\n");
I am getting the value in text field as follows:
UserA, 1
UserB, 2
UserA, 1
UserB, 2
I want to check the textfile that the same value exists or not before writing into it.so that the duplication will not occur!!
I guess a DB is the best option for what you need, but, if you really need to write to a file, you can use:
if(!empty($_POST['username']) and !empty($_POST['userid'])){
$log_file = "sum_file.txt";
$logContent = file_get_contents("sum_file.txt");
$user = $_POST['username'];
$userId = $_POST['userid'];
if (!preg_match("/($user),\\s+($userId)\$/m", $logContent)) {
file_put_contents($log_file, "$user, $userId", FILE_APPEND);
}
}
I personally recommend you to use db , but still i may help you .. You should use json for this
function writeToFile($filename, $msg)
{
$msgArray=array();
if(file_exists($filename))
{
$arrMsg=json_decode(file_get_contents($filename),true);
if($msg['userId']==$arrmsg['userId'])
die('already there'); //checking done
foreach ($arrMsg as $ob)
{
array_push($msgArray,$ob);
}
unlink($filename);
}
array_push($msgArray,$msg);
$msgArrayJSON=json_encode($msgArray);
// open file
$fd = fopen($filename, "a");
// write string
fwrite($fd, $msgArrayJSON. PHP_EOL);
// close file
fclose($fd);
}
And by using the above function you may add user like
writeToFile('user.json', array("userId"=>$id,"userName"=>$name));
Finally , you could get users from file as below
$user_array=json_decode(file_get_contents('user.json'),true);

PHP Modify a single line in a text file

I tried and looked for a solution, but cannot find any definitive.
Basically, I have a txt file that lists usernames and passwords. I want to be able to change the password of a certain user.
Contents of users.txt file:
user1,pass1
user2,pass2
user3,pass3
I've tried the following php code:
// $username = look for this user (no help required)
// $userpwd = new password to be set
$myFile = "./users.txt";
$fh = fopen($myFile,'r+');
while(!feof($fh)) {
$users = explode(',',fgets($fh));
if ($users[0] == $username) {
$users[1]=$userpwd;
fwrite($fh,"$users[0],$users[1]");
}
}
fclose($fh);
This should works! :)
$file = "./users.txt";
$fh = fopen($file,'r+');
// string to put username and passwords
$users = '';
while(!feof($fh)) {
$user = explode(',',fgets($fh));
// take-off old "\r\n"
$username = trim($user[0]);
$password = trim($user[1]);
// check for empty indexes
if (!empty($username) AND !empty($password)) {
if ($username == 'mahdi') {
$password = 'okay';
}
$users .= $username . ',' . $password;
$users .= "\r\n";
}
}
// using file_put_contents() instead of fwrite()
file_put_contents('./users.txt', $users);
fclose($fh);
I think when you get that file use file_get_contents after that use preg_replace for the particular user name
I have done this in the past some thing like here
$str = "";
$reorder_file = FILE_PATH;
$filecheck = isFileExists($reorder_file);
if($filecheck != "")
{
$reorder_file = $filecheck;
}
else
{
errorLog("$reorder_file :".FILE_NOT_FOUND);
$error = true;
$reorder_file = "";
}
if($reorder_file!= "")
{
$wishlistbuttonhtml="YOUR PASSWORD WHICH YOU WANT TO REPLACE"
$somecontent = $wishlistbuttonhtml;
$Handle = fopen($reorder_file, 'c+');
$bodytag = file_get_contents($reorder_file);
$str=$bodytag;
$pattern = '/(YOUR_REGEX_WILL_GO_HERE_FOR_REPLACING_PWD)/i';
$replacement = $somecontent;
$content = preg_replace($pattern, $replacement, $str,-1, $count);
fwrite($Handle, $content);
fclose($Handle);
}
Hope this helps....
The proper way of doing this is to use a database instead. Databases can do random access easily, doing it with text files less so.
If you can't switch to a database for whatever reason, and you don't expect to have more than about a thousand users for your system, then it would be far simpler to just read the whole file in, convert it to a PHP data structure, make the changes you need to make, convert it back into text and overwrite the original file.
In this case, that would mean file() to load the text file into an array with each element being a username and password as a string, explode all elements on the array at the comma to get the username and password separately, make the changes you need to make, then write the modified data to disc.
You might also find fgetcsv() useful for reading the data. If you SplFileObject and have a recent version of PHP then fputcsv() may also be available to write the data back out.
However, just using a database is a far better solution. Right tool for the job.
$fn = fopen("test.txt","r") or die("fail to open file");
$fp = fopen('output.txt', 'w') or die('fail to open output file');
while($row = fgets($fn))
{
$num = explode("++", $row);
$name = $num[1];
$sex = $num[2];
$blood = $num[3];
$city = $num[4];
fwrite($fp, "Name: $name\n");
fwrite($fp, "Sex: $sex\n");
fwrite($fp, "Blood: $blood\n");
fwrite($fp, "City: $city\n");
}
fclose($fn);
fclose($fp);
If you're on a *nix system you could use sed; I find it neater than playing with file handles etc:
exec("sed -i '/^$username,.\+\$/$username,$userpwd/g' ./users.txt 2>&1", $output, $return);
If not I'd agree with GordonM and parse the file into a PHP data structure, manipulate it, then put it back:
$data = file_get_contents('./users.txt');
$users = array_map(function($line) {
return explode(',', $line);
}, explode("\n", $data));
foreach ( $users as $i => $user ) {
if ( $user[0] == $username ) {
$user[1] = $userpwd;
$users[$i] = $user;
}
}
file_put_contents('./users.txt', implode("\n", array_map(function($line) {
return implode(',', $line);
}, $users)));
There are, of course, an infinite number of ways of doing that!

fwrite - need a new line after variable - PHP

When my script writes to the file, it doesn't break the added content onto a new line.
Instead of:
user1:password1
user2:password2
It writes:
user1:password1user2:password2
Originally, my fwrite looked like this fwrite($fh, $data); and from searching other questions, I changed my code to this:
fwrite($fh, $data . "\n");
This does not seem to work though.
Here is my code
<?php
if (isset($_POST['submit']))
{
$username = $_POST['user'];
$password = $_POST['password'];
$confirmpw = $_POST['confirmpw'];
$username = strtolower($username);
//Check if passwords match
if ($password != $confirmpw){
print "Passwords do not match, please try again.";
}
else{
//the data
$data = "$username:$password\n";
//open the file and choose the mode
$fh = fopen("passwd.txt", "a+");
// Cycle through the array
$match_found = false;
while (($buffer = fgets($fh, 4096)) !== false)
{
// Parse the line
list($usercheck, $passwordcheck) = explode(':', $buffer);
if (trim($usercheck) == $username)
{
print "The username is already in our system. Please use another one.";
$match_found = true;
break;
}
}
if(!$match_found)
{
fwrite($fh, $data . "\n");
// Set cookies for an hour
$hour = time() + 3600;
setcookie("username", $username, $hour);
//Redirect to home page
header("location: index.php");
}
}
//close the file
fclose($fh);
}
?>
What you need to use is \r\n.
For me only worked PHP_EOL (xampp on windows 7 php 5.3.8)
Use PHP_EOL for the platform dependent newline character. However, \n actually represents the newline character in the *NIX-world, but some windows editors denies to show them as newline (thats what happens in your case). You should consider using an other IDE and always use \n for compatibility (if the file should be usable on other platforms).
"\r\n" use this instead will work like a charm

Categories