Php Syntax

  • Uploaded by: Muhammad Qaiser
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Php Syntax as PDF for free.

More details

  • Words: 7,773
  • Pages: 42
Downloaded from http://www.w3schools.com/php/php_intro.asp install vertrigo software having php, mysql, apache and every required item for PHP from: http://www.download.com/VertrigoServ/3000-2165_4-10516192.html?tag=lst-1&cdlPid=10782063

PHP Syntax You cannot view the PHP source code by selecting "View source" in the browser - you will only see the output from the PHP file, which is plain HTML. This is because the scripts are executed on the server before the result is sent back to the browser.

Basic PHP Syntax A PHP scripting block always starts with . A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with . However, for maximum compatibility, we recommend that you use the standard form (

A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser:
?>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".

Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

PHP Variables Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script.

Variables in PHP Variables are used for storing a values, like text strings, numbers or arrays. When a variable is set it can be used over and over again in your script All variables in PHP start with a $ sign symbol. The correct way of setting a variable in PHP:

$var_name = value;

New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work. Let's try creating a variable with a string, and a variable with a number:

PHP is a Loosely Typed Language In PHP a variable does not need to be declared before being set. In the example above, you see that you do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on how they are set. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP the variable is declared automatically when you use it.

Variable Naming Rules • • •

A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)

PHP String A string variable is used to store and manipulate a piece of text.

Strings in PHP String variables are used for values that contains character strings. In this tutorial we are going to look at some of the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the string "Hello World" to a string variable called $txt:

The output of the code above will be: Hello World

Now, lets try to use some different functions and operators to manipulate our string.

The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two variables together, use the dot (.) operator:

The output of the code above will be: Hello World 1234

If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.

Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

Using the strlen() function The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!":

The output of the code above will be: 12

The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string:

The output of the code above will be: 6

As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

Complete PHP String Reference For a complete reference of all string functions, go to our complete PHP String Reference. The reference contains a brief description and examples of use for each function!

PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

PHP Form Handling The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Form example:
Name: Age:


The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file. The "welcome.php" file looks like this: Welcome .
You are years old.

A sample output of the above script may be:

Welcome John. You are 28 years old.

The PHP $_GET and $_POST variables will be explained in the next chapters.

Form Validation User input should be validated whenever possible. Client side validation is faster, and will reduce server load. However, any site that gets enough traffic to worry about server resources, may also need to worry about site security. You should always use server side validation if the form accesses a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.

PHP $_GET The $_GET variable is used to collect values from a form with method="get".

The $_GET Variable The $_GET variable is an array of variable names and values sent by the HTTP GET method. The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters). Example
Name: Age:


When the user clicks the "Submit" button, the URL sent could look something like this: http://www.w3schools.com/welcome.php?name=Peter&age=37

The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array): Welcome .
You are years old!

Why use $_GET? Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.

The $_REQUEST Variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods. Example Welcome .
You are years old!

PHP $_POST The $_POST variable is used to collect values from a form with method="post".

The $_POST Variable

The $_POST variable is an array of variable names and values sent by the HTTP POST method. The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Example
Enter your name: Enter your age:


When the user clicks the "Submit" button, the URL will not contain any form data, and will look something like this: http://www.w3schools.com/welcome.php

The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array): Welcome .
You are years old!

Why use $_POST? • •

Variables sent with HTTP POST are not shown in the URL Variables have no length limit

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The $_REQUEST Variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods. Example Welcome .
You are years old!

PHP MySQL Introduction MySQL is the most popular open source database server.

What is MySQL? MySQL is a database. A database defines a structure for storing information. In a database, there are tables. Just like HTML tables, database tables contain rows, columns, and cells. Databases are useful when storing information categorically. A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders".

Database Tables A database most often contains one or more tables. Each table has a name (e.g. "Customers" or "Orders"). Each table contains records (rows) with data. Below is an example of a table called "Persons": LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

Address Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).

Queries A query is a question or a request. With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query: SELECT LastName FROM Persons

The query above selects all the data in the LastName column in the Persons table, and will return a recordset like this: LastName Hansen Svendson Pettersen

Download MySQL Database If you don't have a PHP server with a MySQL Database, you can download MySQL for free here: http://www.mysql.com/downloads/index.html

Facts About MySQL Database One great thing about MySQL is that it can be scaled down to support embedded database applications. Perhaps it is because of this reputation that many people believe that MySQL can only handle small to medium-sized systems. The truth is that MySQL is the de-facto standard database for web sites that support huge volumes of both data and end users (like Friendster, Yahoo, Google). Look at http://www.mysql.com/customers/ for an overview of companies that use MySQL.

PHP MySQL Connect to a Database The free MySQL Database is very often used with PHP.

Connecting to a MySQL Database Before you can access and work with data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function. Syntax mysql_connect(servername,username,password);

Parameter

Description

servername

Optional. Specifies the server to connect to. Default value is "localhost:3306"

username

Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process

password

Optional. Specifies the password to log in with. Default is ""

Note: There are more available parameters, but the ones listed above are the most important. Visit our full PHP MySQL Reference for more details. Example

In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails:

Closing a Connection The connection will be closed as soon as the script ends. To close the connection before, use the mysql_close() function.

PHP MySQL Create Database and Tables A database holds one or multiple tables.

Create a Database The CREATE DATABASE statement is used to create a database in MySQL. Syntax CREATE DATABASE database_name

To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example

In the following example we create a database called "my_db":

Create a Table The CREATE TABLE statement is used to create a database table in MySQL. Syntax CREATE TABLE table_name (

column_name1 data_type, column_name2 data_type, column_name3 data_type, ....... )

We must add the CREATE TABLE statement to the mysql_query() function to execute the command. Example

The following example shows how you can create a table named "person", with three columns. The column names will be "FirstName", "LastName" and "Age":

Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function. Note: When you create a database field of type varchar, you must specify the maximum length of the field, e.g. varchar(15).

MySQL Data Types

Below are the different MySQL data types that can be used: Numeric Data Types

Description

int(size) smallint(size) tinyint(size) mediumint(size) bigint(size)

Hold integers only. The maximum number of digits can be specified in the size parameter

decimal(size,d) double(size,d) float(size,d)

Hold numbers with fractions. The maximum number of digits can be specified in the size parameter. The maximum number of digits to the right of the decimal is specified in the d parameter

Textual Data Types

Description

char(size)

Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis

varchar(size)

Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis

tinytext

Holds a variable string with a maximum length of 255 characters

text blob

Holds a variable string with a maximum length of 65535 characters

mediumtext mediumblob

Holds a variable string with a maximum length of 16777215 characters

longtext longblob

Holds a variable string with a maximum length of 4294967295 characters

Date Data Types

Description

date(yyyy-mm-dd) Holds date and/or time datetime(yyyy-mm-dd hh:mm:ss) timestamp(yyyymmddhhmmss)

time(hh:mm:ss)

Misc. Data Types

Description

enum(value1,value2,ect)

ENUM is short for ENUMERATED list. Can store one of up to 65535 values listed within the ( ) brackets. If a value is inserted that is not in the list, a blank value will be inserted

set

SET is similar to ENUM. However, SET can have up to 64 list items and can store more than one choice

Primary Keys and Auto Increment Fields Each table should have a primary key field. A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table. Furthermore, the primary key field cannot be null because the database engine requires a value to locate the record. The primary key field is always indexed. There is no exception to this rule! You must index the primary key field so the database engine can quickly locate rows based on the key's value. The following example sets the personID field as the primary key field. The primary key field is often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the value of the field by 1 each time a new record is added. To ensure that the primary key field cannot be null, we must add the NOT NULL setting to the field. Example $sql = "CREATE TABLE person ( personID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(personID), FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con);

PHP MySQL Insert Into The INSERT INTO statement is used to insert new records into a database table.

Insert Data Into a Database Table The INSERT INTO statement is used to add new records to a database table. Syntax INSERT INTO table_name VALUES (value1, value2,....)

You can also specify the columns where you want to insert the data: INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

Note: SQL statements are not case sensitive. INSERT INTO is the same as insert into.

To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example

In the previous chapter we created a table named "Person", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Person" table:

Insert Data From a Form Into a Database Now we will create an HTML form that can be used to add new records to the "Person" table. Here is the HTML form:
Firstname: Lastname: Age:


When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php". The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables. Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the database table. Below is the code in the "insert.php" page:

PHP MySQL Select The SELECT statement is used to select data from a database.

Select Data From a Database Table The SELECT statement is used to select data from a database. Syntax SELECT column_name(s) FROM table_name

Note: SQL statements are not case sensitive. SELECT is the same as select. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example

The following example selects all the data stored in the "Person" table (The * character selects all of the data in the table): "; } mysql_close($con); ?>

The example above stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each subsequent call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']). The output of the code above will be: Peter Griffin Glenn Quagmire

Display the Result in an HTML Table The following example selects the same data as the example above, but will display the data in an HTML table: Firstname Lastname "; while($row = mysql_fetch_array($result)) { echo ""; echo "" . $row['FirstName'] . ""; echo "" . $row['LastName'] . ""; echo ""; } echo ""; mysql_close($con); ?>

The output of the code above will be: Firstna Lastname me Glenn

Quagmire

Peter

Griffin

PHP MySQL The Where Clause To select only data that matches a specified criteria, add a WHERE clause to the SELECT statement.

The WHERE clause To select only data that matches a specific criteria, add a WHERE clause to the SELECT statement. Syntax SELECT column FROM table WHERE column operator value

The following operators can be used with the WHERE clause: Operator

Description

=

Equal

!=

Not equal

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

BETWEEN

Between an inclusive range

LIKE

Search for a pattern

Note: SQL statements are not case sensitive. WHERE is the same as where. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example

The following example will select all rows from the "Person" table, where FirstName='Peter':
mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person WHERE FirstName='Peter'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "
"; } ?>

The output of the code above will be: Peter Griffin

PHP MySQL Order By Keyword The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY Keyword The ORDER BY keyword is used to sort the data in a recordset. Syntax SELECT column_name(s) FROM table_name ORDER BY column_name

Note: SQL statements are not case sensitive. ORDER BY is the same as order by. Example

The following example selects all the data stored in the "Person" table, and sorts the result by the "Age" column:
} mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "
"; } mysql_close($con); ?>

The output of the code above will be: Glenn Quagmire 33 Peter Griffin 35

Sort Ascending or Descending If you use the ORDER BY keyword, the sort-order of the recordset is ascending by default (1 before 9 and "a" before "p"). Use the DESC keyword to specify a descending sort-order (9 before 1 and "p" before "a"): SELECT column_name(s) FROM table_name ORDER BY column_name DESC

Order by Two Columns It is possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are identical: SELECT column_name(s) FROM table_name ORDER BY column_name1, column_name2

PHP MySQL Update The UPDATE statement is used to modify data in a database table.

Update Data In a Database The UPDATE statement is used to modify data in a database table. Syntax UPDATE table_name SET column_name = new_value WHERE column_name = some_value

Note: SQL statements are not case sensitive. UPDATE is the same as update.

To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example

Earlier in the tutorial we created a table named "Person". Here is how it looks: FirstName

LastName

Age

Peter

Griffin

35

Glenn

Quagmire

33

The following example updates some data in the "Person" table:

After the update, the "Person" table will look like this: FirstName

LastName

Age

Peter

Griffin

36

Glenn

Quagmire

33

PHP MySQL Delete From The DELETE FROM statement is used to delete rows from a database table.

Delete Data In a Database The DELETE FROM statement is used to delete records from a database table. Syntax DELETE FROM table_name WHERE column_name = some_value

Note: SQL statements are not case sensitive. DELETE FROM is the same as delete from.

To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example

Earlier in the tutorial we created a table named "Person". Here is how it looks: FirstName

LastName

Age

Peter

Griffin

35

Glenn

Quagmire

33

The following example deletes all the records in the "Person" table where LastName='Griffin':



After the deletion, the table will look like this: FirstName

LastName

Age

Glenn

Quagmire

33

PHP Database ODBC ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. an MS Access database).

Create an ODBC Connection With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available. Here is how to create an ODBC connection to a MS Access Database: 1. 2. 3. 4. 5. 6. 7. 8.

Open the Administrative Tools icon in your Control Panel. Double-click on the Data Sources (ODBC) icon inside. Choose the System DSN tab. Click on Add in the System DSN tab. Select the Microsoft Access Driver. Click Finish. In the next screen, click Select to locate the database. Give the database a Data Source Name (DSN). Click OK.

Note that this configuration has to be done on the computer where your web site is located. If you are running Internet Information Server (IIS) on your own computer, the instructions above

will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use.

Connecting to an ODBC The odbc_connect() function is used to connect to an ODBC data source. The function takes four parameters: the data source name, username, password, and an optional cursor type. The odbc_exec() function is used to execute an SQL statement. Example

The following example creates a connection to a DSN called northwind, with no username and no password. It then creates an SQL and executes it: $conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql);

Retrieving Records The odbc_fetch_row() function is used to return records from the result-set. This function returns true if it is able to return rows, otherwise false. The function takes two parameters: the ODBC result identifier and an optional row number: odbc_fetch_row($rs)

Retrieving Fields from a Record The odbc_result() function is used to read fields from a record. This function takes two parameters: the ODBC result identifier and a field number or name. The code line below returns the value of the first field from the record: $compname=odbc_result($rs,1);

The code line below returns the value of a field called "CompanyName":

$compname=odbc_result($rs,"CompanyName");

Closing an ODBC Connection The odbc_close() function is used to close an ODBC connection. odbc_close($conn);

An ODBC Example The following example shows how to first create a database connection, then a result-set, and then display the data in an HTML table. "; echo "Companyname"; echo "Contactname"; while (odbc_fetch_row($rs)) { $compname=odbc_result($rs,"CompanyName"); $conname=odbc_result($rs,"ContactName"); echo "$compname"; echo "$conname"; } odbc_close($conn); echo ""; ?>

Optional PHP Error Handling The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser.

PHP Error Handling When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. This tutorial contains some of the most common error checking methods in PHP. We will show different error handling methods: • • •

Simple "die()" statements Custom errors and error triggers Error reporting

Basic Error Handling: Using the die() function The first example shows a simple script that opens a text file:

If the file does not exist you might get an error like this: Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\webfolder\test.php on line 2

To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:

Now if the file does not exist you get an error like this: File not found

The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error. However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.

Creating a Custom Error Handler Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):

Syntax error_function(error_level,error_message, error_file,error_line,error_context)

Parameter

Description

error_level

Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels

error_message

Required. Specifies the error message for the user-defined error

error_file

Optional. Specifies the filename in which the error occurred

error_line

Optional. Specifies the line number in which the error occurred

error_context

Optional. Specifies an array containing every variable, and their values, in use when the error occurred

Error Report levels These error report levels are the different types of error the user-defined error handler can be used for: Value Constant 2 E_WARNING

Description Non-fatal run-time errors. Execution of the script is not halted 8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally 256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0) Now lets create a function to handle errors: function customError($errno, $errstr) { echo "Error: [$errno] $errstr
"; echo "Ending Script"; die(); }

The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script. Now that we have created an error handling function we need to decide when it should be triggered.

Set Error Handler The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script. It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors: set_error_handler("customError");

Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.

Example Testing the error handler by trying to output variable that does not exist: Error: [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?>

The output of the code above should be something like this: Custom error: [8] Undefined variable: test

Trigger an Error In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.

Example In this example an error occurs if the "test" variable is bigger than "1":
$test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?>

The output of the code above should be something like this: Notice: Value must be 1 or below in C:\webfolder\test.php on line 6

An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered. Possible error types: • • •

E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally

Example In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script: Error: [$errno] $errstr
"; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>

The output of the code above should be something like this:

Error: [512] Value must be 1 or below Ending Script

Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.

Error Logging By default, PHP sends an error log to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination. Sending errors messages to yourself by e-mail can be a good way of getting notified of specific errors.

Send an Error Message by E-Mail In the example below we will send an e-mail with an error message and end the script, if a specific error occurs: Error: [$errno] $errstr
"; echo "Webmaster has been notified"; error_log("Error: [$errno] $errstr",1, "[email protected]","From: [email protected]"); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>

The output of the code above should be something like this: Error: [512] Value must be 1 or below Webmaster has been notified

And the mail received from the code above looks like this:

Error: [512] Value must be 1 or below

This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.

PHP Exception Handling Exceptions are used to change the normal flow of a script if a specified error occurs

What is an Exception With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: • • •

The current code state is saved The code execution will switch to a predefined (custom) exception handler function Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code

We will show different error handling methods: • • • • •

Basic use of Exceptions Creating a custom exception handler Multiple exceptions Re-throwing an exception Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.

Basic Use of Exceptions

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. Lets try to throw an exception without catching it: 1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception checkNum(2); ?>

The code above will get an error like this: Fatal error: with message Stack trace: checkNum(28)

Uncaught exception 'Exception' 'Value must be 1 or below' in C:\webfolder\test.php:6 #0 C:\webfolder\test.php(12): #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch To avoid the error from the example above, we need to create the proper code to handle an exception. Proper exception code should include: 1. Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown" 2. Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" 3. Catch - A "catch" block retrieves an exception and creates an object containing the exception information Lets try to trigger an exception with valid code:
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 shown echo 'If you see this, the number is 1 or below'; } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?>

The code above will get an error like this: Message: Value must be 1 or below

Example explained: The code above throws an exception and catches it: 1. The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown 2. The checkNum() function is called in a "try" block 3. The exception within the checkNum() function is thrown 4. The "catch" block retrives the exception and creates an object ($e) containing the exception information 5. The error message from the exception is echoed by calling $e->getMessage() from the exception object However, one way to get around the "every throw must have a catch" rule is to set a top level exception handler to handle errors that slip through.

Creating a Custom Exception Class

Creating a custom exception handler is quite simple. We simply create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class. The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it. Lets create an exception class: getLine().' in '.$this->getFile() .': '.$this->getMessage().' is not a valid E-Mail address'; return $errorMsg; } } $email = "[email protected]"; try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>

The new class is a copy of the old exception class with an addition of the errorMessage() function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine() and getFile() and getMessage().

Example explained: The code above throws an exception and catches it with a custom exception class: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an email address is invalid 3. The $email variable is set to a string that is not a valid e-mail address

4. The "try" block is executed and an exception is thrown since the e-mail address is invalid 5. The "catch" block catches the exception and displays the error message

Multiple Exceptions It is possible for a script to use multiple exceptions to check for multiple conditions. It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages: getLine().' in '.$this->getFile() .': '.$this->getMessage().' is not a valid E-Mail address'; return $errorMsg; } } $email = "[email protected]"; try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } //check for "example" in mail address if(strpos($email, "example") !== FALSE) { throw new Exception("$email is an example e-mail"); } } catch (customException $e) { echo $e->errorMessage(); } catch(Exception $e) { echo $e->getMessage(); } ?>

Example explained:

The code above tests two conditions and throws an exception if any of the conditions are not met: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an email address is invalid 3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example" 4. The "try" block is executed and an exception is not thrown on the first condition 5. The second condition triggers an exception since the e-mail contains the string "example" 6. The "catch" block catches the exception and displays the correct error message If there was no customException catch, only the base exception catch, the exception would be handled there

Re-throwing Exceptions Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block. A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message: getMessage().' is not a valid E-Mail address.'; return $errorMsg; } } $email = "[email protected]"; try { try { //check for "example" in mail address if(strpos($email, "example") !== FALSE) { //throw exception if email is not valid throw new Exception($email); } } catch(Exception $e) {

//re-throw exception throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>

Example explained: The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an email address is invalid 3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example" 4. The "try" block contains another "try" block to make it possible to re-throw the exception 5. The exception is triggered since the e-mail contains the string "example" 6. The "catch" block catches the exception and re-throws a "customException" 7. The "customException" is caught and displays an error message If the exception is not caught in it's current "try" block, it will search for a catch block on "higher levels".

Set a Top Level Exception Handler The set_exception_handler() function sets a user-defined function to handle all uncaught exceptions. Exception: " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?>

The output of the code above should be something like this:

Exception: Uncaught Exception occurred

In the code above there was no "catch" block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions.

Rules for exceptions • • • •

Code may be surrounded in a try block, to help catch potential exceptions Each try block or "throw" must have at least one corresponding catch block Multiple catch blocks can be used to catch different classes of exceptions Exceptions can be thrown (or re-thrown) in a catch block within a try block

A simple rule: If you throw something, you have to catch it.

Related Documents

Php Syntax
May 2020 8
Basic Php Syntax
May 2020 7
Syntax
May 2020 13
Jsp Syntax
November 2019 27
Full Syntax
November 2019 30
Php
November 2019 9

More Documents from "dymix"