Keep text format line by line Into variable to .txt PHP - php

<form action="editinfo.php" method="post">
<pre><textarea rows="440" name="editinfo" cols="700"></textarea></pre><br><br>
<input type="submit" class="ButtonSub" value="Submit">
</form>
editinfo.php
$editinfo = mysqli_real_escape_string($connd, $_POST['editinfo']);
$myfile = fopen("myinfo.txt", "wb") or die("Unable to open file!");
fwrite($myfile, $editinfo);
fclose($myfile);
What I want to achieve?
Let's say I have editinfo text is
SAM
PLEM
it outputs SAM\r\nPLEM in the txt, how can I format it correctly? so it can look like
SAM
PLEM

Simply don't SQL-escape (mysqli_real_escape_string) the text, that's what's turning a linebreak into escaped \r\n sequences. There's absolutely no point in SQL escaping something that isn't going to be used in an SQL query.

Related

Form input field not displaying previous data correct

With the following code I need to be able to enter a tracking pixel code which contains these " & ? characters.
With the below code it allows entry of the pixel in the textbox saving it and the resulting line in the file is correct.
However when it then reloads the pixel for display in the value in the form field it has been cut off.
<?php
if (isset($_POST["pixel"])) {
$fp = fopen("config.php", "w") or die("Unable to open file config file");
fwrite($fp, $_POST["pixel"]."\n");
fclose($fp);
}
$fp = fopen("configz.php", "r") or die("Unable to open config file");
$pixel = fgets($fp);
fclose($fp);
?>
<form method="post">
Pixel:<input type="text" name="pixel" value="<?=$pixel?>" />
<input type="submit" name="Save" value="Save">
</form>
You need to change below code
<input type="text" name="pixel" value="<?=$pixel?>" />
to
<input type="text" name="pixel" value='<?=$pixel?>' />
Add single '' around value as in your $pixel string you have "". It will break the string from the first occurrence of " in $pixel.
Edit
You can replace all single quote with double quotes.
JS
var b = a.replace(/'/g, '"');
where a will be your string.
PHP
$pixel = str_replace("'", '"', $pixel);
Update
To replace all double quotes with single quotes in form input.
var newVal = [];
$('#form_id *').filter(':input').each(function(){
var k = $(this).attr('name');
var v = $(this).val();
newVal[key] = v.replace(/'/g, '"');
});
You can loop through all the values of the form and get their name as a key, get all values, perform replace on all values and add key=>value pair in an empty array. In newVal you will have the desired output which you can use.
<?php
if (isset($_POST["pixel"])) {
$fp = fopen("config.php", "w") or die("Unable to open file config
file");
fwrite($fp, $_POST["pixel"]."\n");
fclose($fp);
}
$fp = fopen("configz.php", "r") or die("Unable to open config file");
$pixel = fgets($fp);
fclose($fp);
?>
<form method="post">
Pixel:<input type="text" name="pixel" value='<?=$pixel?>' />
<input type="submit" name="Save" value="Save">
</form>
Add a single quote instead of double quotes.
I have solved my issue by leaving all the code as it was originally and just changing the fgets line.
This allows the field to have single or double quotes in it and displays the data correctly.
not letting me post it. it changes it here.

Get HTML data and append to a .txt file in server with PHP

I have been trying to get the data input from <teaxtarea> and append it in a .txt file in the server everytime someone inputs there. The server-side language is currently PHP. I have been trying for a possible solution online or in the tutorials, but likely end up with unsatisfied result. I am pretty sure it's a really simple thing, but as a total newbie (just started PHP few days ago) I am really lost right now.
Help will be much appreciated.
I have tried so many methods, now a bit lost. Here's something I have tried and failed. -
<?php
$myfile = "input.txt";
$txt = $_POST["text"];
fopen($myfile, "a");
fwrite($myfile, $txt);
fclose($myfile);
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
<textarea name="text"></textarea>
<input type="submit"></input>
</form>
</body>
</html>
Please refer to the documentation for fopen and fwrite.
fopen will return a file pointer which you will need to pass to any functions like fwrite and fclose. Passing the file name will not work.
Also, using "a" in fopen requires the file to exist. Change it to "a+" to create it if needed and make sure the script has permission to do so.
Finally, if you want new form submissions to go on a new line, you will need to add new line yourself because "a" will put the file pointer to the end of the file only. It will not add newlines for you.
This should work:
<?php
if (isset($_POST["text"])) {
$txt = $_POST["text"];
$fp = fopen("text.txt", "a+");
fwrite($fp, $txt . PHP_EOL);
fclose($fp);
}
?>
<!DOCTYPE html>
<html>
<body>
<form method = "POST">
<textarea name="text"></textarea>
<input type="submit"></input>
</form>
</body>
</html>
As an alternative to the fopen, fwrite, fclose combo, you could also just use
file_put_contents("text.txt", $_POST["text"] . PHP_EOL, FILE_APPEND);
Your form action is wrong.
You could leave it blank, because the target php-code is on the same page, or use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
And like Gordon said, you have to define a file, e.g.
$filePath = './file/path.txt';
$file = fopen($filePath, 'a');
frwite($file, $message);
fclose($file);

php file write arrays variables html not working

I am trying to make a website where you input a value to order food. In php i am trying to make it create a txt file that i can view. I have gotten it to make the file, but instead of a number, it simply displays 'Fries: Array' and the 'Array' should be a number. My php and HTML code is as follows...
HTML:
<input type="number" name="Fries" min="0" max="69"><br>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen("Fries.txt", "w") or die("Unable to open file!");
$fries = array(['Fries']);
$string = 'Fries: '. strval($fries[0]);
fwrite($fh, $string);
fclose($fh);
?>`
If anyone can tell me how to get php to read HTML form data, that wiuld be great
Assuming that you're aware of all of the potential pitfalls of taking user input and writing it to a file without any type of validation: square brackets in PHP are a shortcut for defining a new array. So what you've written is equivalent to:
$fries = array(array('Fries'));
Also, you're assigning your new array the string value "fries," when you say you're trying to get this from your user input. Try the following:
...
$fries = 'Fries: ' . $_REQUEST['Fries'];
fwrite($fh, $string);
...
No need to use strval() - value is already a string.
And as far as validation, you may want to add the following before you assign your $fries variable:
if (is_numeric($_REQUEST['Fries'] && $_REQUEST['Fries'] >= 0 && $_REQUEST['Fries'] <= 69)
HTML:
<form method="post">
<input type="number" name="fries" min="0" max="69"><br>
<input type="submit" name="submit">
</form>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen($path, "w") or die("Unable to open file!");
$string = 'Fries: '. filter_input(INPUT_POST,'fries');
fwrite($fh, $string);
fclose($fh);
?>

how to handling non English chars with php

I have code in php that create file with name that user input like below
html
<form method="post">
<input type="text" name="file">
<input type="submit">
</form>
php
$file = $_POST['file'].'.php';
$f = fopen($file, 'w');
fclose($f);
the problem appear when user use non-english chars
example user input = اللغة العربيه
resault = ظ…ط±ط§ظ‡ظ‚ظˆ-ط§ظ„طھط§ظٹطھظ†ط.php
but it should be = اللغة العربيه.php
Trying to create files with non-english filenames can be quite hard.
Easiest solution is to not use such filenames at all, but encode all filenames e.g. with urlencode:
$filename = $_POST['file'].'.php';
$encoded_filename = urlencode($filename);
$f = fopen($encoded_filename, 'w');
fclose($f);
This will not affect English characters and will allow creating filenames using any language.
Note that each filesystem will have some limits on how long filesnames can be, so if $encoded_filename becomes too long this will not work.

Need feedback form comments to save to sepoerate lines

I have a feedback form that saves to a txt file, it saves perfectly but it saves on one line. So multiple comments would be saved on one line so that saves to just one line on notepad rather than separating different comments onto different lines.
Here is my HTML
<form action="feedback.php" method="post">
<table>
<tr>
<td>Email Address:</td>
<td>
<input type="text" name="email_address" value="" maxlength="100" />
</td>
</tr>
<tr>
<td>
Comments:
</td>
<td>
<textarea rows="10" cols="50" name="comments">
</textarea>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
Here is my php:
<?php
$email_address = $_POST['email_address'];
$comments = $_POST['comments'];
$myfile = fopen("feedback.txt", "a") or die("Unable to open file!");
$txt = 'Email: '.$email.'\nComments: '.$comments.'\n\n';
fwrite($myfile, $txt);
fclose($myfile);
?>
So I need different comments to save to different line rather than just one.
Your \n (new line) is not working because you use apostrophe ' instead of double quotes ".
eg you have:
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
And you need:
$txt="Email: ".$email."\nComments: ".$comments."\n\n";
EDIT
Your email address isn't being written as you change the variable name used.
e.g. You have this code:
$email_address=$_POST['email_address'];
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
Your $txt variable is using $email however you're setting the $_POST data to variable $email_address.
Try this complete code:
$email_address = $_POST['email_address'];
$comments = $_POST['comments'];
$myfile = fopen("feedback.txt", "a") or die("Unable to open file!");
$txt="Email: ".$email_address."\nComments: ".$comments."\n\n";
fwrite($myfile, $txt);
fclose($myfile);
It's a simple mistake to make, but you should try to get into the habit of copying and pasting your variable names, rather than re-typing them. This (helps) avoid typos etc, which in large code blocks & multiple files, becomes an even bigger problem.
And use your error logs - they are invaluable when coding!
In this case PHP (thus the logs) would have moaned about that $email variable not being defined, which in turn would have led you to inspect the variable and you'd have likely worked it out.
I Would use PHP_EOL since it's cross-platform-compatible! That means it handles Unix/DOS/Mac issues!
(Also i think you want to change the $email variable)
So insteat your line:
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
Use:
$txt = "Email: ". $email_address . PHP_EOL . "Comments: " . $comments . PHP_EOL . PHP_EOL;
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
Use \r\n to make new line text file like:
$txt='Email: '.$email.'\r\n Comments: '.$comments.'\r\n';
You actually may use single quotes and concatenate a newline character but you'd need to write code like this:
<?php
echo 'This is a test of using a newline char.' . chr(10) .
'Did it work? It should have.';
?>
To reduce the possibility of things going wrong one should do certain checks. Did the user actually submit a form? Also, we should not assume that all data from $_POST is safe and hence I use htmlentities() for the email address and the comments, just in case a malicious user tries to slip in something they shouldn't.
The other point is that some people think that variable interpolation is slow but the ironic thing is that the more variable interpolation there is the more efficient that interpolation processing becomes. Incidentally, I changed some of the newlines by adding some and removing others so that the final result is formatted in a way that is easier to read.
<?php
if (isset($_POST) && $_POST != NULL) {
$email_address = htmlentities($_POST['email_address']);
$comments = htmlentities($_POST['comments']);
$myfile = fopen("feedback.txt", "a") or exit("Unable to open file!");
$txt="Email: $email_address\nComments:\n\n$comments\n\n";
fwrite($myfile, $txt);
fclose($myfile);
}
?>
I replaced the morbid die() with exit() since they are both equivalent language constructs; they both generate the same EXIT opcode.

Categories