I have a form which sends data to a text file, but I'm trying to keep all data sent in the first line of that text file, and replacing would-be breaks with the br tags inside the text file itself. Sorry if there's a really easy solution, but I've been searching and testing for over an hour now >_< (php newbie)
Edit: Yeah here's the general gist of what I currently have. I'm using variables for it.
I have a form with one of the inputs named content that sends data to a submit.php.
In submit.php...
$content = $_POST['content'];
and that sends the following to a text file
$data = "$content";
$fh = fopen("file.txt", "a");
fwrite($fh, $data);
Look at the php function nl2br() (php.net). It does exactly what you need, by going through the string you give it and replacing new lines (\ns and \rs) with <br/> tags.
Apparently nl2br doesn't remove the actual breaks, and only adds the br tags, so try this function:
function oneLiner ($str)
{
$str = nl2br($str);
$str = str_replace(array("\n","\r"), '', $str);
return $str;
}
Related
I have a System which makes a new .html file after Inserting some Article information. But, there is a Textarea to input some HTML format codes.Of course there are lot of new lines in that String.I need To write that HTML code to .html file.
My Code Is This
$my_file = 'index.html';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = '<h6>
Hello!,World
</h6>';
fwrite($handle, $data);
actually i get $data from a TEXTAREA. Hope There Is No big difference there
I need FILE CONTENTS be Like This In my .html File
<h6>Hello!,World</h6>
But I get something like this
<h6>\r\n Hello!,World\r\n</h6>
Can Someone Explain How I can stop PHP's Auto add Breaklines system
EDIT: Fine,Didn't Got the exact answer yet! But,Hoped To say this. When We Write a html code there are lot of line breaks,spaces,etc...Like this.
<div class="post-content">
<h6>
Hello!,Yellow
</h6>
<!-- Post Tags -->
</div>
So when This Like code is Input Into A Text Area And Being written To A file It Do Not needed To Be like
<div class="post-content">\r\n<h6>\r\n Hello!,Yellow\r\n</h6>\r\n<!-- Post Tags -->\r\n</div>
RIGHT! I don't Know whether it's a error in my code, But I just need to know whether there is a method to stop file to be like that.
ALSO, when that TEXTAREA content is Inserted into a MySQL Database It Looks Perfectly Fine Like this
<div class="post-content">
<h6>
Hello!,Yellow
</h6>
<!-- Post Tags -->
</div>
It's not a "Auto add Breaklines system," what you are seeing with \r\n is a visual representation of a carriage return and a new line in the passed string.
You can use str_replace to replace the \r\n with ''. Or, you can use a fancy preg_replace to replace both \s+ and \r\n with ''.
You could use str_replace()this way to replace all these newline commands in your $data variable with simple spaces:
$to_be_replaced = array("\r\n", "\n", "\r");
$replacement = array(" ", " ", " ");
$data_changed = str_replace($to_be_replaced, $replacement, $data);
Addition after comments:
If you rather want to keep the line breaks and spaces as written into the text area field, you could replace the newline commands with <br>tags to keep the line breaks.
With spaces it's more problematic, since HTML will merge all multiple spaces into one space. But you could try to replace " " (i.e. a space) with " " (i.e. a non-breaking space HTML entity, which will also be accepted multiple times after each other.
So the code for that that would be
$to_be_replaced = array("\r\n", "\n", "\r", " ");
$replacement = array("<br>", "<br>", "<br>", " ");
$data_changed = str_replace($to_be_replaced, $replacement, $data);
If you don't use a monospace font, this won't look exactly the same as in the textarea (because characters of different fonts will have different widths), but it should come close.
(Posted on behalf of the question author).
Solved! I found that it happens not by PHP but by mysqli_real_escape_string() Function. So I found a way to solve my problem.
I have a PHP script which processes user input. I need to escape all special characters, but also make links clickable (turn them into <a> elements). What I need is:
function specialCharsAndLinks($text) {
// magic goes here
}
$inp = "http://web.page/index.php?a1=hi&a2=hello\n<script src=\"http://bad-website.com/exploit.js\"></script>";
$out = specialCharsAndLinks($inp);
echo $out;
The output should be (in HTML):
http://web.page/index.php?a1=hi&a2=hello
<script src="http://bad-website.com/exploit.js"></script>
Note that the amperstand in the link stays in the href attribute, but is converted to & in the actual content of the link.
When viewed in a browser:
http://web.page/index.php?a1=hi&a2=hello
<script src="http://bad-website.com/exploit.js"></script>
I eventually solved it with:
function process_text($text) {
$text = htmlspecialchars($text);
$url_regex = "/(?:http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+(?:\/\S*)?/";
$text = preg_replace_callback($url_regex, function($matches){
return ''.$matches[0]."";
}, $text);
return $text;
}
The first line html-encodes the input.
The second line defines the URL regex. Could be improved, but working for now.
The 3rd line uses preg_replace_callback, a function which is like preg_replace, but instead of supplying it with a replacement string, you supply a replacement function that returns the replacement string.
The 4th line is the actual function. It's quite self-documenting. htmlspecialchars_decode undoes the actions of htmlspecialchars (therefore making the link valid if it contained an amperstand).
Try this:
$urlEscaped = htmlspecialchars("http://web.page/index.php?a1=hi&a2=hello");
$aTag = 'Hello';
echo $aTag;
Your example doesn't work because if escaping whole html tag, a tag will never get processed by the browser, instead it will just display as plain text.
As you can see, stackoverflow escapes our whole input (questions/answers ...), so we can actually see the code, and not letting browser to process it.
The function below is the one I use to output data
function escape($string){
return htmlentities($string, ENT_QUOTES, 'UTF-8');
}
It works if just need to get strings saved to my database and be echoed
How can I allow certain tags like bold and breaks and still be secured from xss attacks
Here is a sample string I need to work
$string = '<b onclick="javascript:alert(1);">Hello<br>World<script>alert(2);</script></b>';
Output should just be
HelloWorld
I came up with a solution to my question by combining answers I found on this website.
Here's the code
$string = '<b onclick="javascript:alert(1);">Hello<br>World<script>alert(2);</script></b>';
// remove script tag along with everything in it
$string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $string);
// remove all tags except the ones you want to work
$string = strip_tags($string, '<br><b>');
// remove all attributes of the html tags
$string = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $string);
echo $string;
For now, it works against the sample string provided.
If you guys know any problem that might occur by using this code please feel free to comment and advice on better way output data securely but still keep certain tags. Thanks!
the data is captured from a textarea to begin with.
Line1
Line2
Line3
etc
It is sent through this function before being stored in the DB (i'm open to better solutions, but if PDO is one of them, I don't understand it and have yet to get it to work)
function test_input($data) {
global $conn;
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = mysqli_real_escape_string($conn, $data);
return $data;
}
Which is my way of preventing injections (not my way but a way I found that has worked great until now its giving me this problem with line breaks and textareas)
I try to extract the data from the DB and display it in a textarea, and it shows \r\n instead of doing a line break. It is stored in the DB with the line breaks (i do not see the \r\n but instead i see the data on a new line)
I've tried nl2br, i've tried html_entity_decode, i've tried str_replace \r\n to br (and then it just shows br literal instead of \r\n).
from the research I've found on this site, its the stuff i'm doing to it before i store it in the DB that is causing this but none of the solutions have worked for me.
help.
Replace the \r\n in the text with
before putting it into to the textarea and showing it to the user.
It worked for me.
Try This May be help full
<?php
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
?>
Html versus php and windows (carriage return and newline). Le
rning what happens
when you have a field of values in a buffer. A buffer can be coming from or going to an input/output device
What is inside the buffer may need to be substituted for a string appropriate to the device.
Pulling data from a DB line by line or from a SQL api query will require a regular expression and substitution operation repeating until all
expressions are changed. Bullet proofing the input before it goes into the DB field is always a good idea.
I encountered a print problem that was caused by extra data (escape sequences) that caused the printers
to stop and wait for a reset sequence. No one understood why print jobs failed to print for something like
12 months. I wrote a filter and added it to the printers interface. PRoblem solved
I'm using a javascript function that receives some html code that was included using php.
It is not html in a php string but an html file with .php extension.
As the html code is sent as a parameter to the js function it can't contain carriage returns. The problem is that writing big blocks of html in a single line is terrible, I would like to have a function only to erase the carriage returns before sending the content.
Is there a source for such a function?
Thanks!
simple
echo str_replace(array("\r\n", "\r", "\n"), null, $htmlCode);
When you say "in a PHP file", I assume you mean you're include()ing a file that looks something like this:
<html>
<head><title>Foo</title></head>
<body>
<?php do_stuff(); ?>
</body>
</html>
If that's the case, what you're looking for is called Output Control, which allows you to either prevent data from being sent until you're ready or capture it to a string for additional processing. To strip carriage returns from an included file, you can do this:
<?php
ob_start(); // start buffering output
include("foo.php"); // include your file
$foo = ob_get_contents(); // get a copy of the buffer's contents
ob_clean_end(); // discard the buffer and turn off buffering
echo str_replace("\r", "", $foo); // print output w/o carriage returns
If you want to remove newlines as well, change that last line to:
echo str_replace(array("\n", "\r"), "", $foo);
by "building it in PHP" I assume you mean that you're building a string which contains the relevant HTML.
If that's the case, then it's a simple matter of not having the carriage returns as a part of your string.
i.e., don't do this:
foo = " this is my string
and I have it on two lines";
but rather do this
foo = "" .
" this is my string" .
" and it's on one line ";
Sure, you could use a string.replace function, but building via concats means that you get to skip that step.
It's a simple string substitution.
Consider using a XML writer for this, if that's what your javascript parses. That way the result will always be valid, and the code should get cleaner.