I've tried everything I could think of yet I still couldn't get the code to delete the new line character that is appended at each new entry.
if ($_POST['what_to_do']==1){
if ((isset($_POST['chat_name'])) and ($_POST['chat_name']!=NULL)){
$chat_name=$_POST['chat_name'];
$myfile = fopen("users.txt", "a");
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";\n");
fclose($myfile);
$_SESSION['is_chat_logged'] = 1;
}
}
elseif ($_POST['what_to_do']==2){
if ($_SESSION['is_chat_logged'] = 1){
$actual_file=file_get_contents("users.txt");
$position_start=strpos($actual_file, "user_id" . $user_id . " ");
$line=file_get_contents("users.txt",FALSE,NULL,$position_start);
$position_end=strpos($line, ";")+1+$position_start;
$part_to_be_replaced=substr($actual_file, $position_start, $position_end-strlen($actual_file));
$new_actual_file= str_replace($part_to_be_replaced, "", $actual_file);
$myfile = fopen("users.txt", "w");
fwrite($myfile, $new_actual_file);
fclose($myfile);
$_SESSION['is_chat_logged'] = 0;
}
}
The users.txt looks like this:
user_id1 chat_nameJake;
user_id2 chat_nameSomeone;
user_id43 chat_nameZeke;
user_id22 chat_nameBilly;
Any help would be appreciated.
EDIT: I've found out what the problem was. I was using the substr() function the wrong way. Instead of $position_end-strlen($actual_file) I should have put $position_end-$position_start+1
change
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";\n");
to
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";");
The \n represents a new line.
notice when you are writing file (fwrite) you are appending a "/n" char which is a new line char. in order to remove new line char you just need to remove that "/n" from your fwrite function
Related
This question already has answers here:
Cannot open file using fopen (php)
(4 answers)
Closed 2 years ago.
In my first php file I open the users.txt to read it and then write in it. Here is the code for it:
Read:
if(file_exists("users.txt")){
$handle = fopen("users.txt", "r");
if ($handle) {
...
} else {
$ERROR = "Can't open the 'users.txt' file";
}
if ($userExist === true) {
...
}
else {
...
}
} else {
...
}
write:
$file = fopen("users.txt", "a") or die("Unable to open the file");
$data = PHP_EOL. $UserId . " " . $Fname . " " . $Lname . " " . $pass;
fwrite($file, $data);
fclose($file);
In my second php file, I tried to open the same file but apprently when I do this code:
$file = fopen("users.txt", "a") or die("Unable to open the file");
if (file_exists($file)) {
$data = " " . $Phone . " " . $recoveryEmail . " " . $month . " " . $day . " " . $year . " " . $gender;
fwrite($file, $data);
fclose($file);
}
else{
echo "Can't open the file 'users.txt'";
}
When I run it everything works fine for my first php file, but for second it prints the message:
Can't open the file 'users.txt'
After you use the fopen function, the $file is a handle, not the file name.
Hence please amend as follows:
$file = fopen("users.txt", "a") or die("Unable to open the file");
if (file_exists("users.txt")) {
$data = " " . $Phone . " " . $recoveryEmail . " " . $month . " " . $day . " " . $year . " " . $gender;
fwrite($file, $data);
fclose($file);
}
else{
echo "Can't open the file 'users.txt'";
}
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
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
$np = $_POST["np"]; // `sky` for example
$a = "inc/" . $np . ".php";
$new = fopen($a, "w") or die("Unable to open file!");
$str="$np='" . $np . "';";
fwrite($new, $str);
fclose($new);
I need to create a new inc/.sky.php file and write the following inside it:
$np = 'sky';
But what I get is:
sky='sky';
Any idea?
This should work for you:
$np = $_POST["np"]; // `sky` for example
$a = "inc/" . $np . ".php";
$new = fopen($a, "w") or die("Unable to open file!");
$str='$np = \'' . $np . "';";
fwrite($new, $str);
fclose($new);
The problem was that you are using " to define the string $str. Therefore, the content of $np was printed instead of the string '$np'.
Use single comma's
This will insert the $np variable into your sting
$str="$np='" . $np . "';";
This will insert np as text
$str='$np=\'' . $np . '\';';
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.