0

How to block any PHP code inside a HTML code?

I have a function in my application where user create a HTML page, with HTML code, Javascript code and CSS code. But I can't allow him to save any PHP code, because this content will be saved in a file and loaded in the server.

<html lang="pt-BR">
    <head>

    </head>
    <body>
        <h1>This is allowed</h1>
        <?php echo "DELETE THIS LINE"; ?>
    </body>
    <script>
         console.log("THIS IS ALLOWED");
    </script>
</html>

I need to comment or delete the PHP code, but i don't have idea how to do that.

2
  • I will try with str_replace Commented May 22, 2019 at 18:21
  • I think str_replace worked well. Commented May 22, 2019 at 18:57

2 Answers 2

0

Don't include the file and the PHP won't execute (it will be in the HTML source as an unknown HTML tag but not executed). Just read it and output:

$output = file_get_contents("/path/to/file.html");
echo $output;
//or
readfile("/path/to/file.html");

Or if you want to include it, then comment the PHP before writing to the file (it will be a comment in the HTML source):

$output = str_replace(['<?php', '?>'], ['<!--', '?>'], $html);
file_put_contents("/path/to/file.html", $output);

//where you want to use it
include("/path/to/file.html");
Sign up to request clarification or add additional context in comments.

Comments

-1

You need to use the php function htmlspecialchars() to sanitize user's code. See doc here

5 Comments

That will wreck the HTML as well.
htmlspecialchars() not worked.
@AbraCadaver Yes, but then the echo will give it back its syntax without executing it.
But they state that they want HTML, CSS and JavaScript to work correctly.
@AbraCadaver right it's true

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.