PHP Write HTML tags into file and display it

Tags: , , , ,



I want to make a simple comment system in PHP and my problem is when the user type ‘<‘ it disappear because it takes it to HTML code and mess my code. So what I need to do, when the user type this into the textarea: <stdio.h>, and post it, it should appear as <stdio.h>.

My PHP code:

I want to make a simple comment system in PHP and my problem is when the user type ‘<‘ it disappear because it takes it to HTML code and mess my code. So what I need to do, when the user type this into the textarea: <stdio.h>, and post it, it should appear as <stdio.h>.

My PHP code:

<form method="post" name="formc" id="formc" >
    <textarea name="txtmsg" id="txtmsg" cols="25" rows="5" placeholder="Write something!" required="required"></textarea>
    <br>
    <input type="submit" value="Submit" name="submit" /> 
<?php
if ( isset( $_POST[ 'submit' ] ) ) {
    $com  = $_POST[ "txtmsg" ];
    $file = fopen( "inrg.txt", "a" );
    fwrite( $file, "<em>Anonymous:</em>" );
    for ( $i = 0; $i <= strlen( $com ) - 1; $i++ ) {
        fwrite( $file, $com[ $i ] );
        if ( $i % 37 == 0 && $i != 0 ) fwrite( $file);
    }          
    fwrite( $file, "<br>" );
    fwrite( $file, "<em>Sent: ".date('Y F j, H:i:s')."</em>");
    fclose( $file );

    echo '<script type="text/javascript">window.location ="";</script>'; // Add here
}
?>
    <br>
</form>
<?php
if (file_exists("inrg.txt")) {
    $file = fopen( "inrg.txt", "r" );
    echo fread( $file, filesize( "inrg.txt" ) );
    fclose( $file );
}
?>

Answer

I am wondering why you are writing the file one byte at a time, there must be some really dodgy sample code out there somewhere. If you use htmlspecialchars() it will convert special characters to HTML entities

if ( isset( $_POST[ 'submit' ] ) ) {
    
    $file = fopen( "inrg.txt", "a" );
    fwrite( $file, "<em>Anonymous:</em>" );
    fwrite( $file, htmlspecialchars( $_POST['txtmsg'] ));
    fwrite( $file, "<br>" );
    fwrite( $file, "<em>Sent: ".date('Y F j, H:i:s')."</em>");
    fclose( $file );
}

RESULT in File

<em>Anonymous:</em>include &lt;stdio.h&gt;<br><em>Sent: 2021 January 14, 18:01:54</em>

PHP Manual htmlspecialchars()
And if you need it
PHP Manual htmlspecialchars_decode()



Source: stackoverflow