sahmed sahmed - 5 months ago 14
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=\"https://code.jquery.com/jquery-3.0.0.min.js\" 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="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<html>
<head>
<meta charset="utf-8" />
<title>CodeType</title>
</head>
<body>


Here is my code:

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

if(isset($_POST['submit'])){
$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";
}
}

?>

<body>

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

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

</body>
<script>
$(document).ready(function(){
$('.txtInput').bind("paste",function(e) {
e.preventDefault();
});
$( "button" ).on( "click", function(){
if($(#txtInput).text() == $(#code).text()){
alert("Working");
} else {
alert("Failure");
}
});
});

</script>

</html>


Any ideas?

Answer

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.


Modifications:

$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']));
Comments