php replace an string on exist file .env - php

my question is similiar like this : Replace string in text file using PHP
but i want replace by spesification variable
for example, i have already file exist .env
variable_1=data_2021
variable_99=data_2050
variable_991=data_2061
so how i can replace by spesificiation name variable for the value ?
i want replace data_2050 with data_2051 without change on other text where the variable is variable_99
$myfile = fopen("../../.env.securepay", "w") or die("Unable to open file!");
fwrite($myfile, 'variable_99='.$value);
fclose($myfile);
// $myfile = fopen("../../.env", "w") or die("Unable to open file!");
// fseek($myfile, 0);
// fwrite($myfile, 'variable_99 ='.$value);
// fclose($myfile);
// $oldMessage = 'variable_99';
// $deletedFormat = '';
// //read the entire string
// $str=file_get_contents('../../.env.securepay');
// //replace something in the file string - this is a VERY simple example
// $str=str_replace($oldMessage, $deletedFormat, $str);
// //write the entire string
// file_put_contents('../../.env', $str);
above code just remove all the content file .env and re added variable_99=value

You can use file_put_contents and parse_ini_file like this follow below
function modifyEnv($path,$values = []) {
$env = [];
foreach(parse_ini_file($path) as $k => $value) {
if(in_array($k,array_keys($values))) {
$env[$k] = "$k={$values[$k]}";
}
}
return file_put_contents($path,implode(PHP_EOL,$env));
}
Then you can call like this, you can replace multiple .env variables by using array key, value. key is the old value and the value is the new value
modifyEnv('../../.env.securepay',[
'variable_99' => 'data_2051',
'variable_1' => 'data_2051'
]);

Related

Check if value is in an array created from a txt file

I want to check if a value is in array created from a text file (a list of email addresses).
Why neither of these solutions work? (foreach or in_array)
(I've tried printing the array $text and it's ok, no problem coming from file.txt, same thing with $search)
$myfile = fopen("file.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$text[] = fgets($myfile);
}
fclose($myfile);
$search=$_POST['something'];
foreach ($text as $val) {
if (strpos($search, $val) !== FALSE) {
echo "oK";
}
}
/* OR * /
if (in_array($search, $text)) {
echo "OK"; }
Personally, I would not put an entire file input input into an array as its a waste of memory you're already using reading from a file (specially if its large).
You can instead do your "like" condition inside of the loop. I would use str_contains for ease if your PHP version supports it. Build an array based on found results.
if (!isset($_POST['something'])) die('Missing search term');
# TODO: Handle this Exception better
$emails = fopen("file.txt", "r") or die("Unable to open file");
$similarEmails = [];
while(!feof($emails))
if (str_contains(($line = fgets($emails)), $_POST['something']))
$similarEmails[] = $line;
fclose($emails);
References:
str_contains

Trying to build a file in PHP and use fwrite to file

trying to figure out how i can make a and save a file while including default info from another file. i tried include but it did not work. any suggestion on how to build this file?
<?php
$wrtID = $_POST["fileID"];
SQL statement here to get relevant info
mkdir("CNC/$wrtID", 0770, true);
?>
<?php
$batfile = fopen("CNC/$wrtID/$wrtID.bat", "w") or die("Unable to open file!");
$txt = "
#ECHO OFF
#ECHO **** Run NC-Generator WOODWOP 4.0 ****
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sl.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sr.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-tb.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-dc.mpr
#ECHO **** Done ****
";
fwrite($batfile, $txt);
fclose($batfile);
?>
<?php
$slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
$txt = "
include("defaultcnc.php");
if ( additional file pats needed ) {
include("component-1.php");
}
";
fwrite($slfile, $txt);
fclose($slfile);
?>
I don't see a problem in the first block of code.
On the second block, the interpreter will consider the second double quotes to mean the end of the string $txt = " include(". So everything after that would produce a PHP error.
But even if you escape those the mpr file will have the string include("defaultcnc,php"); but not the actual contents of that file. For that you should do file_get_contents("defaultcnc.php").
something like:
<?php
$slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
// set params to pass to defaultcnc.php
$value1 = 1;
$value2 = "I'm a text string";
$file = urlencode("defaultcnc.php?key1=".$value1."&key2=".$value2);
$txt = file_get_contents($file);
if ( additional file pats needed ) {
$txt .= file_get_contents("component-1.php");
}
fwrite($slfile, $txt);
fclose($slfile);
?>
I assume additional file pats needed means something to you. It should be a condition evaluating either true or false.

How to make fwrite() write in the middle of the text file

$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "w") or die("Unable to open file!");
fwrite($myfile, $steps);
fclose($myfile);
echo $steps;
This is my code, The issue is that it is replacing the whole .txt file with just $steps while Test1|b7f2b0b64a3c60a367b40b579b06452d|Male|0|a|02/05/2016|1 is in the text file which therefore it ends up being just 32 if $steps = 32; in the text file, I want to replace the 0 with $steps = $_GET['id'];
hint I know its something like this
explode('|',$....)
It's because you are replacing the file's contents entirely, with $steps, which only contains the $_GET['id'].
Your explode idea can work towards this end, if you are sure that the steps will always be in the same place. Then it'd go somewhat like this.
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "w") or die("Unable to open file!");
//explode on the |
$userData = explode('|', stream_get_contents($myfile));
//This should be the steps data. Replace it with the new value
$userData[3] = $steps;
//put the exploded string back together with the new steps value
fwrite($myfile, implode("|", $userData));
fclose($myfile);
fopen and fclose are quite intense operations for such small files, though. A possibly faster way (and easier, too!) is to do it like this:
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = file_get_contents("save/$username.txt");
//explode on the |
$userData = explode('|', $myfile);
//This should be the steps data. Replace it with the new value
$userData[3] = $steps;
//put the exploded string back together with the new steps value
file_put_contents("save/$username.txt", implode("|", $userData));
p.s. you can use $variables within the double " strings.
Note that you are using the w file mode, which will truncate the file on opening it. This means you will be losing data if you don't set it aside first. As per the documentation:
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Using fgetcsv you could first read the data and then save the entire string back to the file:
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "r+") or die("Unable to open file!");
// Get the current data from the file
$data = fgetcsv($myfile, 0, '|');
// Now replace the 4th column with our steps
$data[3] = $steps;
// Now truncate the file
ftruncate($myfile, 0);
// And save the new data back to the file
fwrite($myfile, implode('|', $data));
fclose($myfile);

Need help - php save .txt

I need your help.
I need to every time the code stores the information in txt file, then each new record to the new line and what should be done to all be numbered?
<?php
$txt = "data.txt";
if (isset($_POST['Password'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['Password'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
Added some comments to explain the changes.
<?php
$file = "data.txt"; // check if both fields are set
$fh = fopen($file, 'a+'); //open the file for reading, writing and put the pointer at the end of file.
$word=md5(rand(1,10)); //random word generator for testing
fwrite($fh,$word."\n"); // Write information to the file add a new line to the end of the word.
rewind($fh); //return the pointer to the start of the text file.
$lines = explode("\n",trim(fread($fh, filesize($file)))); // create an array of lines.
foreach($lines as $key=>$line){ // iterate over each line.
echo $key." : ".$line."<br>";
}
fclose($fh); // Close the file
?>
PHP
fopen
fread
explode
You can do like this in a more simpler way..
<?php
$txt = "data.txt";
if (isset($_POST['Password']) && file_exists($txt))
{
file_put_contents($txt,$_POST['Password'],FILE_APPEND);
}
?>
we open file to write into it ,you must make handle to a+ like php doc
So your code will be :
<?php
$fileName = "data.txt"; // change variable name to file name
if (isset($_POST['Password'])) { // check if both fields are set
$file = fopen($fileName, 'a+'); // set handler to a+
$txt=$_POST['Password'];
fwrite($file,$txt); // Write information to the file
fclose($file); // Close the file
}
?>

How to replace one line in php?

I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/

Categories