How should i store newlines in a MySQL database? - php

I'm going around and around in circles in my mind trying to decide how best I should store newlines in a MySQL database.
A bit of background; the user is asked to complete a textarea. This has to stored in a MySQL database before being read back out and the content included in an HTML email.
Should I store them as:
1) String literal - surely this is dangerous and bad practice
2) As a string with \r\n in - when I read this back out of the database its read as 4 characters so nl2br() fails to correctly replace them.
3) As HTML <br /> - as it has to be html entity encoded to be stored it ends up being stored as <br /> so when it gets to the email <br /> is printed rather than an actual newline. Passing it through html_entity_decode() would decode other characters that need to be encoded.
Any help grately appreciated.

Store it as it is but escape first. This is your option 1. When you need to present this data apply whatever function you need to format it. If you need to show it in HTML use nl2br() and htmlentities() functions. That'll work for mail also.
If you have a text area data like this,
$text="Hello Sir,
I am Robert'); Drop table students; --
.....
Yours most obedient pupil
.....";
Just store it as it is after you escape it, or use a prepared statement.
$text = $mysqli->real_escape_string($text);

use the javascript string replace function str.replace(/\n/g,'\\n')
to transform all newlines to escaped literals in the textarea while forming the url or post string.
Retrieving the same using PHP's json_encode() and displaying it through a textarea works well for me.

It depends on application type (how you want to display your text).
If this is HTML e-mail editor - i think html format will be better.
In most CMS (content management systems) HTML format is used (joomla, wordpress, prestashop etc.), because you can just read this from database and send to browser.
Besides - you probably may need other HTML tags anyway (like <b> for bold or <center>).
I think using \r\n format is better for non-web applications, when data is displayed on windows form controls.
One more thing - you may store them in both ways:
- <br> for HTML view
- \r\n for HTML source (to add some newline's and make more readable html source code)
By more readable html i mean this:
<center>
This is header
</center>
<p>
This is paragraph.
<br>
Second line.
</p>
Instead of this:
<center>This is header</center><p>This is paragraph.<br>Second line.</p>

Related

PHP wont show new line [duplicate]

This question already has answers here:
Echo from MySQL database with spaces and line breaks?
(2 answers)
Closed 9 years ago.
i have a little problem with the text to be readed from my database.
After the user has confirmed their new post, it saves in the database like this ( like i want it to do).
but in the webpage, it will ignore these lines, and just echo out everything on the same line.
Here is a bit my source code:
$objekttekst=str_replace("\\r\\n", "<br>", $obj->innhold);
$objekttittel=$obj->tittel;
?>
<h2><?=$objekttittel?></h2>
<p><?=$objekttekst?></p>
could someone help me out? thanks
Use nl2br() function.
$objekttekst = nl2br($obj->innhold);
The input textarea is pre-formatted, which means that it will show any newlines that the user enters. However, HTML rendered (web browser) does not display any newlines from the input, unless newlines are explicitly inserted with tags such as <BR>.
You have several options here. For sure these three are not your only options, but they are the ones I have personally been using most often.
Form textarea with pre-formatted text
If you want to display the data (objekttekst) in a similar textarea where the input was given, you could do:
<h2><?=$objekttittel?></h2>
<p><textarea><?=$objekttekst?></textarea></p>
This would suit you best in a situation where the user needs a possibility to edit the entry.
Preformatting
If you want to display the text as it is, you can always surround it with <PRE>...</PRE>. That will show any newlines, indentations etc. Note that this will make the output use a fixed-width font such as Courier New.
Convert newlines to <BR> tags
Use function nl2br() as already mentioned in another answer. See: http://php.net/manual/en/function.nl2br.php for more information.
Additional note...
You might want to look into regular expressions, as in many cases you might want to do also some other modifications to your data before showing it in the HTML page. nl2br() will take care of newlines, but for other and more complex modifications you should learn regular expressions.
You can surround your string with <pre> tag instead of replacing \n with <br>
Example:
<?php
$objekttekst=$obj->innhold
$objekttittel=$obj->tittel;
?>
<h2><?=$objekttittel?></h2>
<p><pre><?=$objekttekst?></pre></p>

Replace '&' with 'and' on the fly in PHP

Is there a way to replace the character & with and in a PHP web form as the user types it rather than after submitting the form?
When & is inserted into our database our search engine doesn't interpret the & correctly replacing it with & returning an incorrect search result (i.e. not the result that included &).
Here is the field we would like to run this on:
<input type="text" name="project_title" id="project_title" value="<?php echo $project_title; ?>" size="60" class="btn_input2"/>
Is there a way to replace the character & with and in a PHP web form as the user types it rather than after submitting the form?
PHP is on the server, it has no control over anything taking place under any circumstances what-so-ever on the client-side. It sends raw text from the web server, a 100megaton thermonuclear device explodes, and PHP never exists anymore after the content is sent. Just the document received on your client side remains. To work with effects on your client side, you need to work with JavaScript.
To do that, you would pick your favorite JavaScript library and add an event listener for "keyup" events. Replace ampersands with "and", and drop the replacement text back in the box. mugur has posted an answer that shows you how to do this.
This is a horrible solution in practice because your users will be screaming for bloody justice to deliver them from such an awful user experience. What you've ended up doing is replacing the input text with something they didn't want. Other search tools do this, why can't yours? You hit backspace, then what? When you hit in the text, you probably lose your cursor position.
Not only that, you're treating a symptom rather than the cause. Look at why you're doing this:
The reason is when & is inserted into our database our search engine flips out and replaces it with & which then returns an incorrect result (i.e. not the result that included &).
No, your database and search engine do no such thing as "flipping out". You're not aware of what's going on and try to treat symptoms rather than learn the cause and fix it. Your symptom cure will create MORE issues down the road. Don't do it.
& is an HTML Entity Code. Every "special" charecter has one. This means your database also encodes > as > as well as characters with accents in them (such as French, German, or Spanish texts). You get "Wrong" results for all of these.
You didn't show any code so you don't get any code. But here's what your problem is.
Your code is converting raw text into HTML Entity codes where appropriate, you're searching against a non-encoded string.
Option 1: Fix the cause
Encode your search text with HTML entities so that it matches for all these cases. Match accent charecters with their non-accented cousins so searching for "francais" might return "français".
Option 2: Fix one symptom
Do a string replace for ampersands either on the client or server side, your search breaks for all other encodings. Never find texts such as "Bob > Sally". Never find "français".
Before submitting the form you'd need to use JavaScript to change as the user types it in. Not ideal since JS can be turned off.
You'd be much better to "clean" the ampersands after submitting but before inserting into the database.
A simple str_replace should work:
str_replace(' & ',' and ', $_POST['value']);
But as others have pointed out, this isn't a good solution. The best solution would be to encode the ampersands as they go into the database (which seems to be happening just now), then modify your search script to allow for this.
You can do that as they complete the form with jquery like this:
$('#input').change(function() { // edited conforming Icognito suggestion
var some_val = $('#input').val().replace('&', 'and');
$('#input').val( some_val );
});
EDIT: working example (http://jsfiddle.net/4gXZW/13/)
JS:
$('.target').change(function() {
$('.target').val($('.target').val().replace('&', 'and'));
});
HTML:
<input class="target" type="text" value="Field 1" />
Otherwise you can do that in PHP before the insert sql.
$to_insert = str_replace("&", "and", $_POST['your_variable']);

How to make a textarea ouput textarea code without breaking?

I created a form where users can enter html code and it outputs their code in another textarea. The problem is that if the html the user enters has a textarea in the code, the in their code breaks my textarea form. I see other sites display any html correctly so how is this done without breaking the form and allowing the user to copy it so that it still remains as and not some converted code so they can paste it on their webpage?
Ah crap yeah I figured it out, in fact the problem wasn't with the htmlspecialchars code alone I forgot to add a return to one of my functions haha. Thanks guys.
Represent characters that have special meaning in HTML using entities. Since you are using PHP, use htmlspecialchars
There are millions and millions of ways to do this. The easiest is to use htmlspecialchars or htmlentities on the user's input. This will make a visual </textarea> in the textarea box without closing it. This actually turns it into </textarea>. htmlspecialchars transforms less characters than htmlentities and usually makes more sense to use in a situation like this, but do your research.
strip_tags() is also a possibility.
You can also use a regular expression with PCRE, or even str_replace() or other string manipulation functions to strip off the textarea, convert the special characters, etc.
PECL also as a BB code extension you can use if you still want your users to be able to enter some for of tags to style their output.
<textarea><?php echo htmlentities($code); ?></textarea>
You have to transform the html code into symbols, so it is not treated as html.
Use the function htmlentities() on the textarea content before echoing it.

How do I remove HTML tags from a string?

I have a php script, where the user inserts his name.
Users can insert anything they want, even things like <img src="....
I would like to save their input in a way it won't show any image (or any html).
I know it exists but I don't know what keywords to search in order to find what does it.
Use strip_tags($str).
http://php.net/strip_tags
htmlspecialchars() will encode the text so that the tags are not interpreted as HTML.
The easiest solution is the PHP function strip_tags(), which does exactly what the name suggests, and strips HTML tags from a string.
The other alternative is to 'escape' the input, so that HTML characters such as < and > are converted into displayable text. This would result in the HTML code being displayed.
You would do this with the function htmlentities().
It's worth pointing out that the input may contain HTML characters without actually intending to be HTML. The & character is a HTML reserved character, but can also be found in normal text. > and < are less commonly used in normal text, but still possible. All of them may cause problems when displayed on your page, without necessarily being actual HTML code.
The solution to this is as above, to escape the string using htmlentities(). You may want to run striptags() first, but you should also run htmlentities() as well, to ensure that the string is displayed correctly.
Hope that helps.

What's the trick to display a text from MySql/PHP back to its original HTML layout?

It still keeps the original text layout (I mean the spacing, offsets, new line, paragraphs) while the text fragment is stored in MySql ('text' type) field - I can tell when I peer into it in my DB browser (Adminer:)
but it gets lost when I output it from the DB: it becomes a single line string of my text characters. How can one restore it its original layout?
I've tried to reshape the text fragment using the PHP nl2br() function with some success:
it brought back the newline breaks, but the text words positioning is not kept, everything
shifts to the left.
Thanks in advance for a good idea.
If you've got multiple spaces and things like that. e.g. for code. Then trying using the pre tag.
http://htmldog.com/reference/htmltags/pre
http://reference.sitepoint.com/html/pre
The html_entity_decode() function converts HTML entities to characters.
The syntax is:
html_entity_decode(string, [quotestyle], [character-set]);
You can refer example2.

Categories