Further PHP try / catch PHP 5

A try / catch block is meant to catch exceptions.  An exception would be something like divide by zero which causes a program exception and this can be caught.

An error on the other hand is not usually recoverable.  An example of an error would be forgetting to place a ; at the end of a line or not enclosing a string with ” marks.

In the case of divide by zero, if you use a try / catch block, program execution will continue because you have caught the exception.

Each try must have at least one corresponding catch block.  You can have multiple catch blocks to catch different classes of exceptions.

When an exception is thrown, the code following the statement will not be executed and PHP will then attempt to find the first matching catch block.

The general form of a try / catch block is :

try
{
$a = 1;
$b = 0;
$c = $a / $b;
}
catch (Exception $e)
{
echo($e->getMessage());
}

Other functions of the exception class are :

getMessage();        // message of exception
getCode();           // code of exception
getFile();           // source filename
getLine();           // source line
getTrace();          // an array of the backtrace()
getPrevious();       // previous exception
getTraceAsString();  // formatted string of trace

You may extend the exception class to create your own custom exceptions and the use them as multiple catch blocks to catch different classes of exception as shown in the following code :

<?php

//Extending the exception class

class WidgetNotFoundException extends Exception {}

function use_widget($widget_name) {
$widget = find_widget($widget_name);

if (!$widget) {
throw new WidgetNotFoundException(t(‘Widget %widget not found.’, array(‘%widget’ => $widget_name)));
}
}

//The try / catch block

try {
$widget = ‘thingie’;
$result = use_widget($widget);

// Continue processing the $result.
// If an exception is thrown by use_widget(), this code never gets called.
}
catch (WidgetNotFoundException $e) {
// Error handling specific to the absence of a widget.
}
catch (Exception $e) {
// Generic exception handling if something else gets thrown.
watchdog(‘widget’, $e->getMessage(), WATCHDOG_ERROR);
}

?>

Simple PHP 5 error handling

<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception(“Value must be 1 or below”);
}
return true;
}

//trigger exception in a “try” block
try
{
checkNum(2);//If the exception is thrown, this text will not be shownecho ‘If you see this, the number is 1 or below’;}
//catch exception
catch(Exception $e)
{
echo ‘Message: ‘ .$e->getMessage();
}
?>

Examples of using PDO objects in PHP

<?php

//Example of fetching data from a database using PDO objects

# using the shortcut ->query() method here since there are no variable
# values in the select statement.

try {

$dbhost = “localhost”;
$dbname    = “users”;
$dbusername = “root”;
$dbpass = “”;

//Connect to the database
$dbh = new PDO(“mysql:host=” . $dbhost . “;dbname=” . $dbname, $dbusername, $dbpass);

//the sql query
$sql = “SELECT * FROM users”;

//statment handle
$sth = $dbh->query($sql);

# setting the fetch mode
$sth->setFetchMode(PDO::FETCH_ASSOC);

echo(“——————————————–<br/>”);
echo(“An example of a while loop<br/>”);
while($row = $sth->fetch()) {
echo( $row[“first_name”] . “<br/>” );
$table[] = $row;
}

$dbh = null;

}  catch (PDOException $e) {
print “Error!: ” . $e->getMessage() . “<br/>”;
die();
}

echo(“<br/><br/>”);

echo(“——————————————–<br/>”);
echo(“An example of looping around an array<br/>”);

if ($table) {    //Check if there are any rows to be displayed
//Retrieve each element of the array
foreach($table as $d_row) {
echo( $d_row[“first_name”] . ” ” . $d_row[“last_name”] . “<br/>” );
}
}

echo(“——————————————–<br/>”);
echo(“An example of printing one element from the array<br/>”);
echo($table[0][“first_name”]);

?>

<?php

//Example of fetching data from a database using PDO objects

//This uses a prepared statement using named values

try {

$dbhost = “localhost”;
$dbname    = “users”;
$dbusername = “root”;
$dbpass = “”;

$first_name = “%paul%”;

//Connect to the database
$dbh = new PDO(“mysql:host=” . $dbhost . “;dbname=” . $dbname, $dbusername, $dbpass);

//the sql query using a named placeholder
$sql = “SELECT * FROM users WHERE first_name LIKE :first_name “;

//statment handle
$sth = $dbh->prepare($sql);

$sth->execute(array(“:first_name” => $first_name));

$sth->setFetchMode(PDO::FETCH_ASSOC);

echo(“<br/><br/>”);
echo(“——————————————–<br/>”);
echo(“An example of printing values from a select statement with parameters<br/>”);

while($row = $sth->fetch()) {
echo( $row[“first_name”] . “<br/>” );
$table[] = $row;
}

$dbh = null;

}  catch (PDOException $e) {
print “Error!: ” . $e->getMessage() . “<br/>”;
die();
}

?>

Some regular expression matches

Regular Expression     Will match…

foo     The string “foo”
^foo     “foo” at the start of a string
foo$     “foo” at the end of a string
^foo$     “foo” when it is alone on a string
[abc]     a, b, or c
[a-z]     Any lowercase letter
[^A-Z]     Any character that is not a uppercase letter
(gif|jpg)     Matches either “gif” or “jpeg”
[a-z]+     One or more lowercase letters
[0-9\.\-]     ?ny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$     Any word of at least one letter, number or _
([wx])([yz])     wy, wz, xy, or xz
[^A-Za-z0-9]     Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})     Matches three letters or four numbers

Possible way of dealing with inserting quote marks into a database

This is another possible way of dealing with quote marks for inserting data into a database :

if (!get_magic_quotes_gpc()) {
$item_name = addslashes($_POST[‘txtItem_Name’]);
}
else
{
$item_name = $_POST[‘txtItem_Name’];
}

Dealing with quote marks for inserting data into a database
———————————————————–

if (!get_magic_quotes_gpc()) {
$item_name = addslashes($_POST[‘txtItem_Name’]);
}
else
{
$item_name = $_POST[‘txtItem_Name’];
}

Regular Expression Will match…

Regular Expression     Will match…

foo                                The string “foo”
^foo                            “foo” at the start of a string
foo$                            “foo” at the end of a string
^foo$                         “foo” when it is alone on a string
[abc]                           a, b, or c
[a-z]                           Any lowercase letter
[^A-Z]                      Any character that is not a uppercase letter
(gif|jpg)                   Matches either “gif” or “jpeg”
[a-z]+                       One or more lowercase letters
[0-9\.\-]                  any number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$      Any word of at least one letter, number or _
([wx])([yz])                    wy, wz, xy, or xz
[^A-Za-z0-9]                 Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})     Matches three letters or four numbers

Use regular expressions to validate PHP inputs

To help counter SQL injections you need to make sure that entered values use minimum character types as possible.  So you restrict usernames to just a-z and 0-9 characters.

To test for these, use something like :

//——————————————————
/**
* Purpose : Check input for paticular characters
* Only allow a – z, A – Z , 0-9
* returns true if a match was found, false if no match was found
* @return boolean
*/
function is_valid_input($words) {

if ( preg_match( “/[^0-9a-zA-Z]/”, $words, $array ) )
return false;        //invalid characters
else
return true;        //valid characters

}

How to create htaccess / htpasswd

Here is a simplified description on how to create an htaccess / htpasswd file :

To protect your admin area you can create an htaccess / htpasswd file.

(1) Create an .htaccess file

Go to http://www.htaccesstools.com/htaccess-authentication/

In the first box enter some optional text which gets displayed in the login box

In the second box you need to enter the file path name to a second file htpasswd file.  The htpasswd file is where the list of users / passwords are to be located.

Click on the button, copy the text and place it into a text file.  Name this file .htaccess and upload it to the folder that you want to protect.  In this case this would be the /admin/ folder.

(2) Create the .htpasswd username / password file

Go to http://www.htaccesstools.com/htpasswd-generator/

In the first box enter the username.

In the second box enter the password.

Click the button, copy the text and place it into a text file.  Name this file .htpasswd and upload it to a suitable location on your server.  This can be anywhere on your server, but usually in a defined folder.  The location is the same location as was entered in (1) above.

The folder as defined in (1) should now be protected by the username / password as defined in (2)

EasyPHP on Windows 7

EasyPHP is an application that you install on your Windows computer which you can use as a development system for PHP / Apache and mySQL databases.

It can be downloaded form http://www.easyphp.org/ and I find it a very good way to develop applications using PHP on my Windows computer.

EasyPHP contains a single exectuable which when run, installs PHP, Apache web server and a mySQL database onto your Windows computer.  All very neat and convenient to use.

However, when I tried to install on Windows 7 I came across a number of issues with Apache and with mySQL.

When I launched the software, Apache wouldn’t start.  Here is the error :

Apache cannot run: another Web server is using the Web port or port is blocked by firewall.

To overcome this issue :

1. Click the EasyPHP icon beside the “Apache” button.
2. Click “Configure” then click “EasyPHP“.
3. Uncheck “Check server’s TCP port before starting” then click “Apply” button and then “Close” button.
4. Click “Apache” button and then click “Start“.

That fixes the “Apache cannot run…” problem.

The above gets the Apache server to work but after I closed EasyPHP and ran it again, I got this second error message :

Unexpected end of MySql… See log file?

This is a mySQL error message and is actually a file permission problem.

So I changed the user permission for the EasyPHP directory and mySQL correctly started.

To set your permissions this is what you do :

1. Open and view Drive C using the windows explorer, then double click “Program Files” assuming that you installed EasyPHP in that folder.
2. Right click on the folder where you installed EasyPHP then click “Properties“.
3. On “Security” tab click “Edit…” button.
4. Select the user that you are currently using.  This will probably be something like “Users (computer name)”
5. Under “Permissions for Users” box, tick “Full control” on “Allow” column.
6. And then click “OK” button to apply the changes.

Now you should be able to start mySQL server by clicking “mySQL” button on EasyPHP dialog and then click “Start“.  Or shut down EasyPHP and restart it again.

Hopefully that will solve issues when working with Windows 7 and EasyPHP.

EasyPHP on Windows 7

EasyPHP is an application that you install on your Windows computer which you can use as a development system for PHP / Apache and mySQL databases.

It can be downloaded form http://www.easyphp.org/ and I find it a very good way to develop applications using PHP on my Windows computer.

EasyPHP contains a single exectuable which when run, installs PHP, Apache web server and a mySQL database onto your Windows computer. All
very neat an convenient to use.

However, when I tried to install on Windows 7 I came across a number of issues with Apache and with mySQL.

When I launched the software, Apache wouldn’t start. Here is the error :

Apache cannot run: another Web server is using the Web port or port is blocked by firewall.

To overcome this issue :

1. Click the EasyPHP icon beside the “Apache” button.
2. Click “Configure” then click “EasyPHP“.
3. Uncheck “Check server’s TCP port before starting” then click “Apply” button and then “Close” button.
4. Click “Apache” button and then click “Start“.

That fixes the “Apache cannot run…” problem.

The above gets the Apache server to work but after I closed EasyPHP and ran it again, I got this second error message :

Unexpected end of MySql… See log file?

This is a mySQL error message and is actually a file permission problem.

So I changed the user permission for the EasyPHP directory and mySQL correctly started.

To set your permissions this is what you do :

1. Open and view Drive C using the windows explorer, then double click “Program Files” assuming that you installed EasyPHP in that folder.
2. Right click on the folder where you installed EasyPHP then click “Properties“.
3. On “Security” tab click “Edit…” button.
4. Select the user that you are currently using. This will probably be something like “Users (computer name)”
5. Under “Permissions for Users” box, tick “Full control” on “Allow” column.
6. And then click “OK” button to apply the changes.

Now you should be able to start mySQL server by clicking “mySQL” button on EasyPHP dialog and then click “Start“. Or shut down EasyPHP and restart it again.

Hopefully that will solve issues when working with Windows 7 and EasyPHP.