Hi there, relatively new to PHP, picking it up well and learning quickly. Any pointers as to how secure my script is? E.g. someone entering ‘Drop Table’, etc. Any help and advice is appreciated.
<?php
error_reporting(0);
$email = "";
$msg_to_user = "";
if ($_POST['email']!=""){
include_once "connection.php";
$email = $_POST['email'];
$sql = mysql_query("SELECT * FROM addresses WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email){
$msg_to_user = '<div class="msg_to_user">Please type an email address.</div>';
}
else if ($numRows>0){
$msg_to_user = '<div class="msg_to_user">'.$email.' is already in the system.</div>';
}
else {
$sql_insert=mysql_query("INSERT INTO addresses (email, dateTime)
VALUES('$email',now())") or die (mysql_error());
$msg_to_user='<div class="msg_to_user_success">You have been added successfully.</div>';
$email="";
}
}
?>
This is a huuuge topic… you might want to google ‘sql injection’
Definately use mysql_real_escape_string, it is a must… but you should also go a bit further than that and make sure the user is entering input that you expect.
If you have a form that asks for a users age for example, make sure that it is a number. If it is a username make sure it only contains letters.
Hi, managed to do it, thanks for your help guys. So mysql_real_escape_string would stop a potential injection by adding \ to any " ’ or something as with the \ I’m presuming that database won’t execute them?
Correct. mysql_real_escape_string should make your script about 99% secure… but it is always good practice to add in some of your own validation.
Going back to the age example I posted before, consider this:
You have a form asking someone to enter their age, a (malicious or even non malicious) user enters a string in the age field. You apply mysql_real_escape string to it, there is now no way that there could be any sql injection going on… however, when your script comes to enter the data in the database, mysql throws an error because you are entering a string into an int field.
This can cause a couple of problems… firstly, it is not a very friendly user experience… users get very freaked out when they are encountered with the phrase ‘server error’.
Secondly, a server error often gives away information about the server software itself… the version of apache you are running for instance…
So, using mysqq_real_escape_string will stop sql injection but it will not protect you against 100% of threats.