Hi there, I'm a bit of a newbie PHP coder and just created a webpage that allows visitors to fill out a text field, which is submitted into an SQL table. The page also displays, at random, one of the submissions received. Now I am aware that this is wide open for abuse, can anyone please point me to some tutorials or anything that can help me tighten things up? Also, how do I stop blank submissions?! Thanks
Blank submissions are easy to fix. Simply have an if statement: if(empty(trim($_POST['fieldname']))){ echo 'error, blank'; } else { // do your submission code here } Code (markup): The trim() removes whitespace from the front and end of the string, so it stops someone just putting a space. As for securing the database, you can easily prevent SQL injections by using mysql_real_escape_string on the fields you're inserting into the database.
I tried that if statement but couldn't get it to work I get the error Fatal error: Can't use function return value in write context in... Code (markup): This is my code (before entering the if/else statement <?php $textjcge = $_POST['textjcge']; /* Connect to MySQL Database */ include ('config.php'); /* Insert new row */ $query="INSERT INTO entries (id, title, votes_up, votes_down) VALUES ('NULL','".$textjcge."','NULL','NULL')"; mysql_query($query) or die ('Error updating database'); echo "Database updated with : " .$textjcge. ""; ?> PHP:
Try this: $var = trim($_POST['fieldname']); if(empty($var)){ echo 'error, blank'; } else { // do your submission code here } PHP:
You should use mysql_real_escape_string on all strings you´re about to enter into mysql Also validate so that your integers are truly a numeric value and if you expect it to be between two values check so it really is. I use a function called is_valid_id for ID values // Check if id is numeric // Check so that id is more than 0 // Check so that is isn´t a decimal // Returns bool function Is_Valid_Id($id) { return (is_numeric($id) && $id > 0 && strstr(".",$id) == false); } // Check if num is numeric // Check so that num is greater than min // check so that num is lower that max // Returns Bool function is_between($num, $min,$max) { return (is_numeric($num) && $num > $min && $num < $max); } PHP: im sure there are more ways to do this.. but haven´t been hacked yet, knock on wood
Thank you. I've implemented trim and real_escape As for the is_valid_id, I don't think I need that because ID is an auto-incremented field, the user does not submit any data to this. Am I correct in saying I don't need to use that? Cheers
Actually depends if you´re going to update och select the fields after you have inserted them .=) As for validation through Javascript.. more insecure than that is not possible.. hell the user can alter the javascript loaded through plugins so you should always validate data on serverside..