The error handling in PHP is very easy. An error message with filename, line number and a message describing the error are sent to the browser.
When generate scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unethical and you may be open to security risks.
Using the die() function
The first illustration shows a simple script that opens a text file:
<?php
$file=fopen(“chi1.txt”,”c”);
?>
If the file does not exist you might get an error like this:
Advice: fopen(chi1.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:
<?php
if(!file_exists(“chi1.txt”))
{
die(“File not found”);
}
else
{
$file=fopen(“chi1.txt”,”c”);
}
?>
Now if the file does not exist you get an error like this:
File not found
The code above is more competent than the earlier code, because it uses a simple error handling device to stop the script after the error.
In PHP session variable is used to store up information about, or modify settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
Session Variables in PHP
While you are working with an application, you open it, do some modify and then you close it. This is much like a Session. Computer knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t continue state.
A PHP session solves this problem by allowing you to store user information on the server for later use. However, session information is temporary and will be removing after the user has left the website. If you need a enduring storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is spread in the URL.
Create a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Message: The session_start() function must appear ahead of the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user’s session with the server, allow you to start saving user information, and allot a UID for that user’s session.
Store up a Session Variable
The accurate way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['xxx']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo “Page=”. $_SESSION['xxx'];
?>
</body>
</html>
Output:
Page=1
In the example under, we make a simple page counter. The isset() function checks if the “xxx” variable has already been set. If “xxx” has been set, we can addition our counter. If “xxx” doesn’t exist, we create a “xxx” variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['xxx']))
$_SESSION['xxx']=$_SESSION['xxx']+1;
else
$_SESSION['xxx']=1;
echo “Page=”. $_SESSION['xxx'];
?>
Destroying a Session
If you wish to remove some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['xxx']);
?>
You can also totally destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
message: session_destroy() will reset your session and you will lose all your stored session data.
PHP 5 has been a very important release for the language – it has formalized a lot of the features that before had only a little support, or was perhaps distracted. It was also the first version after PHP 4, which was a rebellion in the language, so it had a great deal to live up to. As a major version, PHP 5 has a lifespan of between three and four years – PHP 4 was officially released on 22nd May 2000 and went through many revisions before being replaced by PHP 5 over four years later.
Between now and PHP 6, we will observe several minor patch releases at first that correct many problems with the original PHP 5 release. With PHP 5.1, whenever it is released, we will see the first big set of new functionality – mostly new functions to use, and new ways of doing things. What is certain is that more and more extensions will be added to the system to allow programmers to take advantage of more and more things in their code.
Already confirmed for PHP 5.1 is the PHP Data Objects extension (PDO), which unifies the various database APIs so that you can just call pdo_query() rather than mysql_query(), pgsql_query(), or any of the others. It won’t replace PEAR::DB because it doesn’t abstract the SQL dialects being used, but it will instead complement PEAR::DB. We’re also expecting big speed improvements in PHP 5.1, and not just in any single area – all sorts of calls, from switch/case statements to the sort() function and class autoloading are all improved.
When it comes to what will be in PHP 6, who knows? Many people have asked that PHP be able to compile down into native instructions for maximum speed, which would certainly keep PHP in the lead when it comes to performance, however it would particularly hard to execute. Another possibility is that code caching be built directly into the language so that products such as PHP Accelerator and Zed Performance Suite are no longer necessary – the language could be made to accept caching simply by toggling a switch in php.ini. It is also possible that some features left out from PHP 5 will finally see the light of day in PHP 6, such as namespaces – only time will tell.
Having said that, there are two features I’d particularly like to see in future releases: multiple dispatch and junctions. Multiple dispatches are the technique of calling a given function on several objects at the same time, and if it were in PHP would look something like this:
$array = array($object1, $object2);
$array->doFunc($para1, $para2, $para3);
That would call the doFunc() method of $object1 and $object2, passing in $para1, $para2, and $para3. Junctions – also called quantum superposition by some Perl hackers – is a new feature in Perl 6 that allows you to assign more than one value to a variable then run circumstances like “if $myvar is any of values A, B, C, or D, then…”. Yes, this is already possible with lots of || operators (or && operators if you want to say “$myvar is all of these values…”). Mmmm… quantum superposition!
With PHP continuing to gain massive support from programmers looking to expand their programming horizon, new versions of the language are likely to be geared towards solidifying its position as opposed to revolutionize. When Perl 6 was being intended, many huge changes were brought that separated a lot of developers – hopefully PHP will not go the same way.
In the interim, be happy that you have chosen such a popular language that is advancing so rapidly – PHP is here to stay, and things are only going to get better!
There is another popular method to create and manage arrays, and it uses square brackets [ ] to mean “add to array”, earning it the name “the array operator”. Using this functionality, you can both create arrays and add to existing arrays, so this is generally more popular – you will generally only find the array() function being used when several values are being put within the array, as it will fit on one line. Here are some examples of the array operator in action:
<?php
$array[] = “Zoo”;
$array[] = “War”;
$array[] = “Taz”;
var_dump($array);
?>
That should work in precisely the same as using the array() function, except it is much more elastic – we can add to the array whenever we want to. When it comes to working with non-default indices, we can just place our key inside the square brackets, like this:
<?php
$array["a"] = “Zoo”;
$array["b"] = “War”;
$array["c"] = “Taz”;
var_dump($array);
?>
array array ( [mixed ...])
int count ( mixed var [, int mode])
bool print_r ( mixed expression [, bool return])
void var_dump ( mixed expression [, mixed expression [, mixed ...]])
mixed var_export ( mixed expression [, bool return])
PHP has fitted support for arrays of data, and there are two ways you can create an array: using the array function, or using a special operator, [ ].
Before we look at how arrays work, there are two key things you require to understand before you continue:
1 An array is a normal PHP variable like any others, but it works like a container – you can put other variables inside it
2 Each variable inside an array is called an element. Each element has a key and a value, which can be any other variable.
Now, see this PHP code:
<?php
$myarray = array(“Dean”, “Akki”, “Pars”);
$size = count($myarray);
print_r($myarray);
?>
On line one we see the most basic way to create an array, the array() function. The array() function takes a minimum of one parameter (and a maximum of as many as you want), and returns an array containing those variables. That is right – $myarray now contains all three variables. Line two contains a new function, count(), that returns the number of elements consisting in the array passed to it as its only parameter – in the example we pass in my $myarray, then store the number of elements (three) in $size.
Author’s Note: The array() function actually allows you to have a trailing comma after the last element, eg: array(“Apples”, “Oranges”, “Pears”,). This is rarely used in hand-written code, but it can make generating code much easier.
Line three contains another new function, print_r(). This takes just one parameter, but it outputs detailed information about a variable, such as its type, length, and contents. In the case of arrays, print_r() iteratively outputs all elements inside the array – it is a good way to see how arrays work.
Here is the output of print_r() from the above code:
Array (
[0] => Dean
[1] => Akki
[2] => Pars
)
As you can see, there are our three variables – Apples is at index 0 in the array (signified by “[0]=>”), Oranges is at index 1 in the array, and Pears is at index 2 in the array. Note that if you are running your scripts through a web browser as opposed to from the command-line, you may find it help to put a HTML <pre> tag before your print_r() calls, as this will format them for easier reading.
Using the proper array terminology defined earlier, the 0, 1, and 2 indices are the keys of each element, the “Apples”, “Oranges”, and “Pears” are the values of each element, and the key and the value considered together are the elements themselves.
Note that you can provide a second parameter to print_r(), which, if set to true, will make print_r() pass its output back as its return value, and not print anything out. To achieve the same output using this method, we would need to alter the script to this:
<?php
$myarray = array(“Dean”, “Akki”, “Pars”);
$size = count($myarray);
$output = print_r($myarray, true);
print $output;
?>
You can store whatever you like as values in an array, and you can mix values also. For example: array(“Foo”, 1, 9.995, “bar”, $somevar). You can also put arrays inside arrays, but we will be getting on to that later.
There is a similar function to print_r(), which is var_dump(). It does largely the same thing, but a) prints out sizes of variables, b) does not print out non-public data in objects, and c) does not have the option to pass a second parameter to return its output. For example, altering the first script to use var_dump() rather than print_r() would give the following output:
array(3) {
[0]=>
string(6) “Dean”
[1]=>
string(7) “Akki”
[2]=>
string(5) “Pars”
}
In there you can observe var_dump() has told us that the array has three values, and also prints out the lengths of each of the strings. For teaching purposes, var_dump() is better as it shows the variable sizes, however you will probably want to use print_r() in your own work.
Finally, there is the function var_export(), which is similar to both var_dump() and print_r(). The key difference with var_export(), however, is that it prints out variable information in a style that can be used as PHP code. For example, if we had use var_export() instead of print_r() in the test script, it would have output the following:
array (
0 => ‘Dean’,
1 => ‘Akki’,
2 => ‘Pars’,
)
Note there is an extra comma after the last element, however this is ignored by PHP and you can copy and paste that information directly into your own scripts, like this:
<?php
$foo = array (
0 => ‘ Dean ‘,
1 => ‘ Akki ‘,
2 => ‘Pars’,
);
?>
* When grabbing data from an array, you can simply add the identifier from the array in a square brackets outside the name of the array.
$myarray = array(“Boos”,”Dars”,”Aazzes”);
print $myarray[0];
print “<br>”;
print $myarray[2];
This will return the text “Boos Aazzes”.
This will also work if you specify a key (covered a bit later).