3

I am creating a directory where the users are able to post articles. To get the values to be posted I am using inputs html elements and using $.post to save the data in the database.

However, I have a problem that if an user writes some html code in the article it is saved formatting the code.

for example if the value entered is:

<input type="text" value="this is an article title <script>$("body").remove();</script>">

when the post is submitted the page will load also the js script removing the body.

How can avoid this and tell that in the input field there is a script, or formatting the script to show as a text?

4
  • 1
    You need to sanitise user inputs on the server - JS/jQuery is not the right tool for this job as it's far too easy to get around. Commented Oct 8, 2016 at 14:40
  • I have to do it on my php get? Commented Oct 8, 2016 at 14:41
  • 1
    Check out htmlspecialchars(). Commented Oct 8, 2016 at 14:42
  • thanks a lot it works ----- $title = htmlspecialchars(filter_input(INPUT_GET, "title"), ENT_QUOTES); Commented Oct 8, 2016 at 14:50

1 Answer 1

2
<?php

//Simple answer
#when you echo data results from the database. consider code below..
#Assuming you are at the last process of echoling the data out.
$data='THIS WOULD BE YOUR DATA OBJECT OR VARIABLE CONTAINING DATA FROM THE DATABASE';


#then...
$data=htmlentities($data);
#or
$data=strip_tags($data);
#or
$data=htmlspecialchars($data);


#just be assured that tags or code will not be executed by the browser once above is included!
echo $data;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but when I return the data I return it as a json
then json encode your data. like ==> $data=json_encode(htmlspecialchars($data));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.