0
votes

I Own a website for posting forums like questions and answers with a database. I want to hardeen my code to prevent both XSS and SQl injection..

for XSS I used the folloinf function : Strip_tags htmlspecialchars htmlentities

My question is: what is the difference between them ?? Also, I face a problem with them which is : 1- I have a textarea and text boxes with default text 2- when using the above functions and I entered any test in the text area.. the output will not take what I wrote in the textarea.. it will always take the default value...

this is what I did

$first_name = $_POST['first_name'];
$first_name = htmlspecialchars($first_name);
echo $first_name

also, any one has any idea about preventing from SQL injection, I have no idea about it ..

2
Prepared queries will protect you from SQL injections. - transilvlad
can u give me an example please - optional

2 Answers

0
votes

To prevent XSS you should use different filtering rules dependent on the area that you are outputting to.

hmtlentities (which translates <to &lt;) is fine, but outputting unsafe variables to the <head> or <script> or <style> tags;

Another tricky areas is tag attributes like <input onMouseDown="" becuase people can break your string and add their own attributes (just like SQL injection).

This subject is covered in depth in the following places:

http://adamjonrichardson.com/2012/02/01/improving-xss-cross-site-scripting-prevention-in-four-simple-steps/ https://www.golemtechnologies.com/articles/prevent-xss

You can also look into using PHP's filter_var function, very useful.

0
votes

Straight from the manual. http://php.net/manual/en/mysqli.prepare.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

For XSS strip_tags will do. Unless someone cracks your FTP password and they go in and edit your files or if you allow them to upload an exploit so make sure you disable script execution in your upload folders.