PHP fwrite() how to insert a new line after some specific line - php

I'm new here.
Anyway, I did my research on fwrite(), but I couldn't find solution, so i'm asking for help.
What I want is f.e. to add a new line of text after some other specific line.
F.e. I have a .txt file in which there is:
//Users
//Other stuff
//Other stuff2
Now what I'd like to do is be able to add a new user below //Users without touching "Other Stuff" and "Other Stuff 2". So it should look something like this:
//Users
Aneszej
Test321
Test123
//Other stuff
//Other stuff2
What I have so far:
$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");
$date = date("F j, Y");
$time = date("H:i:s");
$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time;
while (!feof($file)) {
$line=fgets($file);
if (strpos($line, '//Users')!==false) {
$newline = PHP_EOL . $newuser;
}
}
fwrite($file, $newline);
fclose($file);
test.txt file
//Users
//Something Else
//Something Else 2
But this only writes users to the end of the .txt file.
Thanks a lot everyone for your help! It's solved.

I modified your code, I think follows is what you need, and I also put comment, function below will keep adding new user, you can add condition that to check user exist.
$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");
$date = date("F j, Y");
$time = date("H:i:s");
$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time."\r\n"; // I added new line after new user
$insertPos=0; // variable for saving //Users position
while (!feof($file)) {
$line=fgets($file);
if (strpos($line, '//Users')!==false) {
$insertPos=ftell($file); // ftell will tell the position where the pointer moved, here is the new line after //Users.
$newline = $newuser;
} else {
$newline.=$line; // append existing data with new data of user
}
}
fseek($file,$insertPos); // move pointer to the file position where we saved above
fwrite($file, $newline);
fclose($file);

You write the new content at the end of the reading, so it has to write at the end of file - the cursor is there after reading all the lines.
Either you store all the content in php-variable and overwrite the file in the end, or you rewind the curser with fseek as mentioned by Robert Rozas comment. That should be done as soon as you read the "Something else" - line.

Try fseek:
<?php
$file = fopen($filename, "c");
fseek($file, -3, SEEK_END);
fwrite($file, "whatever you want to write");
fclose($file);
?>
PHP Doc: http://php.net/manual/en/function.fseek.php

You need to break after you find '//Users'. You keep reading to the end of the file.

Related

How do I create a new log file if my current log file is larger than 50mb in php?

I have a project where I have to make a new log file if the current log file is larger than 50mb. I know that we have to test for the size of the file.
I am starting out with this $log variable:
$log =
"Branch: ".$branchDir . PHP_EOL.
"Phase: ". $phaseDir . PHP_EOL.
"Total number of results files deleted: ". count($folderCounter). PHP_EOL.
"File names: " . $filePathToDelete . PHP_EOL.
"Starting CustomerID directory name: " . $CustIDvalue . PHP_EOL;
// $log = 'this is a test' . $branch . PHP_EOL;
$dt = time();
$mysql_datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
$mysql_datetimes = preg_replace('/\s+/', '', $mysql_datetime);
$logFileName = "ResultsFileDeletion" . $mysql_datetimes . ".txt";
if (unlink($filePathToDelete)) {
//this echo string will be moved to a log file
echo "first unlink: {$filePathToDelete} was deleted <br>";
$myFile =
file_put_contents("c:\\sites\\EtonBio/sequencing/logs/{$logFileName}",
$log, FILE_APPEND);
echo 'my file: ' . $myFile . '<br>';
}
I found this code snippet:
$size = filesize($_FILES['foto']['tmp_name']);
I believe my if statement would look something like this:
if($size < 52428800) {
*creates another log file
}
I want to format the $size variable correctly and I am also not sure how to make a new log file.
$size = filesize($_FILES['foto']['tmp_name']); only works if you are uploading the file.
If you want to check a file already in you server ou can simply do
$size = filesize("path/to/file");
Also, there is a ' in your $log declaration that shouldn't be there

PHP fopen() invalid argument

I'm running this code once the user submits a form. The idea is to save a new file called "message_timestamp" where timestamp is the current date and time. It need to be saved in the misc folder, which is located in the same directory as this php file.
My code:
if (isset($_POST['submitIssue'])) {
$type = $_POST['typeOfIssue'];
$prefName = $_POST['preferredName'];
$email = $_POST['userEmail'];
$details = $_POST['detailedReport'];
date_default_timezone_set('Atlantic/Bermuda');
$date = new DateTime('now');
$date = $date->format('Y-m-d_H:i:s');
$date = trim($date);
$fileName = "misc/message_" . $date;
$out = "Issue Alert!\nType of issue: " . $type . "\n\nSubmitted by " . $prefName . "\nEmail ID: " . $email . "\nSubmitted at: " . $date . "\n\nDetails: " . $details;
$myFile = fopen($fileName,"w") or die("Cannot open file!");
fwrite($myFile, $out);
fclose($myFile);
}
I've tried removing whitespaces and looking for escape characters. But as long as $date is appended to the filename, I get the error:
fopen(misc/message_2018-02-0210:47:41): failed to open stream: Invalid
argument in C:\MAMP\htdocs\A2\report.php on line 76
I can get it to work if I don't put the timestamp on it. Any suggestions?

String adding new lines and I don't understand why

I have got this code to open each file in a folder, decrease a value by 5 and then overwrite the existing content.
<?php
foreach (glob("users/*.php") as $filename) {
$array = file($filename);
$wallet = $array[0];
$time = $array[1];
$status = $array[2];
$steamid = $array[3];
$process = fopen($filename, "w") or die("Unable to open file!");
$time = $time - 5;
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
fwrite($process, $newdata);
fclose($process);
}
?>
Before I execute the script, the files that are opened look like this:
680
310
0
74892748232
After the script was executed, the file looks like this:
680
305
0
74892748232
If the script is executed again, it adds more lines and just breaks the files even more.
The string for the file is created here:
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
Why does it add an empty line after $wallet and $status, but not after $time? How can I avoid this and instead write down:
$wallet
$time
$status
$steamid
Thanks a lot in advance.:)
Try with this solution
You can also use file_put_contents():
file_put_contents($filename, implode("\n", $array) . "\n", FILE_APPEND);
from this SO question
https://stackoverflow.com/a/3066811/1301180

PHP fopen() won't write to txt files in some cases

I'm not sure if it has to do with my permissions for file writing, or if I'm just plain doing it wrong.
Here is my PHP code:
Note: this is located in www.sitename/folder1/folder2/index.php
$user = $_POST['user'];
$pass = $_POST['pass'];
$fp = fopen("../folder1/test.txt", "a");
$savestring = $user . "\n" . $pass . "\n";
fwrite($fp, $savestring);
fclose($fp);
It doesn't work. It says it is unwritable.
I tried this too: /folder1/test.txt
and http://sitename.com/folder1/test.txt
The only thing that works is fopen("folder1/test.txt"a");, but that writes to www.sitename.com/folder1/folder2/folder1/test.txt, which is what I completely do not want.
Is it something I did wrong?

php fopen - name of file

I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'

Categories