In this video tutorial I’ll teach pretty much the whole PHP programming language in one video. I have received this tutorial request many times lately so I hope you enjoy it. The cheat sheet can be found below the video.
I cover quotes, comments, date(), variables, data types, getting data from HTML, heredoc, constants, arithmetic, shortcuts, reference operators, comparison operators, if, elseif, else, echo, printf, ternary operator, switch, while, for, foreach, arrays, strings, and much more. Continue reading PHP Programming→
In this tutorial I finish the PHP Forum. If you missed the first part it is here PHP Forum Part 1.
This forum isn’t just built in PHP however. It also uses MySQL, JavaScript and JQuery. Watching this tutorial is a great way to see if you understand how to program more complicated sites.
In part 4 of my PHP Message Board tutorial I show you how to create an account activation script.
In the previous video PHP Message Board pt 3, I created a user registration script. As an added security measure it sent an email with a link to this activation script. The new user will only be able to login if they click on that link.
At that point we check that the userid and 32 character key are the same. If they are we activate the account.
In the last part of this tutorial PHP Message Board Part 2 I set up the database access file, some security stuff and a user registration page. In this part of my message board tutorial I finish off the user registration page.
In this tutorial I’ll show you how to do the following:
A few articles ago I started creating a PHP Message Board, but then I got side tracked. Here is the original video PHP Message Board. You must watch it before you watch this one.
In this video tutorial I’ll start explaining how to create a new user registration system for the message board. You can also use this as a review of all I taught on PHP, MySQL, CSS, HTML, JavaScript and JQuery. If you click on those links you can see all of my tutorials on those subjects as well.
I show you how to create a PHP / MySQL message board in this video tutorial. I start by showing you how to properly set up the database. this can be looked at as a review on how to write SQL as well.
In todays Programming tutorial I show you how to grab information from a website using Regular Expressions in PHP. The information was particularly hard to get for the following reasons:
It was plain text
There were no tags to search for
Data I wanted was laid out in an unorganized way
I had to search for odd unicode characters like ½
I did it though using Regular Expressions and I’ll show you how.
In this web design and programming video tutorial I’ll show you how to make a secure forgotten password script. These scripts are attacked more than mosts and normally are full of security flaws.
I specifically cover how to:
Strip dangerous code from user input using Regular Expressions
Enforce secure security questions
Avoid brute force attacks with CAPTCHA systems
Create secure encrypted temporary passwords
Mail new passwords
All of the code used will follow the video. If you have any questions or comments leave them below.
If you have a recommendation for a future tutorial leave that below as well 🙂
Code From the Video
<?php
session_start();
require_once(“./includes/confighamdb.php”);
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
$query = “SELECT secques, email, userid FROM users WHERE userid=’$u'”;
$result = mysql_query ($query) or trigger_error(“Security Answer was Wrong”);
if (mysql_affected_rows() == 1) {
$row = mysql_fetch_array ($result, MYSQL_NUM);
mysql_free_result($result);
if($sq == $row[0])
{
$email = $row[1];
$p = substr ( md5(uniqid(rand(),1)), 3, 10);
$query2 = “UPDATE users SET pass=SHA(‘$p’) WHERE userid=’$u'”;
$result2 = mysql_query ($query2) or trigger_error(“Your Password Couldn’t be changed. Try later.”);
if (mysql_affected_rows() == 1) { // If it ran OK.
$body = “Your password has been temporarily changed to ‘$p’. Please log in using this password and your username. At that time you may change your password to something more familiar.”;
mail ($email, ‘Your temporary password.’, $body, ‘From: admin@sitename.com’);
echo ‘<h3>Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the “Change Password” link.</h3>’;
mysql_close();
exit();
}
else {
echo “Security Answer was Wrong”;
mysql_close();
exit();
}
} else { // If it did not run OK.
echo ‘<p><font color=”red” size=”+1″>Your password could not be changed due to a system error. We apologize for any inconvenience.</font></p>’;
In this video tutorial I create an extremely secure PHP Login Script. If you didn’t watch part 20 of this tutorial, you should check it out to find out how to use PHP Sessions and Cookies.
To make this login secure I added all of the following security features:
Keep all user information stored on the server with Sessions
Run all input through very strict Regular Expressions
Regenerate a new session token every time the user updates sensitive information
I add a few additional tricks along the way. All of the code follows the video. If you have any ideas on how I could improve this script pass them along.
Code From the Video
Goodlogin.php Script
<?php
// Initialize a session.
session_start();
require_once(“./includes/confighamdb.php”);
?>
<?php
if (isset($_POST[‘submitted’])) { // Check if the form has been submitted.
if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘userid’])))) {
$u = escape_data($_POST[‘userid’]);
} else {
$u = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid User ID!</font></p>’;
}
// FIX IT Check for a good password
if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘pass’])))) {
$p = escape_data($_POST[‘pass’]);
} else {
$p = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid Password!</font></p>’;
}
// FIX IT PHP Code for the CAPTCHA System
$captchchk = 1;
require_once(‘./includes/recaptchalib.php’);
$privatekey = “privatekey”;
$resp = recaptcha_check_answer ($privatekey,
$_SERVER[“REMOTE_ADDR”],
$_POST[“recaptcha_challenge_field”],
$_POST[“recaptcha_response_field”]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
In part 6 of my PHP Security video tutorial I cover a ton of ways hackers attack and how to hold them off. If you missed previous tutorials please watch them first. Here is the first one PHP Security.
In this specific tutorial I will cover:
How Spammers take over Comment Boxes
The Dangers of Providing Access to your Insert, Delete and Update SQL Querys
How Hackers use include and require to attack your site
The Damage that can be Done by Directory Traversal
A few months ago a friend asked me to take a look at their website because they had been receiving an immense amount of spam. Worse yet they were also receiving threats from others to stop sending spam to them. I immediately knew they were being targeted by code injection, but as I dug around I found more danger than I was expecting.
It seems that their grandchild (No doubt a future Mark Zuckerberg) had created the shopping cart for them. The shopping cart application had little to know security. In seconds I was able to dump all of their customers credit card information on to the screen before their frightened eyes.
In this part of the Web Design and Programming Tutorial I will review how to use 3 global storage arrays available in PHP. Specifically in this video I’ll show you how to use:
Cookies: A storage array that you save on the clients computer. You access it by referring to $_COOKIE
Sessions: A storage array that you save on the server. It is accessed by referring to $_SESSION
Server Global: An array that contains info on your server and the client machine. You access it by referring to $_SERVER
In this PHP Security Video tutorial I continue to show you how hackers break into web applications and how to better secure your site. If you missed part 1 of this tutorial definitely watch it first here PHP Security.
Specifically in this tutorial I will show you how SQL Injection works. Don’t do this on any site that you don’t own! I then go over all of the following:
Limit What Hackers can Enter in your Input Fields
Create Encrypted Activation Codes
Validate Input Data
Verify Email Addresses
How to Act Abnormally and Confound Hackers
All of the code follows the video. If you have any other questions or comments leave them below. Feel free to use the code however you like, but I’m not stating that it is 100% secure. The fact is all code can eventually be cracked. The goal is to make the code so complicated that hackers just give up and move on to an easier target.
Code From the Video
Register.PHP Code
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
if (isset($_POST[‘submitted’])) { // Handle the form.
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(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{6,}\z%’, 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>’;
}
if ($fn && $ln && $e && $p && $fn && $s && $c && $st && $z && $ph) {
$query = “SELECT user_id FROM users WHERE email=’$e'”;
$result = mysql_query($query) or trigger_error(“Sorry email is taken”);
echo ‘<br /><br /><h1>Thank you for registering! A confirmation email has been sent to your address. Please click on the link in that email in order to activate your account.</h1>’;
exit();
} else {
echo ‘<p><font color=”red” size=”+1″>You could not be registered due to a system error. We apologize for any inconvenience.</font></p>’;
}
} else {
echo ‘<p><font color=”red” size=”+1″>That email address has already been registered. If you have forgotten your password, use the link to have your password sent to you.</font></p>’;
<p><b>State:</b> <input type=”text” name=”state” size=”2″ maxlength=”2″ value=”<?php if (isset($_POST[‘state’])) echo $_POST[‘state’]; ?>” /> <small>Use only the two letter initials</small></p>
<p><b>Password:</b> <input type=”password” name=”password1″ size=”20″ maxlength=”20″ /> <small>Use only letters and numbers. Must be between 4 and 20 characters long.</small></p>
<?php
// Define these as constants so that they can’t be changed
DEFINE (‘DBUSER’, ‘mysqladm’);
DEFINE (‘DBPW’, ‘password’);
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.
// Handle the error.
trigger_error(“Could not select the database!<br />MySQL Error: ” . mysql_error());
exit();
} // End of mysql_select_db IF.
} else {
// Print a message to the user, and kill the script.
trigger_error(“Could not connect to MySQL!<br />MySQL Error: ” . mysql_error());
exit();
}
// A function that strips harmful data.
function escape_data ($data) {
// Check for mysql_real_escape_string() support.
// This function escapes characters that could be used for sql injection
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);
}
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:
Hide your database access files
How to eliminate code injection with regular expressions
Introduce a bunch of PHP functions that will delete harmful code
In this web design and programming video tutorial I will review a lot of what you have been taught previously. I’ll review many topics by showing you how to make drop down boxes that are populated from data stored in a database. If you don’t completely understand everything don’t worry about it. That’s why it is a review.
All of the code from the video follows the video. I included additional comments in the code that you can better understand what is going on. You also should print out the code and refer to it as you watch the video for better comprehension.
// This function is called to reload the page and pass the values chosen by the user
function reload(form)
{
// Get the value of the dropdown named cat
var val=form.cat.options[form.cat.options.selectedIndex].value;
// Loads the new page with the stored variable values
self.location=’hamtest.php?cat=’ + val ;
}
function reload2(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val2=form.subcat.options[form.subcat.options.selectedIndex].value;
self.location=’hamtest.php?cat=’ + val + ‘&cat3=’ + val2 ;
}
</script>
</head>
<body>
<?php
// Getting the data from Mysql table for first list box
$quer1=mysql_query(“SELECT DISTINCT Prod_Type,PT_ID FROM Product_ID
WHERE PT_ID IN (0,1,2,3,4,7,8,14,15,16,31,32,33,34,35,36,37) order by PT_ID”);
// For second drop down list we will check if category is selected else we will display all the subcategory
$cat=@$_GET[‘cat’]; // This line is added to take care if your global variable is off
if(isset($cat) and strlen($cat) > 0){
$quer=mysql_query(“SELECT DISTINCT Manufacturer_ID.Manufacturer,Manufacturer_ID.Man_ID FROM Manufacturer_ID, Model_Numbers
where ((Manufacturer_ID.Man_ID = Model_Numbers.Man_ID) AND (Model_Numbers.PT_ID = $cat)) order by Manufacturer”);
}else{$quer=mysql_query(“SELECT DISTINCT Manufacturer,Man_ID FROM Manufacturer_ID order by Manufacturer”); }
// end of query for second subcategory drop down list box
// For Third drop down list we will check if sub category is selected else we will display all the subcategory3
$cat3=@$_GET[‘cat3’]; // This line is added to take care if your global variable is off
if(isset($cat3) and strlen($cat3) > 0){
$quer2=mysql_query(“SELECT DISTINCT Model_Num, Model_Num FROM Model_Numbers where ((Model_Numbers.Man_ID=$cat3) AND (Model_Numbers.PT_ID = $cat)) order by Model_Num”);
}else{$quer2=mysql_query(“SELECT DISTINCT Model_Num, Model_Num FROM Model_Numbers order by Model_Num”); }
// End of query for third subcategory drop down list box