php writing additional lines to encrypted files? - php

I'm trying to open an encrypted file that will store a list of information, then add a new ID with information, and save the file back as it was originally encrypted. I have xor/base64 functions that are working, but I am having trouble getting the file to retain old information.
here is what I am currently using:
$key = 'some key here';
$id = $_GET['id'];
$group = $_GET['group'];
$file = "groups.log";
$fp = fopen($file, "w+");
$fs = file_get_contents($file);
$filedec = xorstr(base64_decode($fs),$key);
$info = "$id: $group";
$filedec = $filedec . "$info\n";
$reencode = base64_encode(xorstr($filedec,$key));
fwrite($fp, $reencode);
fclose($fp);
function xorstr($str, $key) {
$outText = '';
for($i=0;$i<strlen($str);)
{
for($j=0;$j<strlen($key);$j++,$i++)
{
$outText .= $str[$i] ^ $key[$j];
}
}
return $outText;
}
?>
It should save an entire list of the ID's and their corresponding groups, but for some reason it's only showing the last input :(

I wouldn't call this encryption. "cereal box decoder ring", maybe. If you want encryption, then use the mcrypt functions. At best this is obfuscation.
The problem is that you're doing fopen() before doing file_get_contents. Using mode w+ truncates the file to 0-bytes as part of the fopen() call. So by the time file_get_contents comes up, you've deleted the original file.
$fs = file_get_contents(...);
$fh = fopen(..., 'w+');
in that order will fix the problem.

Related

PHP fgets() won't work unless it's implemented with a variable?

I'm writing some code that can read in from a .txt file a display it on a webpage.
I had problems in my initial code, in that it would read in any text and it would erase whatever was in the document.
My original code:
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$line = fgets($input);
fclose($input);
return $line
}
It only started working once I put in a While loop to go through EVERY LINE
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$fullText = ""; //Variable full text
while(!feof($input)){
$line = fgets($input);
$fullText = $fullText . $line;
}
fclose($input);
return $fullText;
}
echo readIn();
Use "file_get_contents" to read an entire file into a variable, and then output in whatever fashion you choose.

PHP Write and Read from Text File

I have an issue with writing and reading to text file.
I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:
Write to text file:
$fp = #fopen ("text1.txt", "r");
$fh = #fopen("text2.txt", 'a+');
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$thisline = fgets($fp);
$thisline1 = trim($thisline);
$stringData = $thisline1. "\r\n";
fwrite($fh, $stringData);
fwrite($fh, "test");
}
}
fclose($fp);
fclose($fh);
Read from the written textfile
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
echo rtrim($kw[$i]);
}
But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.
How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.
I'm not sure whether you have issues with the even line numbers or with reading the file back in.
Here is the solution for the even line numbers.
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$myValue = rtrim($kw[$i]);
if(i % 2 == 0)
{
echo $myValue;
}
}

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 do I read each line from a file in php?

I'm new to learning php and in one of my first programs I wanted to make a basic php website with login capabilities with and array of the user and passwd.
my idea is to store the username as a list parameter and have the passwd as the contents, like this:
arr = array(username => passwd, user => passwd);
now my problem is that I don't know how I can read from the file (data.txt) so I can add it into the array.
data.txt sample:
username passwd
anotherUSer passwd
I've opened the file with fopen and stored it in $data.
You can use the file() function.
foreach(file("data.txt") as $line) {
// do stuff here
}
Modify this PHP example (taken from the official PHP site... always check first!):
$handle = #fopen("/path/to/yourfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
to:
$lines = array();
$handle = #fopen("/path/to/yourfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
lines[] = $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
// add code to loop through $lines array and do the math...
Be aware that you should not store login details in a textfile that in addition is not encrypted, this approach has severe security issues.
I know you are new from PHP, but the best approach is to store it in a DB and crypting the passwords with an algorithm such as MD5 or SHA1,
You shouldn't store sensitive information as plaintext, but to answer your question,
$txt_file = file_get_contents('data.txt'); //Get the file
$rows = explode("\n", $txt_file); //Split the file by each line
foreach ($rows as $row) {
$users = explode(" ", $row); //Split the line by a space, which is the seperator between username and password
$username = $users[0];
$password = $users[1];
}
Take a look at this thread.
This works for extremely large files as well:
$handle = #fopen("data.txt", "r");
if ($handle) {
while (!feof($handle)) {
    $line = stream_get_line($handle, 1000000, "\n");
//Do Stuff Here.
}
fclose($handle);
}
Use file() or file_get_contents() to create either an array or a string.
process the file contents as needed
// Put everything in the file in an array
$aArray = file('file.txt', FILE_IGNORE_NEW_LINES);
// Iterate throug the array
foreach ($aArray as $sLine) {
// split username an password
$aData = explode(" ", $sLine);
// Do something with the username and password
$sName = $aData[0];
$sPass = $aData[1];
}

Define array of file locations, parse and replace. Where's my error?

I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.

Categories