PHP Security

Regex TutorialThis 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:

  • Hide your database access files
  • How to eliminate code injection with regular expressions
  • Introduce a bunch of PHP functions that will delete harmful code

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:

  • SQL Injection
  • Cross Site Scripting (XSS)
  • Malicious Code Encoding
  • Session Hijacking
  • Session Fixation
  • Malicious System Calls
  • Buffer Overflows

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

// 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 />”);



} else {

trigger_error(“Could not connect to MySQL!<br /> “);



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


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>’;


40 Responses to “PHP Security”

  1. John C. says:


    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.

    • admin says:

      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 πŸ™‚

    • Jonas says:

      Hey!, can you send all the files for the whole tut ? to my email ? πŸ˜€ the email is , if you will ask why i am asking, is because i am geting loads of errors when i copy and paste it, can you also send me the Database thing ?

  2. John C. says:

    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

    • admin says:

      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

  3. Ankit Gupta says:


    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.

  4. Richard says:

    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()

    • admin says:

      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

      • Richard says:

        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
        +xx xxxx xxx xxx

  5. Richard says:

    I am getting there, the Phone is sorted out.
    I just have to work on why I am getting the Please Try again message.

  6. Richard says:

    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.



  7. Ramit Walia says:

    You did a great job. πŸ™‚ Thank you!

  8. Zerbie says:


    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 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 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

    • admin says:


      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 πŸ™‚

      • Zerbie says:

        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.

        • admin says:

          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.

      • Zerbie says:

        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 !

        • admin says:

          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

  9. Zerbie says:

    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 πŸ™

    • admin says:

      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

  10. Wardak says:

    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.

    • admin says:

      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

  11. Chris says:


    I don’t have any specific questions in relation to the video, or the code or anything really..

    I just wanted to say thank you for the videos, you make even the most complex topics seem simple to understand, and your videos are always of such a high quality, that’s rare to see these days πŸ˜€

    Anyway yeah, thanks and hope you keep up the great work!


    • admin says:

      Thank you very much Chris πŸ™‚ Your kind words are greatly appreciated and I plan on making many, many more videos. Thanks for watching and always feel free to ask questions and make requests – Derek

  12. Dave says:

    Hi Derek, thanks for the tutorial, the security issue is always going to be a problem due to the rate technology changes but with explanations like yours it makes it a lot easier to understand.

    I will start working through all of your security tutorial side as I know I have great big holes in my site which I thought at the time was safe….ish.

    • Derek Banas says:

      You’re very welcome Dave πŸ™‚ I hope to redo this tutorial so I can cover many of the issues in a much better way. You’ll find many of the frameworks available for PHP can really make your life easier. I’ll get to them as soon as possible

  13. Jonas says:

    Hey!, can you send all the files for the whole tut ? to my email ? the email is , if you will ask why i am asking, is because i am geting loads of errors when i copy and paste it, can you also send me the Database thing ?

  14. Dipankar Sutradhar says:

    Hello Derek,
    A fly has a longer attention span than me, and your video tutorial is exact, to the point and concise. Based on the videos, I used to think you can type that quick, then you mentioned on of your videos you edit them half the size. So first of all, thank you for all yours videos.

    I do have one question. Unless I have missed it. Where is the code for sending email with a link and to verify the email account?

    Once again, thank you from keeping things simple and way less intimidating. I am a pure noob and I sincerely appropriate your teaching style.

    Thank you!

    • Derek Banas says:


      I’m very happy that you enjoy the videos. I decided that everyone else makes slow tutorials so I’ll make them fast. I’m glad you like them that way πŸ™‚

      I think this is the code you are looking for PHP Login. I really need to redo this tutorial with Zend, but the code you want for email verification is there and it works.


      • Dipankar Sutradhar says:

        Thank you Derek,

        Funny you mention it, I am actually using zend gdata for the Google Spreadsheet. It works really well. But I had no php security until now.

        Sorry to ask you again (I left a comment in YouTube, video part 1 much more detail explanation). Would it create a hole or make a difference in php security if you were to declare the $fn = $_post[‘first_name’] then call the $fn where you need it?

        Now I am paranoid about this web form. Me being a noob only makes it worse for me. I had a friend’s small business online ordering website getting hacked.

        Your time is much appreciated!

        • Derek Banas says:

          You’re very welcome πŸ™‚ All I ever use security wise now is Zend. If possible I use a CMS like WordPress that has numerous security plugins that are very hard to get through. I don’t know how to get through them any way. This tutorial is more like a guide then anything else to explain some large holes you can try to fill.

          Can your current project be used on WP? Some times you may think that it can’t, but if you gve me an idea of what you are doing I will give a more informed opinion if that would help?

          • Dipankar Sutradhar says:

            Please Please Please make the zend video. I know you mentioned a few times you will do it. Eagerly waiting… It took me a while to understand and get it to work (I was working with wrong file). If you google “gdata spreedsheet” the first 2 results. One of them is this main one,

            What I am working on is a non-profit organization’s website. I am trying to create the new membership online form. So far I implemented the JS validation, php server-side validation, PHP Mailer with SMTP. All gets send to a Google Spreadsheet with Google Spreadsheet PHP Helper Class and Zend Gdata Client Library (see the above link). Then email address verification by sending email with md5 code. Activation code match I did it different than how other video tutorial suggested, mainly because I got confused a bit why they were doing it that way, the length check and etc. Which is why I was asking for your email activation video.

            Yeah that’s what I am working on for the last 2 months. I learned (the basics, I am still at the basic level – a noob) on and off those 2 months from absolutely from zero on JS and PHP between your videos, few others,, and

            I stated on the site 5 months back, didn’t know what CSS was πŸ˜€ – before that last I did little bit of web design was 10 years back. Much has developed since then. So when I started on this site, I didn’t realize what WordPress, Joomla or Drupal for. So I avoided it and also I wanted to learn the basics first.

            I am sorry I think I said more than you wanted to know. I am going to stop here… ha ha..

            Thank you again for your time.

            Newbie out!

            • Derek Banas says:

              All of that hard work will definitely be worth it in the future. Since you brought up WordPress have you considered building the whole site inside of WordPress? If you know PHP, JavaScript, HTML and CSS you’ll be able to do most anything with WP.

              All of the security is already done for you. It is extremely easy to build a multiuser system with WP. I have a ton of WP tutorials. Zend is really kind of overkill for the type of site that I think you are trying to build.

              Tell me if you have any questions. I’ll do my best to help πŸ™‚


  1. Tweets that mention PHP Security | New Think Tank -- - [...] This post was mentioned on Twitter by Sam Hunt, Daniel Taylor. Daniel Taylor said: PHP Security [...]

Leave a Reply

Your email address will not be published.