Hey, I have an example of a “posting an article by user input” script, which input then will be displayed on a certain website; though there are probably some security issues within that script that I’d like to know how to prevent, - for instance, SQL-Injection.
Here’s the code:
<?php
// Noetig fuer die Datenbank.
require('php/connect.php');
// Unsere Variablen.
$postnews = $_POST['postnews'];
$ip = $_SERVER['REMOTE_ADDR'];
// Unsere if-statements.
if (empty($postnews)) {
echo"Bitte gebe deinen Newsbeitrag ein.";
}
else {
// Wenn alles uebereinstimmt, fuege es in die Datenbank hinein.
mysql_query("INSERT INTO news (post, ip) VALUES ('$postnews', '$ip')");
header('Location: index.php');
}
?>
The $postnews variable is a declaration for the <input> field, which lets someone post something; - how and why would someone be able to inject SQL queries? Why would it work, and how would I prevent it? I’d like to see code examples of how I can prevent it.
Validating all user inputs and sanitising them with mysql_real_escape_string() or using prepared statements are your best defences against sql injection or other attacks.
also it’s probably good to keep in mind that if you are building commercial database driven websites, or any website for that matter, you need to not leave yourself vulnerable to being sued for compensation and/or damages for being “negligent” in your coding.
You might also look into using prepare/bind instead of query to do the database updaters as that keeps the data completely separated and so makes SQL injection completely impossible.