An Ongoing PHP & MySQL Tutorial Thread by JD Walker

LESSON #1: A Registration Form (cont.)

isset() and empty()

Both are language constructs. isset checks to see if a Variable exists. It will return true as long as the value is not NULL or FALSE.

empty() will return false if the variable doesn't contain any values.

All these will return as "empty"
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)

You will see me use these quite a bit as I continue this tutorial.
 
Please keep it coming JD - I have always been more of an infrastructure guy, but I am following along and always enjoy opportunities to add to the "toolkit".

:yes:
 
LESSON #1: A Registration Form (cont.)

Conditionals

The php manual for conditional constructs: http://php.net/manual/en/control-structures.if.php

if (perform action if condition is true)
PHP:
if(isset($_POST['registration']))
{
   //process form
}

if/else (perform action until condition is false)

PHP:
if(isset($_POST['registration']))
{
   //process form
}
else
{
  //business as usual
}

if/elseif (perform action if condition is true)
PHP:
if(isset($_POST['registration']))
{
   //process form
}
elseif(!empty($_POST['registration']))
{
  //process form
}
elseif(isset($_POST))
{
  //do more stuff
}

switch (perform action if condition is true, more efficient than if/elseif in this regard)

PHP:
switch ($_GET['food']) {
    case 'apple':
        echo $_GET['food'], ' is apple';
        break;
    case 'bar':
        echo $_GET['food'], ' is sandwich';
        break;
    case 'cake':
        echo $_GET['food'], ' is cake';
        break;
}

Ternary operator (checks to see if only one condition is true, similar to if/else)

PHP:
//$variable = 'true' ? 'yes' : no;

echo $_GET['food'] = 'apple' ? 'apple' : 'no';

I use if/else if/elseif most of the time, but I will use switch for code blocks.
 
LESSON #1: A Registration Form (cont.)

Now back to your registration form. In the Process.php I arbitrarily placed our debugger line in the file. I only want that to show up after the submission button is pressed. In order to do that, I will make a conditional statement telling it to print the array only if the $_POST['registration'] variable exists...

PHP:
if(isset($_POST['registration']))
{
   echo '<pre>', print_r($_POST), '</pre>';
}
 
LESSON #1: A Registration Form (cont.)

Comments
It's good practice to leave comments on lines/blocks of code. That way you will have an easier time keeping track of your code and so will others. Add 2 forward slashes to comment a line of code or ad a forward slash-asterisks asterisks-forward slash to comment a block of code.

PHP:
if(isset($_POST['registration']))
{
   /* We use the line below for debugging.
   we can always add to forward slashes to
   the bebugging line to deactivate it */

   echo '<pre>', print_r($_POST), '</pre>';

   //What comes next is Form Validation
}

When you comment a line it's deactivated or inert, meaning PHP will skip right over it while processing your active code
 
LESSON #1: A Registration Form (cont.)

Cleaning and Validating Data

Now we are about to see how a basic form can potentiall cause a lot of trouble.

Why clean and validate?
We need to make sure that data entered from the client does not in any form or fashion compromise the server, PERIOD.

NEVER EVER EEEEEEEVEEER RELY ONLY ON CLIENT SIDE LANGUAGES TO VALIDATE A FORM.​

Client side languages:
Actionscript (Flash)
Javascript.

Why not rely on them?
Both can be turned off with a click of the mouse in your browser preferences. Server side scripting cannot.

What type of attacks are we trying to prevent?
The attacks of choice these days are XSS (Cross Site Scripting Attacks) and SQL Injections. Using client side scripting to prevent these attacks would be the equivalent of not locking the car doors of your brand new 7-Series Beemer in Detroit.

We also want to make sure that the user themselves don't make mistakes in entering their information. We want to make sure that the username entered doesn't have any extra spaces, no malicious characters, and we want to make sure that the email is entered in email format.
 
LESSON #1: A Registration Form (cont.)

Functions

Remember seeing this f(x) = x² + 1 in your trig/precal classes, then asking yourself "Awwww nigga, what do I need this shit for, I'm never gonna use this shit nigga..."

Well guess what? :lol:

Functions in a computational form have a slightly different meaning. They will probably make more sense that the abstract math you learned in high school, for these functions actually do something.

PHP comes with 700 premade functions. You have already seen me use one of them...

PHP:
print_r();

to return an array for debugging. You will also see me create our own functions from this point on to accommodate out needs. Functions can also be called algorithms in this context.
 
LESSON #1: A Registration Form (cont.)

Back to our form. One rule you should adhere to is never assume anything.

Back to Security...
I highly reccomend reading this here: http://phpsec.org/projects/guide/2.html

I won't delve in to register globals because they are turned off by default in PHP. My advice to you, NEVER TURN THEM ON.

What we will do first is start filtering out input.

Here we assume that Quaid is going to enter his name correctly...

reg3.png


But what if he decides to do the following:
q1.gif


Of course we don't want space in usernames. We can run in to trouble down the road. So how do we remove excessive white space?

Registered Expressions

Better known as "regex". Regex is found in most pregramming languages. Regex identifies patters in text/code YOU define. I'm going to use PHP's built in function "preg_replace" to identify and remove excessive white space

PHP:
if(isset($_POST['register']))
{
	$_POST['name'] = preg_replace('[\s\s+]', '', $_POST['name']); //Removes excess white space
	
	echo '<pre>', print_r($_POST), '</pre>';
}


Now let's take a look at our array:
q2.gif


Now, no matter how much white space Quaid decides to add to his username our regex will remove it.

But now that we think about it, we don't want excess white space in any of our fields, so let's do the following:
PHP:
if(isset($_POST['register']))
{
	$_POST['name'] = preg_replace('[\s\s+]', '', $_POST['name']);
	$_POST['email'] = preg_replace('[\s\s+]', '', $_POST['email']);
	$_POST['password'] = preg_replace('[\s\s+]', '', $_POST['password']);
	
	echo '<pre>', print_r($_POST), '</pre>';
}
 
Props for this thread.

Although I am not a programmer, I had a few classes during my path to becoming an electrical engineer (controls) and it is NOT easy!!! I have the utmost respect for people who are fluent in these languages.
 
LESSON #1: A Registration Form (cont.)

So now Quaid is getting out of pocket by trying to run scripts in the name field...

q3.gif


q4.gif

As you can see this can cause problems, especially if received on the administration side.

What we don't want:
We don't want ANY tags whatsoever.
We don't want anything between those tags
We don't want any quotes
We want to MAKE SURE that the above doesn't happen


As you can see, I modified our Process.php script a bit...

PHP:
//The Pattern
$pattern[] = '[\s\s+]'; //No excess white space
$pattern[] = '[<(.*?)>(.*?)</(.*?)>]'; //Remove tags and everything in between
$pattern[] = '[<(.*?)>]'; //Remove stray open tags
$pattern[] = '[</(.*?)>]'; //Remove stray closing tags

	$_POST['name'] = preg_replace($pattern, '', $_POST['name']);
	$_POST['email'] = preg_replace($pattern, '', $_POST['email']);
	$_POST['password'] = preg_replace($pattern, '', $_POST['password']);
	
	
	echo '<pre>', print_r($_POST), '</pre>';

preg_replace also accepts arrays. So anytime we come up with something we don't want, we can add a pattern to the array. To fully cover our assets, if Quaid got past our regex, we'll create htmlentities out of the tags

PHP:
	$_POST['name'] = preg_replace($pattern, '', $_POST['name']);
	$_POST['name'] = htmlentities($_POST['name']);
	$_POST['email'] = preg_replace($pattern, '', $_POST['email']);
	$_POST['email'] = htmlentities($_POST['email']);
	$_POST['password'] = preg_replace($pattern, '', $_POST['password']);
	$_POST['password'] = htmlentities($_POST['password']);

What htmlentities function does
PHP:
$str = "A 'quote' is <b>bold</b>";
echo htmlentities($str); // Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;

htmlentities() creates the HTML entity of the tag, thereby rendering it inert.

Now we will cap off our cleansing with the mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] ) function.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

Allowing unescaped single quotes in to the MySQL database is a recipe for disaster. This is how SQL injections are perform. So lets apply mysql_real_escape_string() to our code...

PHP:
	$_POST['name'] = preg_replace($pattern, '', $_POST['name']);
	$_POST['name'] = mysql_real_escape_string($_POST['name']);
	$_POST['name'] = htmlentities($_POST['name']);
	$_POST['email'] = preg_replace($pattern, '', $_POST['email']);
	$_POST['email'] = mysql_real_escape_string($_POST['email']);
	$_POST['email'] = htmlentities($_POST['email']);
	$_POST['password'] = preg_replace($pattern, '', $_POST['password']);
	$_POST['password'] = mysql_real_escape_string($_POST['password']);
	$_POST['password'] = htmlentities($_POST['password']);

Now Quaid can't pull anymore shenanigans. He'll have no choice but to register in a civilized manner.

But we're not done.

Notice how our code is becoming a bit messy and illegible? We'll have to take a moment to optimize...
 
LESSON #1: A Registration Form (cont.)

Loops

The PHP loop manual: http://php.net/manual/en/control-structures.foreach.php

You will see me using "for" and "foreach" 90% of the time. I only use while for SQL queries.

You can use loops for various thing. For example, I can count to what ever number I wish without writing it out line by line...

PHP:
for($i = 1; 100 >= $i; $i++)
{
    echo 'The number is: ', $i;
}

The first part of the the for loop argument $i = 1 is setting the variable "$i" to the number 1. The next argument 100 >= $i is telling the loop to stop when it hits 100. The $i++ is telling the loop to iterate until it hits the number 100. the for loop is very flexible and can accommodate a number of arguments.

foreach is a looping function inherent to PHP and is used to loop through arrays.

PHP:
$arr = array('red', 'green', 'blue', 'yellow');

foreach($arr as $colors)
{
   echo $colors, ' ';
}

foreach will loop through the array and output the values of the array until it reaches the end.

The "for" equivalent would be

PHP:
$arr = array('red', 'green', 'blue', 'yellow');
$arr = count($arr);

for($i = 0; $arr >= $i; $i++)
{
   echo $arr[$i], ' ';
}

We are going to use loops to optimize the registration code we have so far...
 
LESSON #1: A Registration Form (cont.)

Let's check out our cleansed data...

PHP:
$pattern[] = '[\s\s+]'; //No excess white space
$pattern[] = '[<(.*?)>(.*?)</(.*?)>]'; //Remove tags and everything in between
$pattern[] = '[<(.*?)>]'; //Remove stray open tags
$pattern[] = '[</(.*?)>]'; //Remove stray closing tags

    $_POST['name'] = preg_replace($pattern, '', $_POST['name']);
    $_POST['name'] = htmlentities($_POST['name']);
    $_POST['email'] = preg_replace($pattern, '', $_POST['email']);
    $_POST['email'] = htmlentities($_POST['email']);
    $_POST['password'] = preg_replace($pattern, '', $_POST['password']);
    $_POST['password'] = htmlentities($_POST['password']);

Now it works. But it's ugly. What if I have to clean a long ass 60 field survey? Do you really want to copy and past each and every line? How about not.

Open up the Engine/Functions.php and copy and paste the following inside

PHP:
function clean_reg(&$array) {
	
	//Let's place our patterns in a neat array
	$pattern = array('[\s\s+]','[<(.*?)>(.*?)</(.*?)>]','[<(.*?)>]','[</(.*?)>]');
	
        foreach ($array as &$input){ //Let's loop through the post array
			if (!is_array($input)){ //if it's not an array, let's wash it... 
				$input = stripslashes($input);
				$input = preg_replace($pattern, '', $input);
				$input = mysql_real_escape_string($input);
				$input = htmlentities($input, ENT_QUOTES);
			}
			else { //if it is an array, for example a multidimensional array, let repeat the function to was deeper inside the $_POST array
			        clean_reg($input);
			}
        }
}

I came up with this while working on a project with a loooooong ass survey. This function will clean an array no matter how large it is. You can have a form with 1000 input fields and it will still clean it properly.

The "stripslashes()" function you see in the beginning is a precautionary measure. Just incase we upload this to a server that has "magic_quotes" turned on, we want to reverse the damage it does. magic_quots automatically adds slashes to POST data. Web hosts protect themselves this way just in case a rookie makes a mistake and forgets to manuall add slashes. But often time magic_quotes does more harm then good.

So what will our Process.php survey look like? Let's take a look at what it used to look like...

PHP:
if(isset($_POST['register']))
{
$pattern[] = '[\s\s+]'; //No excess white space
$pattern[] = '[<(.*?)>(.*?)</(.*?)>]'; //Remove tags and everything in between
$pattern[] = '[<(.*?)>]'; //Remove stray open tags
$pattern[] = '[</(.*?)>]'; //Remove stray closing tags

$_POST['name'] = preg_replace($pattern, '', $_POST['name']);
    $_POST['name'] = htmlentities($_POST['name']);
    $_POST['email'] = preg_replace($pattern, '', $_POST['email']);
    $_POST['email'] = htmlentities($_POST['email']);
    $_POST['password'] = preg_replace($pattern, '', $_POST['password']);
    $_POST['password'] = htmlentities($_POST['password']);  
    
    echo '<pre>', print_r($_POST), '</pre>'; 
}

Let's take a look at it now after we apply the function...

PHP:
if(isset($_POST['register']))
{
	clean_reg($_POST);
	
	echo '<pre>', print_r($_POST), '</pre>';
}

And that's it.

Quaid can't pull anymore fuckery...
q5.gif


We optimized out code so far, we're keeping file size down, we cleaned our input data in the registration form, and we're working SMART.

But we're still not done... 2bcont..
 
LESSON #1: A Registration Form (cont.)

Validation.

Now we must make sure all the fields are filled out properly before Quaid can finish his registration. We need to make a function that will generate an error message if a field is left empty, also we need to make sure the email address entered is formatted as a valid email address.

For starters, let's add the following line inside our "Settings.php"...

PHP:
   $errors = array();

^ This will be the error array. Any errors generated will be collected inside that array.

Second, in your Functions.php, copy and paste the following "warnings" function inside the file...

PHP:
function warnings($errors, $class = '')
{
	if(!empty($errors))
	{
		echo '<div class="' . $class . '">';
			foreach($errors as $error)
			{
				echo $error, '<br />';
			}
		echo '</div>';
	}
}

We have 2 arguments in the function. The first argument, the $errors argument is the array filled with errors. The second argument $class argument is option, that load the error style in to the function. The functions will loop through the array and display what fields Quaid needs to fill out if he misses any.

So what does our Process.php look like?
PHP:
if(isset($_POST['register']))
{
	clean_reg($_POST);
		
	$submit = $_POST; //Good security practice to copy the $_POST variable
	
	if(empty($submit['name'])){ // Checks if name field is empty
		$errors[] = 'Please enter your name.';
	}
        if(empty($submit['email'])){ //Checks is email field is empty
		$errors[] = 'Please enter your email address.';
	}
	if(!empty($submit['email'])){ //If the email field is not empty, let's make sure they have entered a legit email address
		if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $submit['email'])) { //We are using regex again to make sure the email address matches the given pattern
     			$errors[] = 'Please enter a valid email address';
		}
	}
	if(empty($submit['password'])){ //make sure the password field is not empty
		$errors[] = 'Please enter your password.';
	}
}

As you see I added conditions to check each field. The $_POST array was copied to the $submit variable for security and in the event we need to change the information in the array we won't have to touch the original.

Now let's add a little bit of style to our error message. In the style.css add the following class...

HTML:
.errors
{
	color: black; 
	text-align: center; 
	font-size: 2em; 
	width: 600px; 
	padding: 10px; 
	margin: 0 auto 20px auto; 
	border: 20px dashed red;
	-moz-border-radius: 70px;
	-webkit-border-radius: 70px; 
}

and let's not forget to add the function to the IndexTemplate.php...

PHP:
 <div id="copy">',
            warnings($errors, 'errors'), '
                <form method="post" action="">

Now let's see what it all looks like...
error.gif
 
LESSON #1: A Registration Form (cont.)

ever filled out a form, got an error message, and realized you had to enter your information all over again? That becomes a drag, and you can lose visitors that way. Let's see if we can fix that...

Session variables.

Session variable are special variables that will retain dynamically generated values as long as the the browsing session stays a live. Here's the manual on Session Variables: http://www.php.net/manual/en/session.examples.basic.php

Let's add a new file to the Engine folder. Let's call is "Sessions.php"

Let's add the following Session array to the file...

PHP:
<?php

	$_SESSION['register'] = array(
		'name' => (!empty($_POST['name']) ? $_POST['name'] : ''),
		'email' => (!empty($_POST['email']) ? $_POST['email'] : ''),
		'password' => (!empty($_POST['name']) ? $_POST['password'] : ''),
		);
		
?>

Next we'll add the following line to the tutorial/index.php file, under the settings line...
PHP:
include_once('Engine/Sessions.php');

Now, we have to modify our form a bit. We have to make sure that the Session variables CONTINUE to display the user's input after an error has occurred...

PHP:
<?php
echo'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link type="text/css" rel="stylesheet" href="', $theme['default']['style'], '" media="screen" />
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <title>PHP &amp; MySQL Tutorial</title>
    </head>
    <body>
        <div id="header">
            <div>BGOL <span>PHP &amp; MySQL Tutorial</span></div>
        </div>
        <div id="content">
            <div id="copy">',
            warnings($errors, 'errors'), '
                <form method="post" action="">
                    <fieldset><legend>Register</legend>
                        <label for="name">Name</label><input type="text" name="name" id="name" value="', (!empty($_SESSION['register']['name']) ? $_SESSION['register']['name'] : ''), '" />
                        <br />
                        <label for="email">Email</label><input type="text" name="email" id="email" value="', (!empty($_SESSION['register']['email']) ? $_SESSION['register']['email'] : ''), '" />
                        <br />
                        <label for="password">Password</label><input type="password" name="password" id="password" value="', (!empty($_SESSION['register']['password']) ? $_SESSION['register']['password'] : ''), '" />
                        <br /><br />
                        <input type="submit" name="register" value="Submit" />
                    </fieldset>
                </form>
            </div>
            <div style="clear: both;"></div>
        </div>
        <div id="footer">by <span>JD Walker<span></div>
    </body>
</html>';
?>

take note how I am using ternary operators inline with the HTML. The operators state that if the $_SESSION['register'] variable is not empty, display the post data to the user.

Let's see what it all looks like now...
error2.gif


Note how the information is no longer lost from the input fields if a mistake is made.
 
This is a seriously impressive thread. Props JD

and

It is also becoming more and more obvious that there are a slew of fraudulent ass clowns disseminating piss poor information about web development, such as writing half assed code, relying soley on GUIs and having you spend money on hacks from India. Janitor type niggas passing themselves off as web authorities. Vegas hookers workin' in Best Buy trying to get you hooked on GUIs. Black ass niggas who thinks building computers makes them experts on all things code.


:lol::lol::lol::lol::lol::lol::lol::lol::lol:
 
LESSON #1: A Registration Form (cont.)

We are almost ready to enter Quaid's information in the the database. But not quite. Do you see anything wrong here?

PHP:
Array
(
    [name] => Quaid
    [email] => quaid@bgol.com
    [password] => bgol2010
    [register] => Submit
)
1

We can't submit Quaid's password as is. It'll be a cinch to hack with a bruteforce attack. So let's encrypt it.

I use SHA US Secure Hash Algorithm Many still use MD5. MD5 can be decrypted, SHA cannot, which is why I use it.

Let's use PHP's hash function to encrypt (hash) Quaid's password:
PHP:
$submit['password'] = hash('sha512', $submit['password']);

I use sha512 encryption. It can't be decrypt, ONLY MATCHED. Let's take a look at what Quaid's newly hashed password looks like now...

PHP:
Array
(
    [name] => Quaid
    [email] => quaid@bgol.com
    [password] => 13861b1955e10ec0ea9ebfa5d665cf71679ce83bccce44d527fa39679eef0ca49f293d06cc07a458aaeeed9a445f18cb90b820eae5f7fa94adc51541862f6483
    [register] => Submit
)
1

So we're safe, right?

As a good practice it's always good to "salt" passwords/hashes. The salt shouldn't be accessible or stored in the same database as the user info. In the even a hacker is able to steal the database, he'll still need the salt, of better put "key" to decrypt user passwords. Salt can be crated in numerous ways. There are programmers on php.net on some NSA type shit posting their methods that I barely understand. For the sake of this tutorial, I'll keep it simple.

In the in our Settings.php, let's add the following line
PHP:
$salt = 'UnH@cK@b13';

now let's add the following line to the Process.php
PHP:
		$submit['password'] = $submit['password'] . $salt;
		$submit['password'] = hash('sha512', $submit['password']);

Now let's check out the hash.
PHP:
Array
(
    [name] => Quaid
    [email] => quaid@bgol.com
    [password] => fb6e12853f30af31fdb6b7f300013e808387db9e47c9d0162c30f38a4240dfea936054a49061e2d486e020c2f30a7be0ee67ffbad5451212be34abf7255abc69
    [register] => Submit
)
1

We're pretty safe now, although nothing it 100%.
 
LESSON #1: A Registration Form (CONCLUDED).

After looking at the Process.php I realized that I missed a check. We want to put a cap on how long usernames/emails/password can be. the strlen() function in PHP counts how namy characters are in a word and returns the value. I have the maximum value set at 20. Now while we can set a maxlength attribute in our template, it can be circumvented, and we dont' want that.

PHP:
	if(empty($submit['name']))
	{
		$errors[] = 'Please enter your name.';
	}
	if(!empty($submit['name']))
	{
		if(strlen($submit['name']) > $reg_len){
			$errors[] = 'Your username is too long.';
		}
	}
	if(empty($submit['email']))
	{
		$errors[] = 'Please enter your email address.';
	}
	if(!empty($submit['email']))
	{
		if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $submit['email'])) {
     			$errors[] = 'Please enter a valid email address';
		}
		if(strlen($submit['email']) > $reg_len){
			$errors[] = 'Your email is too long.';
		}
	}
	if(empty($submit['password']))
	{
		$errors[] = 'Please enter your password.';
	}
	if(!empty($submit['password']))
	{
		if(strlen($submit['password']) > $reg_len){
			$errors[] = 'Your password is too long.';
		}
	}

Now it's time to make that database drop. Let's create the table where our user information will be stored. In phpMyAdmin, you can create the table by copying and pasting the SQL dump in the SQL input box...

PHP:
CREATE TABLE  `test`.`site_users` (
`id` MEDIUMINT( 8 ) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 256 ) NOT NULL ,
`email` VARCHAR( 256 ) NOT NULL ,
`password` TEXT NOT NULL ,
`date` VARCHAR( 10 ) NOT NULL ,
PRIMARY KEY (  `id` )
) ENGINE = MYISAM ;

In our Settings.php, we need to make a connection with the database in order to query and insert data in to the database.

PHP:
//MySQL
$dbname = 'your_database_name';
$dbuser = 'your_database_username';
$dbpass = 'your_database_password';
$dbhost = '127.0.0.1'; //either 127.0.0.1 or localhost

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);

Now we only want to hash the passwords and insert the data if there are no errors.

Let's see what the Process.php looks like when everything comes together...
PHP:
if(isset($_POST['register']))
{
	clean_reg($_POST);
		
	$submit = $_POST;
	
	if(empty($submit['name']))
	{
		$errors[] = 'Please enter your name.';
	}
	if(!empty($submit['name']))
	{
		if(strlen($submit['name']) > $reg_len){
			$errors[] = 'Your username is too long.';
		}
	}
	if(empty($submit['email']))
	{
		$errors[] = 'Please enter your email address.';
	}
	if(!empty($submit['email']))
	{
		if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $submit['email'])) {
     			$errors[] = 'Please enter a valid email address';
		}
		if(strlen($submit['email']) > $reg_len){
			$errors[] = 'Your email is too long.';
		}
	}
	if(empty($submit['password']))
	{
		$errors[] = 'Please enter your password.';
	}
	if(!empty($submit['password']))
	{
		if(strlen($submit['password']) > $reg_len){
			$errors[] = 'Your password is too long.';
		}
	}
	if(empty($errors))
	{
		$submit['password'] = $submit['password'] . $salt;
		$submit['password'] = hash('sha512', $submit['password']);
		$submit['date'] = time();
		
                //This block submits the data in to the database using a combination of PHP and MySQL language...
		$query ="INSERT INTO `site_users` (`id`, `name`, `email`, `password`, `date`)
			VALUES ('', '{$submit['name']}', '{$submit['email']}', '{$submit['password']}', '{$submit['date']}');";
		$result = mysql_query($query) or die(mysql_error());
		
		$_SESSION['register'] = array(); //We'll clear the Session data since we don't need it anymore
		
		header('Location: ' . url . '/index.php?action=home'); //This generates a dynamic page after submission that takes to user to where ever you want them to go. This will be covered in a later tutorial. 
	}
}

And let's make sure the information was submitted in to the database...

registered.png


There you have it. A basic registration form. It can be improved upon by adding language files and using some AJAX to add some coolness but you get the basic idea. That concludes this lesson.
 
Lesson #2: iPad detection

Want to have special conent for iPad users?

Let's take a look at the iPad's user agent string...

Code:
Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

Now let's make a variable right quick that returns true when the iPad is detected...

PHP:
$iPad = preg_match('[ipad]', strtolower($_SERVER["HTTP_USER_AGENT"]));

Let's put it to use...

PHP:
if($iPad){
   //Display iPad stuff
}else{
   //Business as usual
}
 
Lesson #3: Gallery (pt 1)

A member PMed me last night needing a little advice on how to access directories for a gallery they are making. I have a basic algorithm that reads and returns the files in the directory, but I decided to incorporate elements of the recursive "clean" function that we made earlier to allow the function to thoroughly scan directories now matter how deep they are.

So let's get started. I want to make a Gallery with my soon to be baby's mama. I have almost all her pics, but we are just going to be using 3 sets for this tutorial.

What I want this function to do:
* To scan folders
* To return the folder names as titles
* To display the images in those folders using their parent folder name as a subject and title.


2bcont...
 
Lesson #3: Gallery (pt 1 cont.)

As you can see I made a gallery folder with the 3 folders of the pictures the woman who's ass I'd eat...

Gallery.png


Next, in the Settings.php, let's define the path to our gallery...

PHP:
define('gallery', '/path/to/your/tutorial/Gallery');
 
Lesson #3: Gallery (pt 1 cont.)

In the Engine folder we will make a "Gallery.php" file. Inside that file we will palce the following function...

PHP:
$path = gallery;

function folders($path)
{
	$forbidden = array('.', '..', '.DS_Store', '.htaccess', 'index.php'); //Let's make an array of things we don't want returned while looping through the folders
	$the_array = array(); //Now let's initialize the variable that will hold our folder values...
	
	if ($handle = opendir($path)){ //Let's open the main directory...
		while(false !== ($file = readdir($handle))){//Now let's loop through these folders...
	    	if (!in_array($file, $forbidden)){//Let's make sure the forbidden files aren't returned...  
				if(!is_dir("$path/$file")){//If it's not a directory, return the value in order to avoid duplicate values in the array...
	         		$the_array[] = $file;
	         	}
	         	if(is_dir("$path/$file")){//If it is an array, let's make a key out of it...
					$the_array[$file] = folders("$path/$file");//If there are more folders inside folders, let's display their contents by reusing the function 
				}
			}
		}
	}
	closedir($handle); //Let's close the folder
	return $the_array; //return the array to get ready for use...
}

$gallery = folders($path); //let's assign the "$gallery" variable to the function..


Now in the indexTemplat.php, let's add our debug line to make sure everything is working as it should be...

PHP:
     echo '<pre>', print_r($gallery), '</pre>';


Now let's look at the array of my woman...

tiaraArray2.png



Ok, so I forgot to add the pics, let me drag those in to the folders and see what's outputted after that...

tiaraArray.gif
 
CORRECTION: Regular Expressions

I'm guilty of butchering this term. A board member PMed me about the mistake. Earlier in this thread I called them "Registered Expressions", which is incorrect. For whatever reason I often transpose "regular" and "registered". I think subconsciously I', thinking about "registered globals".

So the correct term is "regular expressions" which I will address later on.
 
Lesson #3: Gallery (pt 1 cont.)

An array doesn't do Tiara any justice, we want to see her pics, so let's loop through the array and create some dynamic HTML to loop through the array BGOL style in the indexTemplate.php

PHP:
		    foreach($gallery as $folder => $files){//We want the folder names first to use as titles...
				echo'
					<div>
						<h1>', str_replace('_', ' ', $folder), '</h1>';
				
							$i = 0;
							foreach($files as $pix){//Now we loop through the images and use HTML to display them properly...
								$i++; //Let's set our counter...
								echo '<div style="float: left; border: 4px double black; margin: 7px;"><img src="', url, '/Gallery/', $folder, '/', $pix, '" alt="" width="200"/></div>';
								
								if($i == 4){//Since there are 12 images per folder, I want the loop to create a new row after every 4th image...
									echo '<br style="clear: both;" />';
									$i = 0; //reset the counter after 4 images are displayed per row
								}
							}
							
				echo '	<br style="clear: both;" />
					</div><br /><br />';
			}


"I no longer see the code, I just see blond, brunette, red head..." - Cipher

I see Tiara...

tiara.jpg
 
Lesson #4: Formatting Phone Numbers

Right now I am adding the finishing touches on one of my websites. I added a function to format my contact number in the database where it has no format, just a straight string of numbers like...

3214567890

Not all that easy to read. Let's use a function to format it...

PHP:
// $number is mandatory, the "$style" is optional
function phone($number, $style = '')
{ //If there's no style, or if the style is set to "1", let's use a default format
	if(empty($style) || $style === 1)
	{ //Let's make sure $number is set...
		if(isset($number))
		{//Let's count the length of the number character by character, and loop through it...
			for($i = 0; strlen($number) > $i; $i++)
			{
				echo $number[$i]; //Let's echo the number character by character...
				
				if($i === 2 || $i === 5){ //If the loop loops past the 3rd character of the area code (remember, the count starts at 0, not 1) and the 5th character (between the prefix and suffix) let's add a dash...
					echo '-';
				}
			}
		}
	}
	elseif($style === 2)
	{//If style 2 is selected...
		if(isset($number))
		{
			for($i = 0; strlen($number) > $i; $i++)
			{	
				if($i === 0){ //Let's open a Parenthesis at the beginning of the area code...
					echo '(';
				}
				if($i === 3){ //Let's close the parenthesis at the end of the area code...
					echo ') ';
				}
				if($i === 6){ //And let's add a dash between the dash between the prefix and suffix
					echo '-';
				}
				echo $number[$i];
			}
		}
	}
}

PHP:
   $myNumber = 3214567890;
   phone($myNumber); // Ouputs 321-456-7890
   phone($myNumber, 2); // Ouputs (321) 456-7890

That's MY phone number formatting function but there are a plethora of other phone number formatting functions that can be found online. I may take this tutorial a little further and show you how to convert standard numbers in to alphabet numbers like 1-800-328-7447 to 1-800-EAT-SHIT.
 
JD, I'm following little by little, but I have a question. I want to do a website where users can submit information, and it automatically gets posted to the website.

I've set the site up in Wordpress, but it lacks the customization that I want. Would PHP be a good route? Should I try to customize the Wordpress code, or build the site from the ground up?

Here are a few of the things that I want to have included in the site:
- decent interface
- user submissions
- email alerts
- easy way to edit / delete submissions
- submission printed directy to website and time stamped
- polling system, where reader can be vote on submission

Any info would help, I just need to know where to focus my efforts as far as building the site. I would prefer to be able to get it done quickly, using something like wordpress or joomla but if I have to learn to do it from scratch, i don't mind doing that.
 
JD, I'm following little by little, but I have a question. I want to do a website where users can submit information, and it automatically gets posted to the website.

I've set the site up in Wordpress, but it lacks the customization that I want. Would PHP be a good route?

Wordpress is written in PHP, as are 95% of all CMSs/Blogs.

Should I try to customize the Wordpress code, or build the site from the ground up?

Here are a few of the things that I want to have included in the site:
- decent interface
- user submissions
- email alerts
- easy way to edit / delete submissions
- submission printed directy to website and time stamped
- polling system, where reader can be vote on submission

Any info would help, I just need to know where to focus my efforts as far as building the site. I would prefer to be able to get it done quickly, using something like wordpress or joomla but if I have to learn to do it from scratch, i don't mind doing that.


I assume wordpress would have widgets for those features.

If you have a couple of months, you could create your own CMS (which isn't that hard) OR if you don't have the time CMSes like Joomla and Drupal would definitely get the job done. I often times use the Simplemachines forum integrated with Simple Portal for those tasks you listed.
 
Lesson #5: Browser Check

This one is easy. We'll simply use the $_SERVER super global to retrieve the client's browser information and build an array of browser to check for...

PHP:
//Let's start with IE since that browser causes the most problems
$browser= array(
	'ie' => preg_match('[msie]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'ie6' => preg_match('[msie 6.0]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'ie7' => preg_match('[msie 7.0]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'ie8' => preg_match('[msie 8.0]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'opera' => preg_match('[opera]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'safari' => preg_match('[safari]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'iphone' => preg_match('[iphone]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'ipod' => preg_match('[ipod]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'ipad' => preg_match('[ipad]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'firefox' => preg_match('[firefox]', strtolower($_SERVER["HTTP_USER_AGENT"])),
	'chrome' => preg_match('[chrome]', strtolower($_SERVER["HTTP_USER_AGENT"])),
);

if($browser['ie'])
{
  //apply ie fixes
}
 
Lesson #6: Generating dynamic pages with PHP

Let me cut to the chase. If you consider yourself a so called "web developer" with "years" of experience and you are still working with no template system and still making static pages or pages like the following:

HTML:
home.html
about.html
new.html
contact.html


Get the fuck off the internet.

Real talk. You are stuck in the 90s. Web Development without a proper template system and static pages is like living in the city with no electricity and running water.



Generating dynamic pages = Changing states
When a dynamic page is generated, the state of your site has changed. So you're not only changing the aesthetics, but you are sending commands to the database to retrieve information pertinent to that page call along with any other supplementary functions needed for that state.

Dynamic URL
What is a dynamic url? If contains information needed to change the state of the site and to generate a new page (in most cases).

A dynamic url can look like the following:

HTML:
http://yourwebsite.com/index.php?page=about

The part AFTER the question mark is called the QUERY STRING.

In this multi-part tutorial we're going to learn how to create and break down query strings to change the state of the site.


Superglobal: $_GET
$_GET. A very important Super Global variable. It does what its name implies. it GETS the contents of query strings, or better put, it gets the contents YOU want from the query string.

In this case, I want the "about" value of the "page" variable. We need to convert that url in to something we can work with. Let's use $_GET...

Now for the sake of this tutorial we are going to use a generic widely used conditional to break down our query string...
PHP:
if(isset($_GET['page'])){ //if the variable "page" exists in the query string...
	$page = $_GET['page']; //assign a variable to "page"
}else{
	$page = NULL; //if page doesn't exist in the query string, set it to null
}

Now later on you will see me complicate that conditional and even make a function out of it. Why? Remember at the beginning of the I said never to trust the content of super globals?

What if a clown decided to do alter the url and do the following:

PHP:
http://yourwebsite.com/index.php?page=about;DROP TABLE users;

^ That you do not want. I'll cover SQL Injections a little later.

2bcont...
 
Lesson #6: Generating dynamic pages with PHP (cont)

So not that we have our $page variable condition set, let's create a "switch" to switch from state to state, or "page to page".

I usually use the "if" condition, but for the sake of these tutorial, I will show you how the "switch" condition works, and it's probably more appropriate for generating dynamic pages.

The "switch" manual can be found here: http://php.net/manual/en/control-structures.switch.php

in our indexTemplate.php, we'll add the following...

PHP:
		switch($page)
		{
			case 'about':
				//Show About stuff
			break;
			
			case 'news':
				//Show News stuff
			break;
			
			case 'faq':
				//Show FAQ stuff
			break;
			
			case 'contact':
				//Show Contact stuff
			break;
		}

2bcont...
 
Back
Top