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.
Related
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).
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);
Let's say I have a file "English.txt" containing these lines :
$_LANG["accountinfo"] = "Account Information";
$_LANG["accountstats"] = "Account Statistics";
Note : the file extension is .txt and there is nothing I can do to change that. There is no opening PHP tag (<?php) or anything, just those lines, period.
I need to extract and actually get the $_LANG array declared from these lines. How do I do that? Simply includeing the file echoes every line, so I do
ob_start();
include '/path/to/English.txt';
$str = ob_get_clean();
Now, if I call eval on that string, I get an syntax error, unexpected $end. Any ideas?
Thanks.
eval(file_get_contents('English.txt'));
however, be sure NOBODY can change English.txt, it could be dangerous!
First of all, note that you should use file_get_contents instead of include with output buffering. Since it contains no <?php tag, there is no need to run it through the script processor.
The following works perfectly in my tests:
<?php
$contents = file_get_contents("English.txt");
eval($contents);
var_dump($_LANG);
As one of the comments said, if you do the above and still get an error, then your file does NOT contain exactly/only those lines. Make sure the file is actually syntax compliant.
As has been mentioned, you should really use eval only as a last resort, and only if the file is as safe to execute as any code you write. In other words, it must not be editable by the outside world.
I am currently working on this project which requires me to make a function which dinamically decides the directory name and then creates a simple .txt file in that directory.
my code is as follows:
($destinatario is a string)
$diretorio="../messages/".$destinatario;
if (is_dir($diretorio)) {
;
}else{
mkdir($diretorio);
}
$path=$diretorio."/".$data.",".$assunto.",".$remetente.".txt";
$handle=fopen($path,'w+');
fwrite($handle, $corpo);
fclose($handle);
nevermind the portuguese, but the bottom line is that it should create a .txt file using the naming guidelines i've provided. The funny thing is that when i do this, php creates this weird file whose filename is "01.09.2010 04"
(with no extension at all) which amounts to the first few characters of the actual filename i'd like to create...
edit($data is actually the output from a call to date("d.m.Y H:i"))
Per comment by OP:
[$data is] actually the output of a call to date("d.m.Y H:i")
The problem is the : character. (Still, there may be other illegal characters in the other parts composing the final file name.)
EDIT
The essence of the problem and solution is in the comments to #tchen's answer. Keep in mind that colon is a valid file name character on (some? all?) *nix platforms but is invalid on Windows.
Make sure there's no bad characters at the end of $data. Call trim() on it.
If it's data taken from a file, it may have a '\r' or '\n' at the end of it.
Not related, but make sure your if statements don't have unused conditions:
if (!is_dir($diretorio)) {
mkdir($diretorio);
}
This will also get rid of that blank line with a single terminator ;, I'm sure that isn't right.
Some ideas:
have you tried not using commas in the filename?
Have you checked the return value if fopen and fwrite?
Just to try to isolate the problem
also you can simplify to:
if (!is_dir($diretorio)) {
mkdir($diretorio);
}