Replace valuie in text file with php - php

i have a text file with the following design:
john smith|1|john#smith.com|nopassword|admin
Tom smith|3|tom#smith.com|admin123|user
....
And so on.
Every field is delimited by "|".
What i need to do is replace values for example the password or the account type of a user in this text file.
Tom smith|5|tom#smith.com|admin1234|admin
I succeeded in finding the line and spiting it with explode() but how do i modify the value and write it back on the text file ?
$name = $_POST['name'];
$mydb = file('./DB/users.txt');
foreach($mydb as $line) {
if(stristr($line,$name)) $pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);

There are various ways to do this. Here's one way. I commented the code to explain how it works.
$name = $_POST['name'];
// use FILE_IGNORE_NEW_LINES so you won't have to deal with the line breaks
$mydb = file('./DB/users.txt', FILE_IGNORE_NEW_LINES);
// use a reference (&$line) so the code in your foreach loop modifies the $mydb array
foreach ($mydb as &$line) {
if (stristr($line,$name)) {
// assign the elements of the row to variables
list($name, $number, $email, $password, $type) = explode('|', $line);
// change whatever you need to change
$password = 'new password';
$type = 'new type';
// overwrite the line with the modified values
$line = implode('|', [$name, $number, $email, $password, $type]);
// optional: break out of the loop if you only want to do the replacement
// for the first item found that matches $_POST['name']
break;
}
};
// overwrite the file after the loop
file_put_contents('./DB/users.txt', implode("\n", $mydb));

PHP gives the options of reading, writing, and appending to files.
You need to open the file, read all content in, and then overwrite the file. You will get duplicate entries using append.
Here is an example code from https://www.w3schools.com/php/php_file_create.asp:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
For your code:
<?php
$name = $_POST['name'];
$mydb = file('./DB/users.txt');
$output = array();
foreach($mydb as $line) {
if(stristr($line,$name)) {
$pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);
// Glue the variables back together and overwrite $line so that it gets up in the array
$line = $name & "|" $position & "|" $email & "|" $password & "|" $atype & "\r";
}
// put everything in the $output array so that it can be writen to file after this loop
array_push($output, $line);
}
fclose($mydb);
// Write your output to file
$mydb = fopen('./DB/users.txt', "w") or die("Unable to open file!");
foreach($output as $line) {
fwrite($mydb, $line);
}
fclose($mydb);
?>

Related

How to remove everything after a space in each of my array objects in PHP?

I have two arrays containing letters and numbers for each array object. example: "Matthew 20897". I want to delete the numbers from every array object so I can compare both arrays and see if they have any words/names in common. I tried doing an explode to get rid of the space but I get an error saying the explode() expects parameter 2 to be a string.
Below is the code I have so far:
<?php
//simple read file and print
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$word = fgets($connectionBoy); //read a record
$word = rtrim($word); //gets rid of end of record char
$boy[] = $word;
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$word2 = fgets($connectionGirl); //read a record
$word2 = rtrim($word2); //gets rid of end of record char
$girl[] = $word2;
}
fclose($connectionBoy);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$itemBoy = explode(" ",$boy);
$itemGirl = explode(" ",$girl);
$result =array_intersect($itemBoy,$itemGirl);
print_r($result);
Also, both arrays have 1000 records stored in them so I would have to remove everything after the space for all items in both arrays.
Use rtrim().
echo rtrim(' Removendo Espaços ');
https://www.php.net/manual/pt_BR/function.rtrim.php
http://www.mauricioprogramador.com.br/posts/remover-espacos-php-trim-ltrim-e-rtrim
From the docs:
explode — Split a string by a string
explode takes a string and splits it into an array. $boy and $girl are already arrays.
If I understand what you're trying to do, you could do get rid of the numbers inside your loops doing something like this:
$splitWord2 = explode(' ', $word2);
$girl[] = $splitWord2[0];
From your code I'm seeing you are using explode function in the wrong place. It should be in the while loop as string should be exploded there to get the first word of name.I have updated your code.
<?php
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$line = fgets($connectionBoy); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$boy[] = $parts[0];
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$line = fgets($connectionGirl); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$girl[] = $parts[0];
}
fclose($connectionBoy);
fclose($connectionGirl);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$result =array_intersect($boy,$girl);
print_r($result);
?>

php unable to open file when open and write into file

i try to read a text file line by line and if any line contain "/" then i need to write them into separate file.
example line
CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6
i need to write this as 4 lines, like
CA,T2B,Calgary,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Dover,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6
what i've tried so far is
$file = fopen("test.txt", "r");
while (!feof($file)) {
$my_string = fgets($file);
$special_chars = array("/");
if (array_intersect(str_split($my_string), $special_chars)) {
echo fgets($file) . "<br />";
$myfile = fopen("fileWithFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}else{
echo fgets($file) . "<br />";
$myfile = fopen("fileWithoutFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}
}
fclose($file);
[
file i get from "CA.zip"
how can i do this?
thank you!
You're repeatedly opening and closing fileWithFL.txt and fileWithoutFL.txt, which is inefficient. Better to just open them once before you loop through the input file.
You're also using fgets(), which makes it difficult to parse the input file. Since the input file seems to be in CSV format, you should use fgetcsv().
As for detecting rows that contain multiple cities, I'm looking for the presence of /, splitting on ( or /), removing any trailing ), and trimming the resulting name. That should give you all the cities in a neat array.
$file = fopen("test.txt", "r");
$file_with_fl = fopen("fileWithFL.txt", "w+");
$file_without_fl = fopen("fileWithoutFL.txt", "w+");
while ($a = fgetcsv($file)) {
if ( FALSE == strpos( $a[2], '/' ) ) {
fputcsv( $file_without_fl, $a );
} else {
$cities = preg_split( '/[\(\/]/', $a[2] ); // Split on '(' and '/'
foreach ( $cities as $city ) {
$city = trim(preg_replace('/\)/', '', $city)); // Remove trailing ')' and trim leading and trailing spaces
$a[2] = $city;
fputcsv( $file_with_fl, $a );
}
}
}
Checking for failure of fopen() and fputcsv() left as an exercise for the reader.
You can use file_put_contents(file, string, FILE_APPEND) to add a line to the end of a file.
The rest is just processing the Calgary (Forest Lawn / Dover / Erin Woods) part of your string.
$string = 'CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6';
//test if string needs processing
//if not, write straight to new file
if(strpos($string,'/') === false){
file_put_contents("fileWithoutFL.txt" , $string , FILE_APPEND);
}
//process
else{
//get all the parts split by comma
//$parts[2] is the one you need processing
$parts = explode(',',$string);
//clean up $part[2], replacing ( , ) with *
//then split on the *
$com=explode('*',str_replace(['(','/',')'],'*',$parts[2]));
//loop $com, creating new arrays by replacing $part[2] in the original array
foreach($com as $val){
if($val == '')continue;
//replace $part[2] cleaning up spaces
$parts[2] = trim($val);
//make a new line
$write = implode(',',$parts);
//write to the new file
file_put_contents("fileWithoutFL.txt" , $write , FILE_APPEND);
}
}
Now you can read every line of the original file and output to the new file. (Tip: use SplFileObject)
$file = new SplFileObject("fileWithFL.txt");
while (!$file->eof()) {
$string = $file->fgets();
// ... process here with previous code
}
$file = null;
Not the best answer but its works
$line = file_get_contents("test.txt");
$body = "";
if(false !== strpos($line,"/")) {
$split = preg_split("/[()]+/", $line,-1, PREG_SPLIT_NO_EMPTY);
$contains = explode("/",$split[1]);
$last = explode(",",$split[0]);
$lastvalue = end($last);
$search = array_search($lastvalue,$last);
unset($last[$search]);
$merge = implode(", ", $last);
$body .= $merge . $split[2] . " ";
foreach($contains as $contain) {
$body .= $split[0] . "," . $contain . $split[2] . " ";
}
if(file_put_contents("fileWithFL.txt",$body) !== false) {
echo $body;
} else {
echo "failed";
}
} else {
if(file_put_contents("fileWithoutFL.txt",$line) !== false) {
echo $line;
} else {
echo "failed";
}
}
Output :
CA, T2B,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary ,Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Dover ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6

Search a string and delete the whole line containg the string in php

I need to search a string in .cfg file, and delete the whole line. I'm using file_get_contents to retrieve the the data in .cfg file, and I'm storing it in a variable, searching is good but not knowing how to delete the whole line?
I have a string in following way:
user $username insecure-password $password
I want to search $username and delete the whole line.
Use a little Regex to match the line:
<?php
$file = 'blah
etc
user delboy1978uk insecure-password 123456
etc
etc';
$regex = '#\nuser\s\w+\sinsecure-password\s.+\n#';
preg_match($regex, $file, $matches);
$file = str_replace($matches[0], "\n", $file);
echo $file;
Which outputs:
blah
etc
etc
etc
See it here: https://3v4l.org/BcDWK
With this method you can read each config file line by line search in each line.
$h = fopen('yourfile', 'r') ;
$match = 'username' ;
$output = [] ;
if ($h) {
while (!feof($h)) {
$line = fgets($h);
//your current search function, which search each line
if ( your_search_function($line, $match) === false) {
//array $output will not contain matching lines.
$output[] = $line;
}
}
fclose($h);
//write back to file or do something else with $output
$hw = fopen('yourfile', 'w') ;
if( $hw ) {
foreach( $output as $line ) {
fputs($hw, $line) ;
}
fclose($hw) ;
}
}

Inserting PHP objects to database

<?php
class Prof {
function get_block($lines, $prof_num) {
$reserve = 200;
$strings = implode("", $lines);
$start_line = preg_grep("/1\.$prof_num\.1\./m", $lines);
$prof_num+=1;
$end_line = preg_grep("/1\.$prof_num\.1\./m", $lines);
$prof_num-=1;
$start_pos = mb_strpos($strings, end($start_line));
$end_pos = mb_strpos($strings, end($end_line));
$finalContent = mb_substr($strings, $start_pos-$reserve, $end_pos-$start_pos+$reserve);
$from = "1.$prof_num";
$prof_num+=1;
$to = "1.$prof_num";
$cutted = mb_substr($finalContent, strpos($finalContent, $from), strpos($finalContent, $to));
$cutted = preg_replace("/$to\..*/", "", $cutted);
// echo $cutted;
// $this->get_id($cutted);
// $this->get_name($cutted);
}
function get_id($txt) { //gettind id
$txt = explode("\n", $txt);
$id = preg_grep("/\d\.\sCode\s/", $txt);
$id = preg_replace("/\d\.\sCode\s\–\s/","", $id);
$id = preg_replace("/\t/", "",$id);
$id = preg_replace("/\.\s+/", "",$id);
foreach($id as $item) {
echo $item ."\n";
}
}
function get_name($txt) { //getting name
$txt = explode("\n", $txt);
$name = preg_grep("/\sName/", $txt);
$name = preg_replace("/\d\.\sName\–\s/","",$name);
$name = preg_replace("/\t/", "",$name);
$name = preg_replace("/\.\s+/", "",$name);
foreach($name as $item) {
echo $item ."\n";
}
}
Obj1 = new Prof();
Obj1 -> get_name(get_block(file('text.txt'))); //ERROR HERE!!!!!!!!
How can I get to get_id and get_name through get_block method?
- get_block gets me the whole text from text file, starting from line number $prof_num.
- get_id gets me the id from the get_block text block. get_name just gets the name from
get_block.
I need to write these methods (id and name) to my database, but as I know, I can't do it, if I only manage to get text block with get_block.
Pls, ask me if something, maybe I just can't explain it. :D
This is wrong:
Obj1 -> get_name(get_block(file('text.txt')))
The function get_block() is not defined, it is a method of your Pro class.
So you would need:
$Obj1->get_name($Obj1->get_block(file('text.txt')));
or, if it is a static method:
$Obj1->get_name(Pro::get_block(file('text.txt')));
Also note that get_block() is defined as a method that takes 2 parameters, something that looks like a string (based on the name...) and a number (based on the name...). So sending it only an array - the return value of file() - will also fail.

Match & Replace a certain line of a text file

I am trying to setup a way where users can change the password to a certain area of a website they have access too and that password is stored as part of a .cfg text file. That is the file I need to pull it from. The contents of the file looks like this:
[main]
roomname = "Room Name"
topfile = /my/link/here
bannerfile = /my/link/here
bannersfile = /my/link/here
banner_freq = 40
bodyfile = /my/link/here
configfile = /my/link/here
actionfile = /my/link/here
memberfile = /my/link/here
moderatorfile = /my/link/here
logfile = /my/link/here
bootfile = /my/link/here
numusers = 30
password = mypassword
defaultmessage = "$USER$ : $SAYS$"
messagewrapper = '<TABLE WIDTH="100%" border=0 cellpadding=0 cellspacing=0><TR><TD>($DATESTAMP$ : $TIMESTAMP$) $PROVE$ $REGISTERED$ $MOD$ $MESSAGE$</TD></TR></TABLE><P>'
I have the change password form created, however what I am having trouble with is the .php file to process the form. I've been reading manuals but am not quite sure what else is missing or certain variables to use.
====
Edit/Update
I am updating my code below with my save.php form. It seems to be working except that its overwriting the entire file blankly and I'm not sure why its doing that. I'm also including my form coding from the send page.
<?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['password'];
$filevar = '/my/site/location/here/prpwtest/prtest.txt';
$fh = fopen($filevar, "w");
$file_contents = file_get_contents($filevar);
$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
if (strpos($lines[$i], 'password = ') === 0)
fwrite($fh, 'password = '.$data.'\r'); // put new password instead of old one
else
fwrite($fh, $lines[$i]); // keep old line
$success_page = '/my/site/location/here/pulldowns/savesuccessful.html';
header('Location: '.$success_page);
}
}
?>
And here is a snippet of my save code:
<form name="loginform" method="post" action="my/site/location/here/prpwtest/prpwtestsave.php">
<input name="password" type="password" /><p><input name="Submit" type="submit" /></form></p></center>
</div>
Give this a try:
$fileurl = '/path/to/my/file/here/file.cfg';
$replace = 'what I want to put in there when they submit';
$file = file($fileurl, FILE_IGNORE_NEW_LINES); // Get file as array of lines
foreach ($file as $n=>$line)
if (substr($line, 0, 8) === 'password') // Line starts with 'password'
$file[$n] = 'password = '.$replace; // Replace password line
file_put_contents($fileurl, implode("\n", $file)); // Put file back together
You need to parse data from $file_contents.
I.e. after reading of this string, you have to process it line by line to find string starting with 'password=' to modify it. You can use explode() for splitting of this string:
$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
if (strpos($lines[$i], 'password = ') === 0)
fwrite($fh, 'password = '.$newpassword.'\r'); // put new password instead of old one
else
fwrite($fh, $lines[$i]); // keep old line
}
Try this.
$array = parse_ini_file('your_ini_file.ini', 'main');
$array['main']['password'] = 'set your password here';
$str = '[main]'."\r\n";
foreach($array['main'] as $key => $value){
$str .= $key.' = '.$value."\r\n";
}
file_put_contents('test.ini', $str, LOCK_EX);

Categories