Is there anyway to improve/change this form to better handle sql injections ? <html> <body> <form action="<?php $_SERVER[PHP_SELF]; ?>" method="post"><br /> Name: <input type="text" name="name" /><br /> Age: <input type="text" name="age" /><br /> Description: <textarea name="description" rows="2" cols="20"></textarea> <input name="submit" type="submit" /> </form> </body> </html> <?php if (isset($_POST['submit'])) { //check if the form was submitted if (!empty($_POST['name']) && !empty($_POST['age']) && !empty($_POST['description'])) { echo "Please fill in all the fields"; die();} // Connect $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password'); $select = mysql_select_db('mysql_name', $link); if(!is_resource($link)) { echo "Failed to connect to the server\n";// ... log the error properly } elseif(!$select) { echo "Failed to select database"; } else { // Reverse magic_quotes_gpc/magic_quotes_sybase effects on those vars if ON. if(get_magic_quotes_gpc()) { $name = stripslashes($_POST['name']); $age = stripslashes($_POST['age']); $description = stripslashes($_POST['description']); } else { $name = $_POST['name']; $age = $_POST['age']; $description = $_POST['description']; } // Make a safe query $query = sprintf("INSERT INTO users (`name`, `age`, `description`) VALUES ('%s', '%s', %s)", mysql_real_escape_string($name, $link), mysql_real_escape_string($age, $link), mysql_real_escape_string($description, $link)); mysql_query($query, $link)or die(mysql_error()); if (mysql_affected_rows($link) > 0) { echo "Username Added\n"; } } } ?> Code (markup):
Looks save to me. But you could use for example intval() for the age. No need to let the user enter non-numeric data. And you could use preg_replace() or preg_match() to make sure the name only contains characters you want to allow. But the way it is right now, there should not be a danger.
<form action="<?php $_SERVER[PHP_SELF]; ?>" method="post"><br /> PHP: This line is vulnerable to XSS, but I don't see any SQL injections.
How? The user cannot modify the value of the variable. If it was QUERY_STRING, then yes, but not PHP_SELF. EDIT: Actually, there's no risk at all, because he forgot the echo.
Yes, PHP_SELF is vulnerable.. http://site.com/index.php/"><script>alert(1)</script> is a perfectly legal URL, and will result in XSS.
[To Fash]: In that case, should he use htmlspecialchars() around $_SERVER['PHP_SELF'] or just have a value of "" for the action attribute? I'm curious as well.
1. because it doesn't have any echo or something like this i think it doesn't have any problem. 2. you can easily use 'htmlentities' , like this : /* Filter Input ($name, $comment) */ $clean_name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
mehdiali: I was just about to suggest the look up http://us3.php.net/htmlentities on the web and use that also.