sahmed sahmed - 1 year ago 40
HTML Question

Need help creating a php program that echoes code

I am creating a program that is supposed to take a code input from the user and it will match it with some other sample code, and once it is done it will print the users input code. The part that I am having trouble with is when I print the users code, everything is printed but instead of indents and line breaks, this is being printed:

<!DOCTYPE html>\r\n <script src=\"\" integrity=\"sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=\" crossorigin=\"anonymous\"></script>\r\n<html>\r\n <head>\r\n <meta charset=\"utf-8\" />\r\n <title>CodeType</title>\r\n </head>\r\n <body>

whereas this is the input (and what I want as the final result):

<!DOCTYPE html>
<script src="" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<meta charset="utf-8" />

Here is my code:

<?php include "database.php"; ?>

$title = mysqli_real_escape_string($con, $_POST['title']);
$code = mysqli_real_escape_string($con, $_POST['code']);
$samplecode = mysqli_real_escape_string($con, $_POST['samplecode']);

$query = "INSERT INTO `assignments` (`title`, `code`) VALUES ('$title', '$code')";

$cleanCode = str_replace( "\r\n", "<br/>" , htmlentities($code));
if(mysqli_query($con, $query)){
if($code = $samplecode){
echo $cleanCode;
} else {
echo "fails";



<form method = "post" action = "">
<label id = "title">Title</label>
<input type="text" class="txtInput" name = "title"/>
<label id = "stuff">Code</label>
<textarea placeholder="Type your code in here" name = "code"></textarea>
<label id = "samplecode">Sample testing</label>
<textarea placeholder="Type your test code in here" name = "samplecode"></textarea>
<input type="submit" name = "submit" value="Submit"/>

<pre><?php echo $cleanCode ?></pre>

$('.txtInput').bind("paste",function(e) {
$( "button" ).on( "click", function(){
if($(#txtInput).text() == $(#code).text()){
} else {



Any ideas?

Answer Source

Background Info:

  1. Like C, PHP presumably (said that way because I haven't found a reference for it yet...) converts \r\n / \n to just an \n.
    (Different sequences are used for a newline depending on the OS.)

  2. mysqli_real_escape_string() escapes \r and \n, among others.


$cleanCode = str_replace( "\r\n", "<br/>" , htmlentities($code));

should be:

$cleanCode = str_replace( "\n", "<br/>" , htmlentities($code));

& that should be changed to:

$cleanCode = str_replace( "\n", "<br/>" , htmlentities($_POST['code']));