fwrite - need a new line after variable - PHP - 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

Related

php - one time access by looking up serial in a .dat file

i've now written this short script.
It records a serial or token number, checks to see if its in a .dat file, and allows access if its present. Otherwise it denies access to the site.
It also removes the token from the file once it has been redeemed as it were.
However, when i add multiple tokes in the dat file, the code doesn work properly. It only works with a single entry. How would i make it work for multiple entries.
im thinking of maybe implementing some sort of array somewhere? or explode?
index.php
require_once "married.php";
session_start();
$url_request = (isset($_SERVER['HTTPS']) ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ip = $_SERVER['REMOTE_ADDR'];
$token = substr($url_request,45);
$_SESSION["cookie"] = $token;
$tk = $_SESSION["cookie"];
$ips = array();
$page = file("urls.dat");
foreach($page as $line)
{
array_push($ips, $line);
}
if(in_array($tk, $ips))
{
//header("Location: mysite.co.uk");
echo "<title>My Site</title>Here is my site";
$file = fopen("ip_match.dat","a");
fwrite($file,$tk . " " . $ip . "\r\n");
fclose($file);
$oldMessage = $_SESSION["cookie"];
$deletedFormat = "";
$str=file_get_contents('urls.dat');
$str=str_replace("$oldMessage", "$deletedFormat",$str);
file_put_contents('urls.dat', $str);
exit;
} else {
echo ("<title>404 Not Found</title>
<h1>Not Found</h1>The requested URL was not found on this server.
<br>
<br>
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. test");
exit;
}
urls.dat
1089yht
url: http://mmmmmmmmmmmmm.co.uk/url/index.php?key=1089yht
ps. Happy Holidays all!
Look at JSON. You could do something like this:
$tokens = ['foo', 'bar'];
file_put_contents('urls.json', json_encode($tokens));
// and then you can decode it back
// returns ['foo', 'bar']
$decodedTokens = json_decode(file_get_contents('urls.json'));
If you still want to use simple text file, you could save every record at new line and then load line by line.
$tokens = [];
while(! feof($file)) {
$line = fgets($file);
// or save to array
$tokens[] = $line;
}
fclose($file);
try
$str = preg_replace("/{$oldMessage}/", $deletedFormat, $str, 1);
Instead of
$str=str_replace("$oldMessage", "$deletedFormat",$str);
Because: str_replace replaces everything.
preg_replace lets you limit how many replacements.

HTPASSWD Automatic

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.

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!

How to Search and Find in Txt file. Then Using The Found Variable

OK, this is Another Project Im Working ON.
Its a Chat Client. and Using it For Staff
I want the server to have a staff.txt on it.
and I want the php file to do this.
Execute the php.
if The Submitted Username is Found in the staff.txt then
The Username changes to [Staff]"Username Here"
I got the search and find down.
I Cant seem to keep the username that was submitted, and just adding staff to it.
Im Adding my Source Now.
<?php
// Parameters (Leave this Alone)
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$time = ($_GET["time"]);
// User Banning
$data = file_get_contents('Banned.txt');
if(strpos($data, $Username) !== FALSE)
{
die();
}
else
{
// File Writing (Leave this Alone)
$File = "Chat.txt";
$Handle = fopen($File, "a");
fwrite($Handle, $Username);
fwrite($Handle, ": ");
fwrite($Handle, $Message);
fwrite($Handle, " -:-:- ");
fwrite($Handle, $time);
fwrite($Handle, "\r\n");
print "Message Sent";
fclose($Handle);
}
?>
I have user banning working, and i Want the Staff To Work in the same way.
Any Help would be appreciated
Trying it a different way
If ($Username=="!divider!StaffMember1") $Username="!divider![Staff] StaffMember1";
If ($Username=="!divider!StaffMember2") $Username="!divider![Staff] StaffMember2";
that seems to work fine in the php file thats running the php with everything else.
Is there a way to have that list in a seperate file? .txt file or .php doesnt matter.
You can just do it like the banlist:
<?php
// Parameters (Leave this Alone)
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$time = ($_GET["time"]);
// check staff
$data = file_get_contents('staff.txt');
if(strpos($data, $Username) !== FALSE)
$Username = '[STAFF]' . $Username;
// User Banning
$data = file_get_contents('Banned.txt');
if(strpos($data, $Username) !== FALSE)
{
die();
}
else
{
// File Writing (Leave this Alone)
$File = "Chat.txt";
$Handle = fopen($File, "a");
fwrite($Handle, $Username);
fwrite($Handle, ": ");
fwrite($Handle, $Message);
fwrite($Handle, " -:-:- ");
fwrite($Handle, $time);
fwrite($Handle, "\r\n");
print "Message Sent";
fclose($Handle);
}
?>

how to implement FILTER_SANITIZE_SPECIAL_CHARS

here's what I've got so far - i really need to ban any tags from being entered as it's like a guestbook, but this doesn't seem to work:
<?php
$txt = $_POST['txt'];
//the data
$data = "
$txt";
//my attempt to implement a filter
var_dump(filter_var($data,FILTER_SANITIZE_SPECIAL_CHARS));
//open the file and choose the mode
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
//close the file
fclose($fh);
header('Location: http://www.google.com/');
?>
You need to assign the returned value of filter_var
$data = filter_var($data,FILTER_SANITIZE_SPECIAL_CHARS);
filter_var can return FALSE if the filter fails. So, to be complete, you really should do something like:
$filtered_data = filter_var($data,FILTER_SANITIZE_SPECIAL_CHARS);
if($filtered_data !== FALSE) {
//write $filtered_data
} else {
//handle error
}

Categories