Webcodez at Squidoo

After being very busy for a while, I started writing more PHP tutorials again. However this time I chosen Squidoo to be the place to post them. Squidoo makes it so much fun to write tutorials and it even makes it possible to earn quite some money as well ( on long term ). Therefore I thought I’d post the links to the webcodez tutorials on squidoo here.

Webcodez at Squidoo

Tagged with: [ , , , ]

PHP Regular Expressions

This item was filled under [ PHP & MySql, References ]

Regular expressions can be used for matching or replacing certain patters inside a string. A simple example would be to check whether a certain word is inside a certain string and maybe on a certain position ( begin / end of string ). However also more complicated patterns can be made ( for example to verify whether a string is an URL address ).To do this, regular expressions can be used. Functions that make use of regular expressions in PHP are: preg_replace, preg_match and preg_match_all. These are the functions that will be used inside examples with regular expressions.

To match a regular expression pattern with a string, we may use the preg_match or preg_match_all function. The difference between these two functions is that preg_match stops searching for a match after one has occurred while preg_match_all continues to search for all matches. The preg_match function therefore is moreover used to check whether a pattern occurs inside a string, while the preg_match_all function is used to actually retrieve all matches with the pattern inside the string. So how do we set up a pattern? Therefore multiple symbols can be used. Here’s a table of the most common ones:

SymbolMeaning
^The word after this symbol should be at the beginning of the string to match.
$The word before this symbol should be at the end of the string to match.
*The expression before this symbol may occur any amount of times in the string to
match.
?The expression before this symbol may or may not occur once.
+The expression before this symbol should at least occur once.
{x}The expression before this symbol should occur x amount of times.
{x1,x1}The expression before this symbol should occur atleast x1 amount of times,
max x2 amount of times.
.Any character.
|Either the expression before or after this symbol should match.
ExpressionMeaning
bar$The string to match should contain the word ‘bar’ at the end of the string.
^foo(.*)bar$The string to match should contain the word ‘foo’ at the beginning of the
string AND the word ‘bar’ at the end of the string.
^[A-Za-z]*[0-9]*$The string to match should start with only letters and end with only numbers.
.* Any amount of any characters.
[A-Za-z]Any letter ( basicly: all the characters between the brackets are allowed).
[A-Za-z]*Any amount of letters ( but also: only letters ).
[A-Z]|[a-z]Either a capital or a non-capital letter.
^fooThe string to match should contain the word ‘foo’ at the beginning of the
string.

preg_match example


<?php
//preg_match([pattern], [string], [match], [flag], [offset])

$pattern = “/^[A-Za-z0-9_]*@[A-Za-z0-9_]*\.com$/”;
$str1       = “match_example@provider.com”;
$str2       = “no_match_example@provider.nl”;
$str3       = “no-match@[test.com”;
$str4      = “example_match123@456web.com”;

if(preg_match($pattern, $str1)) {
echo “$str1 matches.”;
}else{
echo “$str1 does not match.”;
}

if(preg_match($pattern, $str2)) {
echo “$str2 matches.”;
}else{
echo “$str2 does not match.”;
}

if(preg_match($pattern, $str3)) {
echo “$str3 matches.”;
}else{
echo “$str3 does not match.”;
}

if(preg_match($pattern, $str4)) {
echo “$str4 matches.”;
}else{
echo “$str4 does not match.”;
}
?>

preg_match_all example

<?php
//preg_match_all([pattern], [string], [matches], [flag], [offset])
$pattern = “match[0-9]”;
$str         = “this is match1 and this is match2”;
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches); //prints the array containing all matches found
}
?>

PHP Classes

This item was filled under [ PHP & MySql, References ]

Object Oriented Programming ( OOP ) is programming with use of classes and objects. A class consists of constants, variables and methods ( functions to alter the class’s properties ). An object can be created from a class and can be altered by calling the class’s functions.

Why would I use classes & objects?

You may be asking yourself: why would I use OOP? That question has one simple answer: for writing your codes fast, efficient and keeping them clear.

Creating a class

As mentioned before, a class consists of constants, variables and methods. There’s one default method which ‘creates the object’. It is automaticly executed when an object of the class is created. In other words: it can be used to ‘initialize’ the object ( its default properties e.g. ). This method is called the construction ( __construct ) method.

class ClassName {
	public function __construct( ... arguments ...  ) {

	}
}

What you may have noticed is that there’s the keyword ‘public’ before the function. This indicates that the function may be used/called from anywhere ( also from outside the class ). There are 3 types of keywords that indicate how a function may be accessed:

  • Public May be accessed from anywhere: inside the class, outside the class or from a
    parent  class
  • Protected May be accessed from inside the class OR from a parent class.
  • Private May be accessed ONLY from inside the class.

Alright, knowing that, let’s go back to the construction method. The construction method may or may not need certain information to create the object and its properties. These need to be given as arguments to the class ( or: to the construction method of the class ).

For example: for creating a Product object, we may need the id, name and price of the product.

class Product {
private static $id, $name, $price;
	public function __construct( $product_id, $product_name, $product_price ) {

	}
}

The construction method now asks for the id, name and price of the product upon creating an object of the class (a Product object).

Using &amp; Creating class variables and methods

To access variables and methods of the current class we use:
$this->variable_name or $this->function_name(… arguments …). In the example of the product class, we can now set the class variables equal to the ones given as arguments to the construction method:

class Product {
private static $id, $name, $price;
	public function __construct( $product_id, $product_name, $product_price ) {
		$this->id = $product_id;
		$this->name = $product_name;
		$this->price = $product_price;
	}
}

Now we can create any other functions for the class ourselves, just the same way as the construction method was formed. For example a function to ‘buy’ the product could be created:

class Product {
private static $id, $name, $price;
	public function __construct( $product_id, $product_name, $product_price ) {
		$this->id = $product_id;
		$this->name = $product_name;
		$this->price = $product_price;
	}

	public function buy() {
		echo “Successfully bought the product ‘”.$this->name.”’ for $”.$this->price.”!”;
	}

}

How to create an object of a class?

So far we know how to create a class, but not yet how to create an actual object of the class. It’s however not so hard to do. An object of a class is created using the keyword new followed by the name of the class and brackets which may contain arguments that are required for the class ( by the construction method of the class ). An object is usually created inside of a variable:

$myObject = new ClassName( … arguments … );

We’ll continue with the Product class we’ve been creating. The construction method requires 3 variables to be given values to: product_id, product_name and product_price. These need to be given values to when we want to create an object ( product ) of the class. We do this by giving them as arguments.

$product = new Product( 1, “Example Product”, 9.95 );

This will create an object of the class and set the variable id equal to 1, name equal to “Example Product” and price equal to 9.95. We’ve created a ‘product’! Now we may use any of the public variables and functions of the class. For example the buy function we made.

$product = new Product( 1, “Example Product”, 9.95 );
$product->buy();

This will output:

Successfully bought the product ‘Example Product’ for 9.95!

Note: the script of the class we created needs to be included in the script that creates the object of the class and needs to be put BEFORE it, so that the class is recognized when it’s created. Usually the code of a class definition is put in a separate file ( e.g. ClassName.class.php ) and then included into the file that uses the class. For example, assuming we put our class code inside the file Product.class.php:

<?php
include(“Product.class.php”);
$product = new Product( 1, “Example Product”, 9.95 );
$product->buy();
?>

Extending classes

Classes can also be extended. When this happens, we create a new class based on an earlier created class. The new (parent) class may use any methods and variables of the earlier created class ( the ‘main’ class ).

class MainClass {

}

class ParentClass extends MainClass {

}

For example:

<?php
class Product {
protected $id, $name, $price; //protected: can be accessed from parent class too
	public function __construct() { }

	public function buy() {
		echo “Successfully bought the product ‘”.$this->name.”’ for $”.$this->price.”!”;
	}
}

class Game extends Product {
protected $rank;
	public function __construct($game_id, $game_name, $game_price, $game_rank) {
		//may use any variables from the parent class (‘Product’)
		$this->id = $game_id;
		$this->name = $game_name;
		$this->price = $game_price;
		//may also create and use its own, new variables
		$this->rank = $game_rank;
	}
}

$test_game = new Game(1, “Test Game”, 19.95, 3);
//when creating an object of the Game class, the methods of the ‘main’ class may be used
$test_game->buy();
?>

PHP POST Variables

This item was filled under [ PHP & MySql, References ]

A POST Variable is a special kind of variable that is used for handling form data. POST variables are created when a (POST type) form is submitted. They will contain all values of the form fields. Although a form can send its data through the POST method or the GET method. When using the POST method, the values of the form fields are stored inside these POST variables. There will be created an array $_POST containing all data. Each form field has its own sub-variable to this array ($_POST[‘form_field_name’]). Take for example this form:

<form method=”POST” action=”<?=$_SERVER[‘PHP_SELF’];?>”>
<input type=’text’ name=’username’>
<input type=’password’ name=’password’>
<input type=’submit’ name=’submitBut’ value=’Login!’>
</form>

The above form has 3 fields. Two of them are text fields which can be given values to by the user. The other ‘field’ is a submit button ( which will automaticly be given the value ‘Login!’ in this example ). The method of the form is set to ‘POST’, which means: once the user presses the submit button, all form data is stored into the $_POST array and sent to the target page ( as set in the action parameter of the form tag ). In this example form the values of 3 fields will be stored inside the $_POST array like this:

$_POST[‘username’] = “ ... “;
$_POST[‘password’] = “ ... “;
$_POST[‘submit’]      = “Login!”;

Where would be replaced by the user filled in values.

How to check whether a form was submitted
We know that once a form is submitted the $_POST array is created containing all form data. Therefore we can just check whether the $_POST array is set to define whether the form was submitted.

<?php
if(isset($_POST) AND !empty($_POST)) { //if the $_POST array is set and not empty
	//... form was submitted ...
}else{
	//... form isn’t submitted yet ...
}
?>

Note: If multiple forms can be submitted at one page, you could identify the submitted form by checking
for example the POST variable for the submit button of that form.

Example of usage

<?php
if(isset($_POST) AND !empty($_POST)) { //if the $_POST array is set and not empty
	//... form was submitted ...
	// -> show filled in form values
	echo “<p><b>Username:</b> “.$_POST[‘username’].” </p>”;
	echo “<p><b>Password:</b> “.$_POST[‘password’].” </p>”;
}else{
	//... form isn’t submitted yet ...
	// -> show form
?>
	<form method=”POST” action=”<?=$_SERVER[‘PHP_SELF’];?>”>
	<input type=’text’ name=’username’>
	<input type=’tetx’ name=’password’>
	<input type=’submit’ name=’submitBut’ value=’Login!’>
	</form>
<?php
}
?>
Tagged with: [ , , , , ]

PHP GET Variables

This item was filled under [ PHP & MySql, References ]

A GET Variable is a special kind of variable that is created through the URL. They can be created by passing parameters via the URL. Take for example the following URL:

http://mywebsite.com/somefile.php?var1=value1&var2=value2&var3=value3

When accessing the URL as shown above, there will be created a total of three GET variables: var1, var2 and var3 with the values value1, value2 and value3. As you can see,  to add GET variables to the URL you need to put a question mark (?) after the filename. Then you can define any GET variables, separated by the AND mark (&).

All GET variables will be created inside an array $_GET. Accessing a file somefile.php through the above example URL, would create the following GET variables in code:

somefile.php(?var1=value1&var2=value2&var3=value3)

$_GET[‘var1’] = “value1”;
$_GET[‘var2’] = “value2”;
$_GET[‘var3’] = “value3”;

To print all GET variables, the print_r function may be used. This may make it even more clear to see what’s happening.

print_r($_GET); //prints the $_GET array on the screen
Tagged with: [ , , ]