Category Archives: How to Code PHP

MySQL Video Tutorial

MySQL Video TutorialWelcome to my MySQL video tutorial. I’ll cover 95 – 98% of everything you’ll ever need to know in one video.

I cover creating / destroying databases, creating / destroying tables, data types, NULL, DEFAULT, ENUM, AUTO_INCREMENT, primary keys, foreign keys, atomic data, normalized, DESCRIBE, INSERT, ALTER, SELECT, SHOW, RENAME, WHERE, logical operators, comparison operators, ORDER BY, GROUP BY, LIMIT, string operators, joins, LIKE, DISTINCT, math functions and more. Continue reading MySQL Video Tutorial

PHP Programming

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

PHP Message Board Pt 5

PHP Message Board 5In part 5 of my PHP Message Board Tutorial, I show you how to create a proper login system.

This isn’t a simple system though. It is multi-layered and very secure. I specifically cover how to:

  • Secure against code injection and session hijacking
  • Change page elements based off of login status
  • Verify login status with cookies and sessions
  • Create a small compact captcha system
  • Search the database to verify identity and make changes to the data

And, a whole bunch more. All of the code follows the video like always.

This is a more advanced script and you may need help with the following topics:


Code From the Video

<?php

include(‘header.html’);

?>

<style>

#recaptcha_image img {

width: 185px;

height: 28.5px;

border: 1px solid gainsboro;

}

#recaptcha_widget {

height:400;

}

</style>

<script type=”text/javascript”>

// Changes the styling for the Captcha image

var RecaptchaOptions = {

theme : ‘custom’,

custom_theme_widget: ‘recaptcha_widget’

};

</script>

<?php

if (isset($_POST[‘submitted’])) { // Check if the form has been submitted.

// Security check for a valid username

if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘userid’])))) {

// Scrub username with function in header.php

$u = escape_data($_POST[‘userid’]);

} else {

$u = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid User ID!</font></p>’;

}

// Security check for a valid password

if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘pass’])))) {

// Scrub password with function in header.php

$p = escape_data($_POST[‘pass’]);

} else {

$p = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid Password!</font></p>’;

}

// PHP Code for the CAPTCHA System

$captchchk = 1;

$privatekey = “Public Key Here”;

$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

echo ‘<p><font color=”red” size=”+1″>The CAPTCHA Code wasn\’t entered correctly!</font></p>’;

$captchchk = 0;

}

// Query the database. Verify the username, password and captcha

if ($u && $p && $captchchk) {

$query = “SELECT user_id, first_name, last_name, email, username, passwd, active FROM users WHERE username=’$u’ AND passwd=SHA(‘$p’)”;

$result = mysql_query ($query) or trigger_error(“Either the Userid or Password are incorrect 1”);

if (mysql_affected_rows() == 1) { // A match was made

$row = mysql_fetch_array ($result, MYSQL_NUM);

mysql_free_result($result);

// If they haven’t activated the account redirect

if ($row[6] != NULL)

{

header(“Location: http://localhost/msgbrd/mbforgotpass.php”);

mysql_close(); // Close the database connection.

exit();

}

$_SESSION[‘first_name’] = $row[1];

$_SESSION[‘userid’] = $row[4];

// Create Second Token for security

$tokenId = rand(10000, 9999999);

$query2 = “update users set tokenid = $tokenId where username = ‘$_SESSION[userid]'”;

$result2 = mysql_query ($query2);

$_SESSION[‘token_id’] = $tokenId;

// Reset session id for security

session_regenerate_id();

// Redirect the user

header(“Location: http://localhost/msgbrd/mblogin.php”);

mysql_close(); // Close the database connection.

exit();

}

} else { // No match was made.

echo ‘<br><br><p><font color=”red” size=”+1″>Either the Userid or Password are incorrect 2</font></p>’;

mysql_close(); // Close the database connection

exit();

}

} // End of SUBMIT

?>

<body>

<div id=”header”><h2>Message Board</h2></div>

<div id=”login”>

<?php

echo ‘<h1>Welcome’;

if (isset($_SESSION[‘first_name’])) {

echo “, {$_SESSION[‘first_name’]}!”;

}

echo ‘</h1>’;

// Display links based upon the login status

// If user is on the logout page disable the login

if (isset($_SESSION[‘userid’]) AND (substr($_SERVER[‘PHP_SELF’], -10) != ‘logout.php’)) {

echo ‘<a href=”logout.php”>Logout</a><br />

<a href=”change_password.php”>Change Password</a><br />’;

} else { // Not logged in.

echo ”

<form action=’mblogin.php’ method=’post’>

<p><b>Userid:</b> <input type=’text’ name=’userid’ size=’20’ maxlength=’20’ /></p>

<p><b>Password:</b> <input type=’password’ name=’pass’ size=’16’ maxlength=’30’ /></p>”;

// Captcha stuff from Google

echo ”

<div id=’recaptcha_widget’ style=’display:none’>

<div id=’recaptcha_image’></div>

<div class=’recaptcha_only_if_incorrect_sol’ style=’color:red’>Incorrect please try again</div>

<span class=’recaptcha_only_if_image’>Enter the words above:</span><br />

<span class=’recaptcha_only_if_audio’>Enter the numbers you hear:</span>

<input type=’text’ id=’recaptcha_response_field’ name=’recaptcha_response_field’ />

<div><a href=’javascript:Recaptcha.reload()’>Get another CAPTCHA</a></div>

<div class=’recaptcha_only_if_image’><a href=’javascript:Recaptcha.switch_type(\’audio\’)’>Get an audio CAPTCHA</a></div>

<div class=’recaptcha_only_if_audio’><a href=’javascript:Recaptcha.switch_type(\’image\’)’>Get an image CAPTCHA</a></div>

<div><a href=’javascript:Recaptcha.showhelp()’>Help</a></div>

</div>

<script type=’text/javascript’

src=’http://www.google.com/recaptcha/api/challenge?k=Public Key Here’>

</script>

<noscript>

<iframe src=’http://www.google.com/recaptcha/api/noscript?k=Public Key Here’

height=’300′ width=’500′ frameborder=’0′></iframe><br>

<textarea name=’recaptcha_challenge_field’ rows=’3′ cols=’40’>

</textarea>

<input type=’hidden’ name=’recaptcha_response_field’

value=’manual_challenge’>

</noscript>

“;

echo “<div align=’left’><input type=’submit’ name=’submit’ value=’Login’ /></div>

<input type=’hidden’ name=’submitted’ value=’TRUE’ />

</form>”;

echo ‘<a href=”register.php”>Register</a><br />

<a href=”forgot_password.php”>Forgot Password</a><br />’;

}

?>

</div>

</body>

</html>

PHP Message Board Pt 3

PHP Message Board 3In 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:

  • Using Regular Expressions to Secure your Website
  • How to Perform Form Validation
  • Implement a Captcha System
  • Issue MySQL Common Queries
  • Generate Random Numbers
  • How to Generate a Email Verification System

Continue reading PHP Message Board Pt 3

PHP Message Board Pt 2

PHP Message BoardA 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.

Continue reading PHP Message Board Pt 2

PHP Message Board Pt 1

MySQL LogoI 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.

I specifically will review how to:

  • Create Databases
  • Create Tables and the Data Contained in them
  • Use the Insert Command
  • Use the Alter Command

Continue reading PHP Message Board Pt 1

Web Design and Programming Pt 24

Regex TutorialIn 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.

Continue reading Web Design and Programming Pt 24

Web Design and Programming Pt 23

PHP Forgot Password ScriptIn 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”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />
<title>Forgot My Password</title>
</head>
<body>
<div id=”main”>
<?php
if (isset($_POST[‘submitted’])) { // Handle the form.
// Check for a valid User ID
if (preg_match (‘%^[A-Za-z0-9]{8,20}$%’, stripslashes(trim($_POST[‘userid’])))) {
$u = escape_data($_POST[‘userid’]);
} else {
$u = FALSE;
echo ‘<p><font color=”red” size=”+1″>1Information Entered is Wrong</font></p>’;
}
// Check for valid Mother name
if (preg_match (‘%^[A-Za-z]{6,25}$%’, stripslashes(trim($_POST[‘mothername’])))) {
$sq = escape_data($_POST[‘mothername’]);
} else {
$sq = FALSE;
echo ‘<p><font color=”red” size=”+1″>2Information Entered is Wrong</font></p>’;
}
// 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
echo ‘<p><font color=”red” size=”+1″>The CAPTCHA Code wasn\’t entered correctly!</font></p>’;
$captchchk = 0;
}
if ($u && $sq && $captchchk) {
// Check the account information
$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>’;
mysql_close();
exit();
}
} else { // Failed the validation test.
echo ‘<p><font color=”red” size=”+1″>Please try again.</font></p>’;
mysql_close();
exit();
}
}} // End of the main Submit conditional.
?>
<h1>Reset Your Password</h1>
<p>Enter the Following Information Below and your Password will be Reset.</p>
<form action=”forgot_password.php” method=”post”>
<fieldset>
<p><b>Userid:</b> <input type=”text” name=”userid” size=”20″ maxlength=”20″/></p>
<p><b>Mothers or Grandmothers Maiden Name:</b> <input type=”text” name=”mothername” size=”25″ maxlength=”25″/></p>
<?php
require_once(‘./includes/recaptchalib.php’);
$publickey = “publickey”; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</fieldset>
<div align=”center”><input type=”submit” name=”submit” value=”Reset My Password” /></div>
<input type=”hidden” name=”submitted” value=”TRUE” />
</form>
</div>
</body>
</html>


PHP Security Pt 6 Directory Traversal

Directory TraversalIn 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
  • How to Stop Directory Traversal Attacks

Continue reading PHP Security Pt 6 Directory Traversal

PHP Security Pt 5 SQL Injection

SQL InjectionA 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.

Continue reading PHP Security Pt 5 SQL Injection

PHP Security Pt 4 Set Up Captcha

PHP Set Up CaptchaIn this video / article on PHP Security I will show you how to create more secure new user registration scripts. I’ll show you how to:

  • Fight off SQL Injection by thinking about your queries
  • Set up a CAPTCHA system that will protect you from brute force attacks
  • Lock down authentication hacks by forcing proper user ids and passwords

Continue reading PHP Security Pt 4 Set Up Captcha

Web Design and Programming Pt 20

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

Continue reading Web Design and Programming Pt 20

PHP Security Pt 2

PHP SecurityIn 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”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />

<title>Registration</title>

</head>

<body>

<div id=”main”>

<?php
require_once(“./includes/confighamdb.php”);

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

if(mysql_num_rows($result) == 0) {
$a = md5(uniqid(rand(), true));

$query = “INSERT INTO users(email, pass, first_name, last_name, active, registration_date, street, city, state, zip, work_phone) VALUES (‘$e’, SHA(‘$p’), ‘$fn’, ‘$ln’, ‘$a’, NOW(), ‘$s’, ‘$c’, ‘$st’, ‘$z’, ‘$ph’)”;

$result = mysql_query($query) or trigger_error(“Sorry an error happened”);

if(mysql_affected_rows() == 1) {

$body = “Thanks for registering. Activate account by clicking this link: <br />”;

$body .= “http://localhost/activate.php?x=” . mysql_insert_id() . “&y=$a”;

mail($e, ‘Registration Confirmation’, ‘$body’, ‘From: derekbanas@verizon.net’);

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

}

mysql_close();
}

?>

<h1>Register</h1>

<form action=”register.php” method=”post”>

<fieldset>

<p><b>First Name:</b> <input type=”text” name=”first_name” size=”15″ maxlength=”15″ value=”<?php if (isset($_POST[‘first_name’])) echo $_POST[‘first_name’]; ?>” /></p>

<p><b>Last Name:</b> <input type=”text” name=”last_name” size=”30″ maxlength=”30″ value=”<?php if (isset($_POST[‘last_name’])) echo $_POST[‘last_name’]; ?>” /></p>

<p><b>Email Address:</b> <input type=”text” name=”email” size=”40″ maxlength=”40″ value=”<?php if (isset($_POST[’email’])) echo $_POST[’email’]; ?>” /> </p>

<p><b>Street:</b> <input type=”text” name=”street” size=”40″ maxlength=”40″ value=”<?php if (isset($_POST[‘street’])) echo $_POST[‘street’]; ?>” /> </p>

<p><b>City:</b> <input type=”text” name=”city” size=”25″ maxlength=”25″ value=”<?php if (isset($_POST[‘city’])) echo $_POST[‘city’]; ?>” /> </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>Zip Code:</b> <input type=”text” name=”zip” size=”5″ maxlength=”5″ value=”<?php if (isset($_POST[‘zip’])) echo $_POST[‘zip’]; ?>” /> </p>

<p><b>Phone:</b> <input type=”text” name=”work_phone” size=”20″ maxlength=”20″ value=”<?php if (isset($_POST[‘work_phone’])) echo $_POST[‘work_phone’]; ?>” /> </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>

<p><b>Confirm Password:</b> <input type=”password” name=”password2″ size=”20″ maxlength=”20″ /></p>

</fieldset>

<div align=”center”><input type=”submit” name=”submit” value=”Register” /></div>

<input type=”hidden” name=”submitted” value=”TRUE” />

</form>

MySQL Connect Code

<?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);
}

// Return the escaped value.
return $data;

} // End of function.

?>

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

Continue reading PHP Security

Web Design and Programming Pt 19

Help Web Design and ProgrammingIn 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.

Here is a dump file for the database Database Dump File.

If you have any questions or comments leave them below, otherwise enjoy the video 🙂

Code From the Video

<?php
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.
// 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();
}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />
<title>Products</title>
<script language=JavaScript>
// 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
echo “<form method=post name=f1 action=’confirm.php’>”;
//  Starting of first drop downlist
echo “<select name=’cat’  onchange=\”reload(this.form)\”><option value=”>Select one</option>”;
while($results = mysql_fetch_array($quer1)) {  // Fetch a row of data based on a query
if($results[‘PT_ID’]==@$cat){echo “<option selected value=’$results[PT_ID]’>$results[Prod_Type]</option>”.”<br />”;}
else{echo  “<option value=’$results[PT_ID]’>$results[Prod_Type]</option>”;}
}
echo “</select>”.”<br />”;
//  Starting of second drop downlist
echo “<select name=’subcat’  onchange=\”reload2(this.form)\”><option value=”>Select one</option>”;
while($results2 = mysql_fetch_array($quer)) { // Fetch a row of data based on a query
if($results2[‘Man_ID’]==@$cat3){echo “<option selected value=’$results2[Man_ID]’>$results2[Manufacturer]</option>”.”<br />”;}
else{echo  “<option value=’$results2[Man_ID]’>$results2[Manufacturer]</option>”;}
}
echo “</select>”.”<br />”;
//  This will end the second drop down list
echo “<select name=’subcat3′ ><option value=”>Select one</option>”;
while($results3 = mysql_fetch_array($quer2)) {
echo  “<option value=’$results3[Model_Num]’>$results3[Model_Num]</option>”;
}
echo “</select>”.”<br />”;
?>
<input type=submit name=Submit value=Submit>
</form>
</body>
</html>

Web Design and Programming Pt 16

MySQL LogoIn this video tutorial I show you the many ways to insert information into MySQL. I specifically show you how to enter the information:

  • Directly through the MySQL shell
  • Through PHP code
  • From a CSV file

I then go into some other basic queries you need to understand to use MySQL. All of the code used follows the video.

Continue reading Web Design and Programming Pt 16