Category Archives: Web Design

Design To Website, Blog How To Set Up, Google Update Pagerank, Google Crawl, Free Submit Site

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

Get More Views YouTube

zefrank how to vlogA while back I analyzed what all the superstars do to consistently get more views on YouTube. Here is that original article, along with a mashup of the greatest vlogger of all time ZeFrank How to Video Blog.

In this video tutorial I go over all that I learned about vlogging back then through today. I personally follow only a few of these tips for success and if you want to see more on what I do check out Become a YouTube Partner.

Whatever you do in your videos just understand that you will only be successful if you post a large number of videos. By doing so you will improve your ability to make good videos, but also you will increase the odds that you hit on a subject that nobody else does as well as you.

If you have any other questions or comments on YouTube or anything else leave them below.

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 18

MySQL StatementsIn this video tutorial I cover how to do numerous things with MySQL. I show you how to:

  • Join Data in Tables
  • Create Indexes
  • Delete Indexes
  • Change Column Data Types
  • Change Table Names
  • Create Full Text Indexes
  • Change Data in Columns
  • Perform Full Text Searches

And a bunch more…

All of the MySQL statements follow the video. If you have any questions or comments leave them below.

In the next tutorial I’ll be getting into how to use MySQL with PHP.

SQL Statements from the Video

select prod_type,pt_id from product_id;

describe manufacturer_id;
describe model_numbers;

describe manufacturer_id;describe model_numbers;

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 = 45)) order by Manufacturer;

use customer;

show tables;

describe customer;

alter table customer add index state_id (state_id);

describe customer;

alter table customer add index phone_id(phone_id);

drop index state_id on customer;

alter table customer add UNIQUE state_id(state_id);

drop index state_id on customer;

alter table customer add index state_id (state_id);

describe customer;

alter table customer add index order_id(order_id);

create index index_name on tbl_name(columnsToIndex);

alter table customer add column comments varchar(40);

describe customer;

alter table customer change column comments comments text;

describe customer;

alter table customer rename as newTableName;

alter table customer add fulltext index (comments);

show create table customer \G

select * from customer;

describe phone;

insert into phone values (NULL, ‘412-876-7878′,’Work’);

insert into customer values(‘Sally’,’Smith’,’234 Main St’,’Happy Town’,3,15234,SHA(‘Monkey2′),2,NULL,NULL,’Really nice lady who loves cats’);

update customer set comments=’Crazy man who has 2 cats named Peekaboo and Sophie’ where cust_id=1;

insert into customer values(‘Paul’,’Smith’,’234 Main St’,’Happy Town’,3,15234,SHA(‘pw1234′),2,NULL,NULL,’Sally Smiths husband he wants a dog’);

select first_name, comments from customer where match (comments) against (‘crazy’);

insert into customer values(‘Mark’,’Marks’,’194 South St’,’Happy Town’,3,15234,SHA(‘abc1234′),3,NULL,NULL,’Craziest man I ever met. Loves dogs’);

select first_name, last_name, comments from customer where match(comments) against(‘craz*’ in boolean mode);

select first_name, last_name, comments from customer where match(comments) against(‘+craz* -cat*’ in boolean mode);

YouTube Partner Benefits

YouTube RobotAll day I have been taking advantage of my new YouTube Partner Benefits. You have been sending me a bunch of questions on these benefits and in this article I will answer them.

The main question I have been getting is, “Can I become a YouTube Partner if I don’t live in the United States?”

The YouTube Partner Program is only available to users in Australia, Brazil, Canada, Germany, Spain, France, the United Kingdom, Ireland, Israel, Italy, Japan, Mexico, the Netherlands, and the United States.

I’ve also received questions on what benefits you actually receive as a YouTube Partner. Here is the list of what you can do:

Continue reading YouTube Partner Benefits

Become a YouTube Partner

YouTube LogoLast week I became a YouTube Partner and I received a bunch of requests on how I did it. SackettGraphics also asked me how I make my videos. I cover both of these topics in the video below.

I created a detailed formula on how to become successful vlogger in the article How to Video Blog. If you missed it? Almost everyone that is successful online copies from the first great vlogger named ZeFrank.

As per the software I use:

If you are on a PC, I recommend that you use the following free tools:

If you have any questions or comments leave them below.

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

WordPress Problems Solved Pt 3

Wordpress Problems SolvedPreviously I covered many of the WordPress problems you were having in WordPress How To and WordPress How To Pt 2. In this video I’ll answer a recent request from Dan to help him better:

  • Layout a WordPress Site
  • Make a SEO Friendly WordPress Site
  • How to Make a Static Site in WordPress
  • How to Link Pages through Images

And a bunch more…

Continue reading WordPress Problems Solved Pt 3

Web Design and Programming Pt 15

MySQL StatementsIn this video tutorial I explain how to create efficient tables using SQL. Specifically I’ll show you how to create Atomic Databases. A table is considered Atomic when it focuses on describing just one thing. Here is an article that goes more into this subject MySQL Atomic Tables.

Once you make all of your tables you should make sure they are Normalized. A Normalized Table is a table that follows the 3 Normalized table rules.

Continue reading Web Design and Programming Pt 15

Web Design and Programming Pt 14 MySQL

Go Daddy Grid HostingIncrease Website SpeedA while back I did a series of tutorials on MySQL. However, because you guys requested a more example heavy MySQL tutorial I’m now going to provide that.

If you want to check out the previous tutorial I have it in both text and video format here:

I especially am happy with the articles!

In this video, I go over the basics of using MySQL. For example: Creating Tables, Data Types, Entering Information, Deleting Tables and Basic MySQL commands.

If you have any questions or comments leave them below.

Web Design and Programming Pt 13

Help Web Design and ProgrammingIn this PHP video tutorial I’ll show you how to work with exception handling.

When an error occurs in your code this code is referred to as an exception. Meaning the code runs fine Except if the user of the code does certain things. When these Exceptions occur an error is thrown and handled by code that lies somewhere else in your code.

I specifically cover the following topics in the video:

Continue reading Web Design and Programming Pt 13

Web Design and Programming Pt 12

Web Design and ProgrammingIn this PHP video tutorial I’ll cover how to manipulate files with PHP. Specifically I cover the following:

  • Read file into an array
  • Read file into a string
  • Grab text off of web pages
  • Strip HTML tags
  • Write to files

Here is a link to the first article and video for this series, if you haven’t seen it Web Design and Programming.

All of the code follows the video. Use it in anyway. Leave any questions or comments below.

Code from the Video

<html>
<head>
<title><?php echo “Object Oriented Programming”;?></title>
</head>

<body>

<?php

# Creates a file descriptor and assigns it to $file
# The second attribute opens the file for read only purposes
# You can access any file online with this same function
# r+ – Read and Write from beginning of file
# w – Write only to beginning of file
# w+ – Delete contents and read and write to file
# a – Write only to the end of the file
# a+ – Read and Write to the end of the file
$file = fopen(“customers.txt”, “r”);

# While the end of file hasn’t been met print lines to screen
while (!feof($file))
{
# fgets() returns all the characters up to a newline or EOF
# You can also specify the number of characters to return in the 2nd attribute
echo fgets($file). “<br />”;
}

echo “<br />”;

# You can also read a file into an array
$customers = file(“customers.txt”);
foreach ($customers as $customer)
{
list($name,$street,$city,$state) = explode(“,”, $customer);
$state = trim($state);
echo “Name: ” . “$name <br />”;
echo “Street: ” . “$street <br />”;
echo “City: ” . “$city <br />”;
echo “State: ” . “$state <br /><br />”;
}

# Close the file
fclose($file);

$file4 = fopen(“customers.txt”, “a”);

$newCustomer = “\nRick,219 Almond St,Pittsburgh,PA”;
fwrite($file4, $newCustomer);

fclose($file4);

# You can also read a file into a string
$customers = file_get_contents(“customers.txt”);
$customers = explode(“\n”,$customers);

foreach ($customers as $customer)
{
list($name,$street,$city,$state) = explode(“,”, $customer);
$state = trim($state);
echo “Name: ” . “$name <br />”;
echo “Street: ” . “$street <br />”;
echo “City: ” . “$city <br />”;
echo “State: ” . “$state <br /><br />”;
}

$file2 = fopen(“http://www.wikileaks.ch/static/html/faq.html”, “rt”);

while (!feof($file2))
{
$faqs .= fgetss($file2, 1024);
}
fclose($file2);

$file3 = fopen(“justthefaqs.txt”, “wt”);
fwrite($file3, $faqs);

fclose($file3);

?>

</body>
</html>

Web Design and Programming Pt 11

Object Oriented ProgrammingHere I continue to explain Object Oriented Programming with PHP. If you missed the first part definitely watch that video tutorial first Object Oriented Programming with PHP.

Here I’ll cover the following topics:

  • Inheritance
  • Static Attributes (Variables)
  • The _destruct Function
  • The Final Keyword
  • Overriding Functions
  • And more…

If you have any questions, leave them below. All of the code follows the video.

All the Code from the Video

<html>
<head>
<title><?php echo “Object Oriented Programming”;?></title>
</head>

<body>

<?php

# Inheritance is done when you create a new class from another, thus borrowing the data
# and methods that can be found there.

class Animal
{
private $name; # Private variables are only accessed by class methods, but not subclasses
private $favFood = “meat”;

# A static attributes value is shared by all objects of the class
# You refer to static attribute like this self::$numOfAnimals, not with $this
public static $numOfAnimals = 0;

# Constructor and Deconstructor
public function __construct($name=”No Name”)
{
echo “__construct was called”. “<br />”;
$this->setName($name);
self::$numOfAnimals++;
}

public function __destruct()
{
echo “__destruct was called”. “<br />”;
}

# Get and Set Methods – final is used to keep methods from being overwritten
final public function getName()
{
return $this->name;
}

final public function setName($sentName)
{
$this->age = $sentName;
}

# Animal Default Functions
public function makeNoise()
{
echo “Grrrr”. “<br />”;
}
public function favFood()
{
echo “My favorite food is ” . $this->favFood . “<br />”;
}
public function move()
{
echo “Walk around”. “<br />”;
}

}

class Dog extends Animal
{
# If I didn’t create a new constructor the parent would be called
public function __construct($name=”No Name”)
{
parent::__construct($name); # How to call the parent constructor
# Animal::__construct($name); this would also call the parent constructor
}

public function __destruct()
{
echo “__destruct was called”. “<br />”;
}

# Dog Default Functions Overwrites Class Function
public function makeNoise()
{
Animal::makeNoise(); # How to call the original class method
echo “Bark, Bark”. “<br />”;
}
}

#function animalStuff(

$grover = new Dog(“Grover”); # Create an object grover of class Dog
$paul = new Dog(“Paul”);
$grover->makeNoise(); # Call the makeNoise() method for the grover object
$grover->favFood();
$grover->move();

echo Animal::$numOfAnimals. “<br />”; # Prints out the number of objects created

?>

</body>
</html>

Web Design and Programming Pt 10 OOP & PHP

Object Oriented ProgrammingIn this PHP video tutorial I cover Object Oriented Programming with PHP. I specifically go over the following topics:

  • Encapsulation
  • Classes
  • Objects
  • Public
  • Private
  • Constructors
  • Destructors
  • __set
  • __get
  • And more….

All of the code from the tutorial is available after the video. Use it in anyway that you like. I’ll continue covering OOP with PHP in the next video tutorial in this series.

If you have any questions leave them below.

All the Code from the Video

<html>
<head>
<title><?php echo “Object Oriented Programming”;?></title>
</head>

<body>

<?php
# Encapsulation lets you hide the code behind an interface so you can protect the code
# and so your user need not understand the code to use it

# A class is a blueprint you use to create objects

# Objects contain the data (attributes) and actions (methods) needed to perform its tasks

# Inheritance is done when you create a new class from another, thus borrowing the data
# and methods that can be found there.

# Polymorphism allows a class to perform differently based on how it is being used.
# Polymorphism can be used to a certain extent with PHP in that you can use common
# method and attribute names for similar classes

# Any use of this is a reference to a specific object and that objects attributes and methods

class Animal
{
public $name; # Public variables can be accessed directly by anyone
private $age; # Private variables are only accessed by class methods, but not subclasses
protected $money; # Protected is like private except can be accessed by inherited classes
const POUNDID = 12345; # A constants value can never change
# A static attributes value is shared by all objects of the class
# You refer to static attribute like this self::$numOfAnimals, not with $this
private static $numOfAnimals = 0;

public function __construct($age)
{
echo “__construct was called”. “<br />”;
$this->setAge($age);
}

public function __destruct()
{
echo “__destruct was called”. “<br />”;
}

# __set can be used to perform error checking before assigning values to private attribs
function __set($attribName, $attribValue)
{
echo “__set was called for “. $attribName. “<br />”;
$this->$attribName = $attribValue;
}

# __get can be used to perform error checking before returning values from private attribs
function __get($attribName)
{
echo “__get was called for “. $attribName. “<br />”;
return $this->$attribName;
}

public function getAge()
{
return $this->age;
}

public function setAge($sentAge)
{
$this->age = $sentAge;
}
}

$dog = new Animal(8); # Create an object dog of class Animal
$dog->name = “Grover”; # Assign a value to the public attribute name
$dogName = $dog->name; # Retreive value from public attribute name

$dog->setAge(8); # Call the setAge() method for the dog object

$dog->age = 9; # Try to set a private attribute that makes a call to __set
echo $dog->age. “<br />”; # Try to get a private attribute that makes a call to __get

echo “The dogs name is ” . $dogName . “<br />”;
echo “The dogs age is ” . $dog->getAge() . “<br />”;
echo “The pounds ID number is “. $dog::POUNDID. “<br />”;

?>

</body>
</html>

Web Design and Programming Pt 9 PHP Strings

StringsHere I show you how to use many string manipulation methods in PHP. Also, I finish showing you how to use regular expressions.

You should watch the previous 2 PHP Regular Expressions video tutorials before you continue on to this one. They are avaialable here PHP Regular Expressions & PHP Regular Expressions Pt 2

I specifically cover the following PHP Methods in this tutorial:

Web Design and Programming Pt 7 REGEX

Regex TutorialIn this video tutorial I will tackle Regular Expressions. People think Regular Expressions are too hard to use. And, while I have received many thank you’s for creating my last Regex Tutorial. Here I’m going to finish up where I left off.

Before you proceed you should most definitely take a look at those Web Design and Programming tutorials that came previous to this one. This tutorial starts with this article Web Design and Programming.

Continue reading Web Design and Programming Pt 7 REGEX

Web Design and Programming Pt 6

iPhone DevelopmentIn this part of the Web Design and Programming tutorial, I will show you how to do anything with PHP functions. Specifically I will cover:

  • How to Create Functions
  • How to work with Function Attributes (Variables)
  • How to Pass Multiple Attributes to and from Functions
  • What Does Scope Mean (Local vs. Global)
  • What is Recursion

Continue reading Web Design and Programming Pt 6