How to add more text to a file by php - php

Hello guys the following code will add only one line of text to my 'file.txt' whenever i m
going to add more text so its replacing the old one, i want to have the old one with new also
Beside this one i want to separate the words in my 'txt.file' by a comma and space.
Here is my code:
<?php
$Fname = $_POST['fname'];
$email = $_POST['email'];
$Phone = $_POST['number'];
$date = $_POST['date'];
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $Fname);
fwrite($handle, $email);
fwrite($handle, $Phone);
fwrite($handle, $date);
?>

Because you are using write mode (w). To add lines to the end, you have to append (a):
$handle = fopen($my_file, 'a');
To separate words by comma and space, join it into one string in PHP and than save it:
$finalString = $Fname . ', ' . $email . ', ' . $Phone . ', ' . $date;
fwrite($handle, $finalString );

//or you can use file_put_content to add to end of each line
$my_file = 'file.txt';
file_put_content($my_file, $Fname, PHP_EOL, PHP_APPEND);
file_put_content($my_file, $emai, PHP_EOL, PHP_APPEND);
file_put_content($my_file, $phone, PHP_EOL, PHP_APPEND);

Related

PHP - Difficulties Writing New Line [duplicate]

This question already has answers here:
Writing a new line to file in PHP (line feed)
(4 answers)
Closed 6 years ago.
I am encountering difficulties with writing to a new line in a basic text file. All the other text (including the comma) appears just fine, but no new line (no space or anything either). I would greatly appreciate any direction.
<?php
session_start();
$user = $_SESSION['store'];
function format($input) {
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$file = "messages/reminder.txt";
$image;
$secFreqLabel;
$freqLabel;
$uploadDirectory = "corpImages/";
if(!file_exists($file)) {
$temp = fopen($file, "w"); // create file
fclose($temp);
}
$con = new PDO("sqlite:bk.db");
if($_SERVER['REQUEST_METHOD'] == "POST") {
$secFreqLabel = 'reminder.jpg';
$freqLabel = 'reminderHourly.jpg';
$thirdFreqLabel = 'reminderThree.jpg';
$fourthFreqLabel = 'reminderFour.jpg';
$freqUploadFile = $uploadDirectory . $freqLabel;
$secFreqUploadFile = $uploadDirectory . $secFreqLabel;
$thirdFreqUploadFile = $uploadDirectory . $thirdFreqLabel;
$fourthFreqUploadFile = $uploadDirectory . $fourthFreqLabel;
$statement = $con->prepare("INSERT INTO slides (image, label) VALUES (:image, :label)");
if(!empty($_FILES['freqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminder.jpg'");
}
if(!empty($_FILES['secFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderHourly.jpg'");
}
if(!empty($_FILES['thirdFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderThree.jpg'");
}
if(!empty($_FILES['fourthFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderFour.jpg'");
}
$image = file_get_contents($_FILES['freqImage']['tmp_name']);
move_uploaded_file($_FILES['freqImage']['tmp_name'], $freqUploadFile);
$statement->bindParam(":label", $freqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['secFreqImage']['tmp_name']);
move_uploaded_file($_FILES['secFreqImage']['tmp_name'], $secFreqUploadFile);
$statement->bindParam(":label", $secFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['thirdFreqImage']['tmp_name']);
move_uploaded_file($_FILES['thirdFreqImage']['tmp_name'], $thirdFreqUploadFile);
$statement->bindParam(":label", $thirdFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['fourthFreqImage']['tmp_name']);
move_uploaded_file($_FILES['fourthFreqImage']['tmp_name'], $fourthFreqUploadFile);
$statement->bindParam(":label", $fourthFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$text = format($_POST['freq']) . "," . format($_POST['freqMessage']) . "\n" . format($_POST['secFreq']) . "," . format($_POST['secFreqMessage']) . "\n" . format($_POST['thirdFreq']) . "," . format($_POST['thirdFreqMessage']) . "\n" . format($_POST['fourthFreq']) . "," . format($_POST['fourthFreqMessage']);
$writer = fopen($file, "w");
fwrite($writer, $text);
fclose($writer);
touch("update.txt");
}
$handler = fopen($file, "r");
$firstReminder = fgetcsv($handler, ",");
$secondReminder = fgetcsv($handler, ",");
$thirdReminder = fgetcsv($handler, ",");
$fourthReminder = fgetcsv($handler, ",");
fclose($handler);
?>
Instead of using \n use constant called PHP_EOL which represents end of line according to your enviroment.
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 5.0.2
$text = format($_POST['freq']) . "," . format($_POST['freqMessage']) . PHP_EOL . format($_POST['secFreq']) . "," . format($_POST['secFreqMessage']) . PHP_EOL . format($_POST['thirdFreq']) . "," . format($_POST['thirdFreqMessage']) . PHP_EOL . format($_POST['fourthFreq']) . "," . format($_POST['fourthFreqMessage']);
PHP_EOL in windows will be CR+LF and in unix system LF
CR - Carriage Return, U+000D
LF - Line Feed, U+000A

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

Add to textfile doesn't work

I have created a small script to add a string to a text file, but it does not seem to work.
<?php
$email = $_POST["email"];
$name = $_POST["name"];
$city = $_POST["city"];
// Concatenate all values into one string.
$subscription = strtolower(trim($email)) . "," . ucwords(trim($name)) . "," . ucwords(trim($city));
$file = "21_nieuwsbrief.txt";
file_put_contents($file, (string)$subscription, FILE_APPEND);
echo $subscription;
?>
When testing this on the server, the echo $subscription shows the correct output.
But when I go to 21_nieuwsbrief.txt, it does not show any lines of text.
Could someone help me out here?
Thanks in advance.

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

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.

PHP - Adding predefined text as well as session variable using fwrite

In the following code, i want to be able to include 'Name:', 'Age:' and 'Email:' before the PHP script writes the variables $name, $age and $email.
It seems so simple, but i just can't get it to work!
<?php
session_start();
$name = $_SESSION['name'];
$age = $_SESSION['age'];
$email = $_SESSION['email'];
$handle = fopen('users.txt', 'a');
fwrite($handle, $name."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, $age."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, $email."\n");
fclose($handle);
?>
I have tried this:
<?php
session_start();
$name = $_SESSION['name'];
$age = $_SESSION['age'];
$email = $_SESSION['email'];
$handle = fopen('users.txt', 'a');
fwrite($handle, 'Name:', $name."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, 'Age:', $age."\n");
$handle = fopen('users.txt', 'a');
fwrite($handle, 'Email', $email."\n");
fclose($handle);
?>
However, all that prints in the user.txt document is 'Age:'.
Any help would be appreciated, thanks!
UPDATE: Removed the multiple fopen and replaced ',' with '.' Everything working perfectly, thanks for everyones help!
<?php
session_start();
$data = array(
'Name:' . (isset($_SESSION['name']) ? $_SESSION['name'] : '') ,
'Age:' . (isset($_SESSION['age']) ? $_SESSION['age'] : '') ,
'Email:' . (isset($_SESSION['email']) ? $_SESSION['email'] ; '') ,
);
if ($fp = fopen('users.txt','a')) {
fwrite($fp,implode(PHP_EOL,$data).PHP_EOL);
fclose($fp);
} else {
die('Error');
}
Use can use this
$fp = fopen('users.txt', 'a');
fwrite($fp, 'Name : '.$name . PHP_EOL);
fwrite($fp, 'Age : '.$age . PHP_EOL);
fwrite($fp, 'Email : '.$email . PHP_EOL);
fclose($fp);

Categories