Markus Markus - 3 months ago 16
PHP Question

Safely store textarea input with newlines and preserve linebreaks

I have a problem storing a user submitted presentation in a database as a TEXT field. It shall not allow any HTML whatsoever but should preserve the linebreaks.

So for example if the user submits an presentation like this from a form using a textarea as input method:

This is line 1

This is line 3

This is line 4

It shall be outputted exactly like that and clean the input from any HTML in the process.

Stored procedure:

if (isset($_POST['presentation'])) {
$presentation = $purifier->purify($_POST['presentation']);
$presentation = $mysqli->real_escape_string($presentation);
if (strlen($presentation) > 1000) {
return 2;
}
}
else {
$presentation = null;
}

if ($update_stmt = $mysqli->prepare("UPDATE user SET user_presentation = ?
WHERE user_id = ?")) {
$update_stmt->bind_param('ss', $presentation, $user_id);
}
if ($update_stmt->execute() == false) {
$success = 0;
}
$update_stmt->close();


And to output after fetching:

<p><?php echo nl2br($profile['presentation']); ?></p>


It is stored as this in the database:

This is line 1\r\n\r\nThis is line 3\r\nThis is line 4


And displayed on the page as:

This is line 1rnrnThis is line 3rnThis is line 4


What I want is the presentation to be displayed as it was submitted by the user with the newlines preserved, cleaned of any HTML and safe to be stored in the database.

I have tried strip_tags, stripcslashes etc but I still can't get it to work..

Someone who might be able to help?

Thanks in advance.

Answer

You could translate them into their respective escape sequences using str_replace before passing the string through nl2br(). This is an example:

$profile = nl2br(str_replace('\\r\\n', "\r\n", $profile['presentation']));
Comments