I'm trying to use file_put_contents to manage bans in a .txt
However, I'm having trouble adding text or a new line amidst the text I'm adding.
I'm using $_GET to grab the reason and information of the banned person, i.e "loser,127.0.0.1" (simple example) and then add them to the txt. Thing is I can't figure out how to add a new line. When I try adding text
<?php
file_put_contents("banned.txt", $_GET["r"], + "for example here", FILE_APPEND);
The code fails to run, I'm not sure whether or not to actually have a comma either.
This is the code I'm trying to use as of now, and it does add a line, but it doesn't go to the next line.
<?php
file_put_contents("banned.txt", $_GET["r"], FILE_APPEND);
What I'm trying to achieve is that it adds a new line, so if I said "loser,127.0.0.1" it adds that text to the txt, and goes to the next line for the next ban.
Try this
get your ban data and explicitly add the new line:
$banData = $_GET["r"] . PHP_EOL;
If you want to write csv data in the file (in a very simple way) you can do so like this:
$banData = $_GET["ban_data"] . ";" . $_GET["ban_reason"] . PHP_EOL;
then simply write to the file
file_put_contents("banned.txt", $banData, FILE_APPEND);
instead of "banned.txt" save to "banned.csv" and you're set
First code is invalid as you should not have , between your GET reference and concatenated string. Once that is fixed, just add \n (\r\n on Windows) at the end of your string that you append and you should have new lines (or to stay platform agnostic, use PHP_EOL instead).
Related
VERY simple routine that pulls the name of each PDF file in a folder and creates a list of each file found with a link to it. But I cannot get a line break between the items
Nothing seems to give me each file name and link on a new line. I have no idea why.
Neither of the \n has any affect at all.
<?php
$directory = "./images/";
$phpfiles = glob($directory . "*.pdf");
foreach($phpfiles as $phpfile)
{
echo "\n","<a href=$phpfile>".basename($phpfile)."</a>";
echo "\n";
}
?>
All I get for output is this....all on one line.
CAD_REPEQUEST.pdf JP_CADS.pdf JP_Reports.pdf
What I want is this....
CAD_REPEQUEST.pdf
JP_CADS.pdf
JP_Reports.pdf
If you're outputting to a Web page you'll need to replace \n with <br>.
If you're outputting to a text or other type of file, you may wish to replace \n with the constant PHP_EOL.
If you're outputting this to an email that's getting sent in text format, you'll have trouble with some clients, like Outlook, that will automatically attempt to remove unnecessary line breaks. Sometimes using a double line break helps, or you could convert your email to HTML and use the <br> approach.
I am trying to write a function in which a string of text is written with timestamps to the file "text2.txt", I want each entry to be on a new line, but PHP_EOL does not seem to work for me.The strings simply write on the same line and does not write to a new line for each string.
Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated?
Some sort of example would be highly appreciated.
Thank you in advance.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['sendmsg']))
{
writemsg();
}
function writemsg()
{
$txt = $_POST['tbox'];
$file = 'text2.txt';
$str = date("Y/m/d H:i:s",time()) . ":" . $txt;
file_put_contents($file, $str . PHP_EOL , FILE_APPEND );
header("Refresh:0");
}
?>
Also, I want to get rid of the character count on the end of the string when using the below code :
<?php
echo readfile("text2.txt");
?>
Is there any way for the character count to be disabled or another way to read the text file so it does not show the character count?
Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated? Some sort of example would be highly appreciated.
Given the code you posted I'm pretty sure newlines are properly appended to the text lines you are writing to the file.
Try opening the file text2.txt on a text editor to have a definitive confirmation.
Note that if you insert text2.txt as part of a HTML document newlines won't cause a line break in the rendered HTML by the browser.
You have to turn them into line break tags <br/>.
In order to do that simply
<?php
echo nl2br( file_get_contents( "text2.txt" ) );
?>
Using file_get_contents will also solve your issue with the characters count display.
A note about readfile you (mis)used in the code in your answer.
Accordind to the documentation
Reads a file and writes it to the output buffer.
[...]
Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as #readfile(), an error message is printed.
As readfile reads a file and sends the contents to the output buffer you would have:
$bytes_read = readfile( "text2.txt" );
Without the echo.
But in your case you need to operate on the contents of the file (replacing line breaks with their equivalent html tags) so using file_get_contents is more suitable.
To put new line in text simply put "\r\n" (must be in double quotes).
Please note that if you try to read this file and output to HTML, all new line (no matter what combination) will be replaced to simple space, because new line in HTML is <br/>. Use nl2br($text) to convert new lines to <br/>'s.
For reading file use file_get_contents($file);
I have a script that generates Javascript based on user form inputs. At present the code is outputted to a txt file on the server, but I'd like to put it into a MySql database.
Writing line by line to a txt file is easy with fopen, and helpful with my script due to the way the code is generated and wrapped around user inputs (various loops etc).
However, I'd really like to write the output to a variable, and then send that to the database. However, I can't see any way of accomplishing this?
Im sure it is possible, but the information I've found online only deals with quite basic variable creation.
A dirty solution would be to write to the txt file as I currently do, and then load the text file into a variable and then delete the text file. But this seems silly and clearly a waste of processing time.
Very new to Php so sorry if the above seems dumb.
It's not too difficult, you can declare the variable with the first line and then incrementally write to it, with the \n escape sequence (representing a new line) separating each line. You can size use the PHP_EOL built-in inserted, as commented. The=` assignment operator appends the string following the operator to the variable's value prior to the operation.
$lines = "my first line";
while (condition) {
$lines .= PHP_EOL . "my next line";
}
A derivative way of doing this would be to insert all the lines inside the loop and start with just declaring an empty string.
$lines = "";
while (condition) {
$lines .= "my next line" . PHP_EOL;
}
Note that this method will add an empty newline at the end, which you can trim off of needed.
Alternatively, another way would be to create an array, push to it, and then use the implode function to glue together the array into a string using a newline.
$lines = array();
while (condition) {
array_push($lines, "my next line");
}
$lines = implode(PHP_EOL, $lines);
ive got the following fwrite code, with , separating the data and it ending in ))
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
fwrite($handle, $shapeType);
but this is how it saves in the text file...
,,,,))Triangle,180,120,80,Red))
why have the first set of
,,,,,))
appeared in front of what it should look like?
You need to add a new line character to the end of each line. Otherwise your lines will all run into each other.
Use PHP_EOL for this as it will automatically use the Operating System appropriate new line character sequence.
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform.
Available since PHP 4.3.10 and PHP 5.0.2
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))'.PHP_EOL;
FYI, this might be a little cleaner to do using sprintf():
$shapeType = sprintf("%s,%s,%s,%s,%s))%s",
$_POST['shapeType'],
$_POST['triangleSide1'],
$_POST['triangleSide2'],
$_POST['triangleSide3'],
$_POST['triangleColour'],
PHP_EOL
);
Without seeing more of the code I would guess that you post to the same file and you do not check if a POST request was made before you write your file. So probably you write to your file on a GET request as well, causing empty entries to appear.
You would need something like:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// ...
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
fwrite($handle, $shapeType);
// ...
}
Edit: By the way, you should probably use fputcsv as that takes care of escaping quotes, should you change something in the future that adds for example a description field.
I am trying to make a news feed type thing in php.
I have a text file - news.txt and a php file index.php.
I have done the surrounding code and opening/closing the text file. Now I am stuck how to insert the new news item $newsnew to the top of the news.txt file and how to delete the old bottom news file in the news.txt file.
Is there any way to do this without deleting the whole file and writing it all again?
EDIT: Each news item is just a small string, say 500 characters, a single line.
Use a database.
If you really must use text files, use a different file for every news-item and name them sequentially like:
news001.txt
news002.txt
etc.
Then you can just add and delete files, read the directory and display what´s there.
Use the file() function to import the items in news.txt as an array, and use array_unshift() to add the new first item, and array_pop() to remove the last item. Join the array back into a single string and write it to news.txt:
$items = file('news.txt');
array_unshift($items, 'New item 1');
array_pop($items);
$newstext = implode(PHP_EOL, $items);
// write $newstext to the external file
If this is a XML file you could read it, parse it and delete the last child in the DOM. But if you have all your data in a DB it could be much easier to rewrite the file every time.
EDIT: after your edit: yes, you can do it like this:
write your new line to a new file
read the old file line by line and write it to the new one
skip the last line (detected by counting or EOF)
delete the old file and rename the new
No, there is not. But you might consider storing the messages in revers order. That way you only need to append to news.txt when new news arrive.
You are not going to be able to prepend to the beginning of the file without writing the whole thing out again. You could append to the end of it with the "a" mode flag to fopen(), but still to delete the oldest item you'll need to write out the entire file again.
Really, a database is solution here instead of a single text file.
There are many ways you can do it using the flat text file, but I'm not really sure it it's worth it. You can use some lightweight structured file or embedded database. For example SQLite, which would store it in normal file, no additional setup needed.