0

I have a site which allows the user to save images. I sanitize mysql inserts with 'mysql_real_escape_string', but someone went and entered a meta with a content redirect in his image description, so that whenever our site loads (loading the latest images as well), it redirects.

How can I sanitize my strings or sql queries to protect against that?

Thanks in advance!

Phil
  • 1,719
  • 6
  • 21
  • 36
  • Use framework that protects from MySQL Injections. – s.webbandit Sep 12 '12 at 09:39
  • 2
    `strip_tags()` on input and `htmlspecialchars()` on output are a good start - also, if accepting image uploads, make sure you use GD to copy the pixel data from the uploaded file to a new one, or it is possible for malicious code to be hidden inside the image itself. – DaveRandom Sep 12 '12 at 09:40
  • 1
    possible duplicate of [What are the common defenses against XSS?](http://stackoverflow.com/questions/3129899/what-are-the-common-defenses-against-xss) – Quentin Sep 12 '12 at 09:41
  • Also, welcome to the world of XSS and CSRF (Google them) – DaveRandom Sep 12 '12 at 09:42

4 Answers4

0

For this particular example, you could have avoided it by using htmlentities when outputting the data:

<?php
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

The catch is that it would destroy pretty much any HTML from being used in the stuff you are saving. If you are trying to allow certain tags and disallow others, it quickly gets a lot more complicated.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
0

mysql_real_escape_string is only used to prevent sql injection.

To prevent XSS, you need to use htmlspecialchars or htmlentities to sanitize the html content.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

I think you should be using the htmlspecialchars(); everytime before putting anything from the database and before you submit the user input to the database use prepared statements + htmlspecialchars();[optional]

D. Dimitrov
  • 89
  • 10
0

Here is couple of things you can do

  1. Use strip_tags()
  2. Use mysqli_* function instead of mysql_
  3. Use parameterized queries/prepared statments.
  4. If possible consider using PHP Frameworks.
  5. Convert special character into their respective htmlentities()
WatsMyName
  • 4,240
  • 5
  • 42
  • 73