This tutorial is a continuation of my Web Design and Programming Tutorial, but if you’re are well versed in PHP you should understand everything I present here.
I specifically will show you how to:
This is just the beginning of what will be a pretty long PHP Security tutorial. I’m going to cover how the following tricks work and how to block them:
It should be fun
All of the code used follows the video. Leave any questions or comments below. I use Sucuri Security here to keep my site hacker free.
Code From the Video
Database Config File
<?php
// Define these as constants so that they can’t be changed
DEFINE (‘DBUSER’, ‘mysqladm’);
DEFINE (‘DBPW’, ‘Turtle2Dove’);
DEFINE (‘DBHOST’, ‘localhost’);
DEFINE (‘DBNAME’, ‘hamdb’);
if ($dbc = mysql_connect (DBHOST, DBUSER, DBPW)) {
if (!mysql_select_db (DBNAME)) { // If it can’t select the database.
trigger_error(“Could not select the database!<br />”);
exit();
}
} else {
trigger_error(“Could not connect to MySQL!<br /> “);
exit();
}
function escape_data ($data) {
if (function_exists(‘mysql_real_escape_string’)) {
global $dbc; // Need the connection.
$data = mysql_real_escape_string (trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string (trim($data));
$data = strip_tags($data);
}
return $data;
}
?>
Regular Expression Code
<?php
require_once(“./includes/confighamdb.php”);
if (isset($_POST['submitted'])) { // Handle the form.
// Check for a first name.
// Unquote a quoted string with stripslashes
if (preg_match (‘%^[A-Za-z\.\' \-]{2,15}$%’, stripslashes(trim($_POST['first_name'])))) {
$fn = escape_data($_POST['first_name']);
} else {
$fn = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter your first name!</font></p>’;
}
// Check for a last name.
if (preg_match (‘%^[A-Za-z\.\' \-]{2,30}$%’, stripslashes(trim($_POST['last_name'])))) {
$ln = escape_data($_POST['last_name']);
} else {
$ln = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter your last name!</font></p>’;
}
// Check for an email address.
if (preg_match (‘%^[A-Za-z0-9._\%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$%’, stripslashes(trim($_POST['email'])))) {
$e = escape_data($_POST['email']);
} else {
$e = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid email address!</font></p>’;
}
// Check for a street.
if (preg_match (‘%^[A-Za-z0-9\.\' \-]{5,30}$%’, stripslashes(trim($_POST['street'])))) {
$s = escape_data($_POST['street']);
} else {
$s = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter your street address!</font></p>’;
}
// Check for a city.
if (preg_match (‘%^[A-Za-z\.\' \-]{2,25}$%’, stripslashes(trim($_POST['city'])))) {
$c = escape_data($_POST['city']);
} else {
$c = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid city!</font></p>’;
}
// Check for a state.
if (preg_match (‘%^(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N{CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$%’, stripslashes(trim($_POST['state'])))) {
$st = escape_data($_POST['state']);
} else {
$st = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid state!</font></p>’;
}
// Check for a zip code.
if (preg_match (‘%^[0-9]{5}$%’, stripslashes(trim($_POST['zip'])))) {
$z = escape_data($_POST['zip']);
} else {
$z = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid 5 digit zip code!</font></p>’;
}
// Check for a phone number.
if (preg_match (‘%^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$%’, stripslashes(trim($_POST['work_phone'])))) {
$ph = escape_data($_POST['work_phone']);
} else {
$ph = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid phone number!</font></p>’;
}
// Check for a password and match against the confirmed password.
if (preg_match (‘%^[A-za-z0-9]{4,20}$%’, stripslashes(trim($_POST['password1'])))) {
if ($_POST['password1'] == $_POST['password2']) {
$p = escape_data($_POST['password1']);
} else {
$p = FALSE;
echo ‘<p><font color=”red” size=”+1″>Your password did not match the confirmed password!</font></p>’;
}
} else {
$p = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid password!</font></p>’;
}
Hi,
Just found your site. I’m one of those dangerous type developers that have been self taught so have previously had vulnerabilities all over the place in my code, luckily nothing live just hobby stuff on my local PC.
I’m glad I found your site and I look forward to working through all of your tutorials
When working through this one I have an error:
Parse error: syntax error, unexpected ‘^’on line 24
I was wondering if this might be related to the version of php being used?
Also I was wondering about a less secure… secure (ok thats an oxymoron) State field. Lets say I want people from all over the world to register, it would be extremely time consuming not only to enter state abbreviations but also to figure out how the locals abbreviate them and to make allowances for that within the code.
I’m not planning on using State fields but thought it may come in useful in case something similar comes up later on. Of course I’m also a little behind with what you have released so far so you may have already discussed this.
Keep up the great work and thanks for doing this!
John C.
Hi John, normally if you get any errors in my code it is because wordpress replaces normal quotes with back quotes. In recent tutorials I’ve started to provide links to the original code. I should have done that in the past, but to fix the code just run a find and replace to change back quotes to normal quotes.
As per the state field stuff I don’t know that much about other counties, but if you just limit input to a small number of characters and don’t allow anything but letters you’ll be ok.
Hope that helps
Thanks for the tip!
Just thought I would drop in a quick note after I got it working for anyone else that does a copy and past on the above code.
As well as finding and replacing all the ‘ and ” for some reason the .html in the form area that I pasted had ? in some places instead of “.
More often than not that was the last quote before the close brackets > and of course was triggering a php close statement and confusing my browser :S
Thanks for pointing that out. All of my new tutorials provide links to the raw files that have been triple checked for errors. The quote thing is done for security reasons. Sorry about that
Hi,
I love these tutorials. I am a beginner freelancer. I have been using PHP and MySql for quite some time, writing a lot of insecure code
. However, now i can write better code. I just have one problem. Recently, I got a project in which I have to use MS SQL Server with PHP. And I found that the inbuilt methods in PHP are only for mysql. They dont work well for SQL Server. Can you tell me what things I should do to maintain security in my code.
Thanks a bunch. I’m sorry though I don’t use anything that isn’t free so I haven’t used Microsofts applications for many years. This may help Microsoft PHP SQL Server Training Kit
Great read I have been learning PHP for a short while but wanted to learn about security and the every growing list of potential problems.
Could you please let me know what this means.
Fatal error: Call to undefined function escape_data()
That function is setup in the external file that connects to my database. It’s a function that helps scrub potentially unsecured code. That error is just stating that it can’t find that function
Ok I have fornd and sorted out that little error.
Does it matter what format the user places there phone number in as.
xxxx (x) xxxx xxxxxx
or
+xx xxxx xxx xxx
I didn’t set it up to except any number in the world but that can easily be fixed by following the regex I did create.
I am getting there, the Phone is sorted out.
I just have to work on why I am getting the Please Try again message.
How Do you deal with optional fields?
like fax and cell numbers. and comments sections etc.
They are not essential but still vulnerable to attack.
Thanks
Richard
I cover pretty much everything you need in regards to PHP Security in these tutorials
PHP Security
PHP Security Pt 2
PHP Security Pt 3
PHP Security Pt 4 Set Up Captcha
PHP Security Pt 5 SQL Injection
PHP Security Pt 6 Directory Traversal
Web Design and Programming Pt 21 Secure Login Script
It’s a complicated subject, but with these tutorials you should be able to block most attacks.
I hope that helps?
Thanks
You did a great job.
Thank you!
Thank you. I’m glad you liked it. Thanks for taking the time to say hi
Hi,
I know absolutely nada about building websites and coding, but i have been learning by following tutorials, I must say I respect you all who do it. Anyway I wish i found you earlier this year. I copy and pasted the configdb.php im guessing that i am to put this on my server and run it like this domainName.com/configdb.php but when i did that on my site i received this error: Not Found
The requested URL /configdb.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Apache Server at http://www.deardiarys.com Port 80
also when i copy and pasted the file into Dreamweaver these two lines were in red indicating an error.
trigger_error(“Could not select the database”);
trigger_error(“Could not connect to MySQL “);
one more thing must i leave this in all my scripts
Untitled Document
Sorry its so long!
God Bless and Thank Youuu
Hi
It is probably best for you to start out with my more basic tutorials like this Web Design Tutorial. My PHP Security tutorial is one of the most advanced ones I have ever made. Learn HTML, CSS, JavaScript and PHP on the page I provided and then move into How to Layout a Website. That knowledge will allow you to make anything you’d like. I hope that helps. God Bless
ok I will do that but is there anything i’m missing from what i copy and pasted besides the back quote and the “?” that i didn’t see? what else would cause it to give me error, im using cs5 Dreamweaver.
I can see the basic tutorials are working for you. That’s great
It’s kind of hard for me to figure out what may have gone wrong. If I was you I’d avoid Dreamweaver because it can actually confuse you when you are learning. I think a basic text editor is definitely best. I use TextWrangler on the Mac and Notepad++ on PC.
I started the basics tutorial you’re a great teacher. I wish you were my professor before i decided to quit when i was in school. All i heard was blah blah blah lol. You’re great i understand everything you’ve taught so far !
I very much appreciate that
I don’t know why there are so many bad teachers? I guess they have just lost the passion to teach? I’ll do my best to live up to expectations
I still cant figure the errors im getting i copy and pasted so there should be no errors, i also triple checked my db info its still not working
Did you replace all of the backquotes with regular quotes? My website does that for security reasons in old posts. Just do a find and replace all if you haven’t tried that. Sorry for making you have to take this extra step. I plan to fic it, and I have fixed it in all of my code over the last few months. I hope that helps
Hi Derek,
I appreciate your efforts these extremely helpful tutorials. I have the following question: I can’t understand why you check for the existence of mysql_real_escape_string function; isn’t that a built-in function in recent versions of php? Would you please explain that; thanks.
I do that in case someone takes this code and tries to use it. I try to write tutorials that will work on numerous configurations. That sometimes makes the code longer than needed, but it also avoids potential errors. Sorry I forgot to point that out in the video