Writing a new and appending a file in PHP without erasing contents - php

How could one write a new line to a file in php without erasing all the other contents of the file?
<?php
if(isset($_POST['songName'])){
$newLine = "\n";
$songName = $_POST['songName'];
$filename = fopen('song_name.txt', "wb");
fwrite($filename, $songName.$newLine);
fclose($filename);
};
?>
This is what the file looks like
Current view
This is what is should look like Ideal View

Simply:
file_put_contents($filename,$songName.$newLine,FILE_APPEND);
Takes care of opening, writing to, and closing the file. It will even create the file if needed! (see docs)
If your new lines aren't working, the issue is with your $newLine variable, not the file append operations. One of the following will work:
$newLine = PHP_EOL; << or >> $newLine = "\r\n";

You have it set for writing with the option w which erases the data.
You need to "append" the data like this:
$filename = fopen('song_name.txt', "a");
For a complete explanation of what all options do, read here.

To add a new line to a file and append it, do the following
$songName = $_POST['songName'];
$filename = fopen('song_name.txt', "a+");
fwrite($filename, $songName.PHP_EOL);
fclose($filename);
PHP_EOL will add a new line to the file

Related

using fopen to add some text after multiple appearance of a text

what I am trying to do is to create an installer for my world calendar in a script.
I need to make some changes to one of the files in. the main script.
I have managed to use the code above to make the change that I want. the problem is that there is more than one occurrence. how do I make the same change every time that the string is repeated. it could happened 0 or 1 or 2 times
$target_line='$second = (int)substr($raw_date, 17, 2);';
$lines_to_add= '$raw_date = translate_from_gregorian($raw_date);'. PHP_EOL.
'$year = (int)substr($raw_date, 0, 4);'. PHP_EOL.
'$month = (int)substr($raw_date, 5, 2);'. PHP_EOL.
'$day = (int)substr($raw_date, 8, 2);'. PHP_EOL;
$config ='includes/functions/general.php';
$file=fopen($config,"r+") or exit("Unable to open file!");
$insertPos=0; // variable for saving //Users position
while (!feof($file)) {
$line=fgets($file);
if (strpos($line,$target_line)!==false) {
$insertPos=ftell($file); // ftell will tell the position where the pointer moved, here is the new line after //Users.
$newline = $lines_to_add;
} 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);
Read the entire file into a variable. Use str_replace() to make all the replacements. Then write the result back to the file.
$contents = file_get_contents($config);
$contents = str_replace($target_line, $target_line . PHP_EOL . $lines_to_add, $contents);
file_put_contents($config, $contents);

Why file_put_contents() not always rewrites a file?

I wonder, why PHP file_put_contents() function works in a weird way.
I used it in a loop to write some logs to file and all was fine (new lines were appended even if no flag was specified). When I started the script again, it re-created my file.
From PHP doc:
If filename does not exist, the file is created. Otherwise, the
existing file is overwritten, unless the FILE_APPEND flag is set.
OK, so my question is: Why (when used in one loop) it doesn't overwrite my file (without FILE_APPEND flag of course)? Bug or feature? :)
Edit: Example context of use when this happened:
$logFile = dirname ( __FILE__ ) . '/example.log';
foreach($something1 as $sth1) {
$logData .= "Something\n";
foreach($something2 as $sth2) {
if($something_else) {
$logData .= "Line: \t" . $sth2 . "\n";
file_put_contents($logFile, $logData);
}
}
}
As it has been very clearly mentioned in this link under the flags content(which you should have read) it clearly states that if file filename already exists, append the data to the file instead of overwriting it(when this flag is set). So when the flag for FILE_APPEND is set it appends and when not it rewrites. Hope this helped you.
Alternative Way
<?php
$file = 'file.txt';
$append = true;
if (file_exists($file)) {
if ($append) {
// append file
$file = fopen($file, 'a+');
} else {
// overwrite file
$file = fopen($file, 'a');
}
} else {
// create file
$file = fopen($file, 'a');
}
fwrite($file, 'text');
fclose($file);
?>
here is a php fopen documentation
and php file
and read on its related topics
ok, when you are run the script each time try to rename the log file with random number or currentdate timestamp and try to save it in your DB
by this when you again run the script and can take the log file name from DB and update it when you needed

Developing a text editor with PHP

I've started a small project trying to make an online text editor, it WAS going well until the system started overwriting files and adding spaces in unnecessarily. I have one file called editor.php where all the file loading, saving and editing is done.
So this is the opening/closing for the files:
<?php
if(isset($_POST['new'])){
$filer = substr(md5(microtime()),rand(0,26),6);
$file_create = $filer.".txt";
$handle = fopen("files/".$file_create,"w");
fclose($handle);
header("Location: editor.php?e=".$filer);
}
$file = $_GET['e'];
$file = basename($file);
$filename = "files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
file_put_contents($filename, $_POST['text']);
}
?>
further down the page I have this in a <textarea> tag:
<?php
echo $file_content;
?>
This uses the string from the file_get_contents();
But when I save, nothing happens, in fact it erases the file, when I load a file there are eight spaces but nothing else.
I know there is another way to do this with fopen() and if someone could give me a method to use that, it would be much appreciated.
You have to verify if the $_POST['text'] actually has a content in it.
if(isset($_GET['e'])){
$file = $_GET['e'];
$file = basename($file);
$filename = $_SERVER['DOCUMENT_ROOT']."/files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
if(!empty($_POST['text']) && isset($_POST['text']))
{
$length = strlen($_POST['text']);
if($length > 0)
file_put_contents($filename, trim($_POST['text']));
else
die("No content");
}
}
}
ALso check if the file exists and its writable. You can use chmod,mkdir and file_exists functions.
Have a look at PHP's file modes: http://php.net/manual/en/function.fopen.php
If you are opening all your files using fopen() in w mode then your files are being truncated as they are opened. This is how w mode operates. Try using a+ or c+ modes with fopen().
EDIT
Also, the file_put_contents() will also overwrite file contents unless you sett the FILE_APPEND flag, e.g. file_put_contents($file, $data, FILE_APPEND).

Using fwrite() to set a variable in a file

I have two php files: one is called key.php and the other is the function that validates the key. I want to regularly write to the key.php file and update the key from the validator.php file.
I have this code:
$fp = fopen('key.php', 'w');
$fwrite = fwrite($fp, '$key = "$newkey"');
What I'm trying to do is set the $key variable in the file key.php to the value of $new key which is something like $newkey = 'agfdnafjafl4'; in validator.php.
How can I get this to work (use fwrite to set a pre-existing variable in another file aka overwrite it)?
Try this:
$fp = fopen('key.php', 'w');
fwrite($fp, '$key = "' . $newkey . '"');
fclose($fp);
This will "overwrite" the variable in a literal sense. However, it won't modify the one you're using in your script as it runs, you'll need to set it ($key = somevalue).
More to the point, you really should be using a database or a seperate flat text file for this. Modifying php code like this is just plain ugly.
for_example, you have YOUR_File.php, and there is written $any_varriable='hi Mikl';
to change that variable to "hi Nicolas", use like the following code:
<?php
$filee='YOUR_File.php';
/*read ->*/ $temmp = fopen($filee, "r"); $contennts=fread($temp,filesize($filee)); fclose($temmp);
// here goes your update
$contennts = preg_replace('/\$any_varriable=\"(.*?)\";/', '$any_varriable="hi Jack";', $contennts);
/*write->*/ $temp =fopen($filee, "w"); fwrite($temp, $contennts); fclose($temp);
?>

How to open a file and remove the last line?

I am looking to open up a file, grab the last line in the file where the line = "?>", which is the closing tag for a php document. Than I am wanting to append data into it and add back in the "?>" to the very last line.
I've been trying a few approaches, but I'm not having any luck.
Here's what I got so far, as I am reading from a zip file. Though I know this is all wrong, just needing some help with this please...
// Open for reading is all we can do with zips and is all we need.
if (zip_entry_open($zipOpen, $zipFile, "r"))
{
$fstream = zip_entry_read($zipFile, zip_entry_filesize($zipFile));
// Strip out any php tags from here. A Bit weak, but we can improve this later.
$fstream = str_replace(array('?>', '<?php', '<?'), '', $fstream) . '?>';
$fp = fopen($curr_lang_file, 'r+');
while (!feof($fp))
{
$output = fgets($fp, 16384);
if (trim($output) == '?>')
break;
}
fclose($fp);
file_put_contents($curr_lang_file, $fstream, FILE_APPEND);
}
$curr_lang_file is a filepath string to the actual file that needs to have the fstream appended to it, but after we remove the last line that equals '?>'
Ok, I actually made a few changes, and it seems to work, BUT it now copies the data in there twice... arggg, so each line in the file is now in there 2 times :(
Ok, removed the fwrite, though now it is appending it at the bottom, just below the ?>
OMG, I just need everything up to the last line, isn't there a way to do this??? I don't need "?>"
A simple way with the file on the filesystem:
<?php
$path = "file.txt";
$content = file($path); // Parse file into an array by newline
$data = array_pop($content);
if (trim($data) == '?>') {
$content[] = 'echo "... again";';
$content[] = "\n$data";
file_put_contents($path, implode($content));
}
Which does..
$ cat file.txt
<?php
echo 'Hello world';
?>
$ php test.php
$ cat file.txt
<?php
echo 'Hello world';
echo "... again";
?>
It's copying each line twice because of your line that says:
#fwrite($fp, $output);
You're just reading the file to find the end tag, there's no need to write the line you've read as you read.
I would add a new <? YOUR CODE ?> after the last line...
Or if you have the new PHP code to add in $code this could be done with a regular expression
$output = preg_replace('\?>','?>'.$code,$output)

Categories