If you are putting this at the top of every file…
// i will keep yelling this // DON'T FORGET TO START THE SESSION !!! session_start();
You may just be doing php wrong… and I hate you
When I saw this post on Better Error Handling, while there is nothing horribly horribly wrong with it I couldn’t help thinking that he has gone past proper error handling. Exceptions are for exceptional cases, hence the name. They should not to be used for flow control, or for things that could occur normally like a user failing to login.
This is because almost all function calls are basically a question:
Within these functions, you can pass an error to the next screen, view, wherever you are returning to because the function failed to produce a positive result.
Things that are exceptional cases would be something similar to the following. In these cases, you cannot continue because the assumptions made by your code were not fulfilled.
The problem with using exceptions for flow control is that you will inevitably end up with something like this if you want to handle each exception individually:
<?php try{ $user->login(); } catch(InvalidDataException $e){ //handle invalid data exception }catch(CouldNotLogInException $e){ //handle could not login }catch(DatabaseException $e){ //handle database exception }
Or something like this if you don’t want to check all possible errors:
<?php try{ $user->login(); } catch(Exception $e){ //handle exception }
The problem with the second one is that now you are treating all exceptions the same way regardless of their actual severity.
Or, if you are validating data:
try{ validateUsername($_POST['username']); } catch(Exception $e){ //handle exception } try{ validatePassword($_POST['password']); } catch(Exception $e){ //handle exception } try{ validateDateOfBirth($_POST['birthday']); } catch(Exception $e){ //handle exception } try{ validateTwitterAccount($_POST['twitter_account']); } catch(Exception $e){ //handle exception } //and so on...
Or if you are lazy:
try{ validateUsername($_POST['username']); validatePassword($_POST['password']); validateDateOfBirth($_POST['birthday']); validateTwitterAccount($_POST['twitter_account']); } catch(Exception $e){ //handle exception }
But then you can only show the user the first thing that failed. Which is not good from a usability perspective because they might have messed up everything after the username, and would then have to submit the form 4 times.
Instead you could do this:
/** * Show the fatal error page when an exception occurs * @var Exception $exception; */ function myExceptionHandler($exception){ displayErrorPage($exception->getMessage()); } set_exception_handler('myExceptionHandler'); $u = new user(); $u->username = $_POST['username']; $u->password = $_POST['password']; $u->birthday = $_POST['birthday']; $u->twitter_account = $_POST['twitter_account']; if($u->save()){ //continue to the next page with a confirmation message } else { //show the user the errors that occurred on the page they just came from }
Which is a much nicer alternative.
Just a quick tip today. If your function looks something like this:
<?php /** * A really long function definition * @param string $has * @param bool $a * @param int $lot * @param float $of * @param assoc_array $parameters * @param string $I * @param string $wonder * @param int $what * @param int $they * @param int $do */ function myfunction( $has=null, $a=null, $lot=null, $of=null, $parameters=null, $I=null, $wonder=null, $what=null, $they=null, $do=null ){ //do some magic } //this is how it would be called myfunction(null, false, null, 1.2, array('one'=>1, 'two'=>2), 'I', null, 1, null, 3);
You are doing it wrong, if all of these parameters are really nullable and required for your function, and there is no way for you to split it up, then you _can_ refactor it like this:
<?php /** * Quickly refactored to make it easier to use * @param array $array containing: (string)'has', (bool)'a', (int)'lot', (float)'of', (assoc_array)'parameters', (string)'I', (string)'wonder', (int)'what', (int)'they', (int)'do' */ function myFunction(array $array){ //make sure we are only taking in parameters that we recognize... $has = isset($array['has'])? $array['has']:null; //array key exists because it is a fake boolean value... it has 3 possibilities $a = array_key_exists('a', $array)? $array['a']:null; $lot = isset($array['lot'])? $array['lot']:null; $of = isset($array['of'])? $array['of']:null; $parameters = isset($array['parameters'])? $array['parameters']:null; $I = isset($array['I'])? $array['I']:null; $wonder = isset($array['wonder'])? $array['hwonders']:null; $what = isset($array['what'])? $array['what']:null; $they = isset($array['they'])? $array['they']:null; $do = isset($array['do'])? $array['do']:null; //some magic } //it could also be written: /** * Quickly refactored to make it easier to use * @param array $array containing: (string)'has', (bool)'a', (int)'lot', (float)'of', (assoc_array)'parameters', (string)'I', (string)'wonder', (int)'what', (int)'they', (int)'do' */ function myFunction(array $array){ //make sure we are only taking in parameters that we recognize... $args = array('has', 'a', 'lot', 'of', 'parameters', 'I', 'wonder', 'what', 'they', 'do'); foreach($args as $arg){ $$arg = array_key_exists($arg, $array)? $array[$arg]:null; } //some magic } //this is how it would be called //equivalent to: //myfunction(null, false, null, 1.2, array('one'=>1, 'two'=>2), 'I', null, 1, null, 3); myfunction(array('a'=> false, 'lot'=>1.2, 'parameters'=>array('one'=>1, 'two'=>2), 'I'=>'I', 'what'=>1, 'do'=>3));
It may be more to type, but it is harder to get it wrong when you are using named parameters. You don’t have to remember what each of the parameters do in their specific positions either so it is easier to understand the code as you quickly glance at it. Note that this is similar to the way that a lot of ruby functions are written, except we don’t have a short hand for named parameters like they do (it would be awesome if we did…):
myfunction(:a => false, :lot => 1.2, :parameters => { :one => 1, :two => 2 }, :I => 'I', :what => 1, :do => 3)
While this is definitely easier to read and remember, it is probably worth refactoring a function like this (as it is an extreme case) further because it is likely that you are doing way too many things within it.
I realise that I already posted something today, but this seemed like an emergency…

I thought maybe this was a serious post when I clicked on it, then when I got to number 2 on the list (I had skipped reading his post about how you should write an index page), I thought maybe he was joking, but at the end of it I realised that he was not.
1. How to Properly Create a Website Index Page
See my post about how to do it right.
[... snip]$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'home'; switch($page) { case 'home': break; case 'mail': break; case 'contact': break; default: $page = 'home'; } include("$page.php");[... snip]
Apparently this is the right way. I do like the single point of entry idea, and at least he is filtering the variables so you can’t load other php pages right? It really is too bad my $_COOKIE['page'] = ‘mail’… I wonder what the rest of the site is like. This also makes it a pain to add new pages, and causes a massive switch statement.
2. Use the Request Global Array to Grab Data
There is actually no reason to use $_GET and $_POST arrays to grab values. $_REQUEST, is another global array that fetches you either a get or form request. Therefore, it’s most times more convenient to use something like this to parse data…
No! This is wrong, the $_REQUEST array contains not only the $_POST and $_GET variable contents but it also contains the contents of the $_COOKIE array. The arrays are merged in the order described by your php.ini file, generally $_GET, $_POST, $_COOKIE but not always. So, use the $_POST variable when you mean for it to come from the $_POST variable, use the $_GET for get variables, and the $_COOKIE for things in the cookie. Don’t take the lazy way out.
3. Debugging PHP is About var_dump
If you’re looking for php debugging techniques, i have to say that var_dump is most times the way to go about it…
Wrong again. var_dump simply tells you what is in whatever object/array/whatever you are var_dumping. The xdebug extension is a much better alternative:
The Xdebug extension helps you debugging your script by providing a lot of valuable debug information. The debug information that Xdebug can provide includes the following:
* stack traces and function traces in error messages with:
o full parameter display for user defined functions
o function name, file name and line indications
o support for member functions
* memory allocation
* protection for infinite recursions
Xdebug also provides:
* profiling information for PHP scripts
* code coverage analysis
* capabilities to debug your scripts interactively with a debug client
4. PHP Handles The Code Logic, Smarty Handles The Presentation
… Learn to use smarty as a template engine for your websites, it will pay off, i promise.
While I am not advocating combining “Code Logic” and “Presentation”, there are much better tools out there than Smarty. Smarty is a horrid piece of archaic spaghetti that had it’s purpose a long time ago, but no longer really does. Or you could learn to separate the presentation from the logic by using one of the myriads of frameworks out there. You could even go one better by separating it out to use the MVC pattern.
5. When You Absolutely Need Global Values, Create a Config File
… Doing it for database tables or database connection information is a good idea, but do not use global variables throughout your PHP code. Moreover, it is always a better idea to keep your global variables at a single config.php file.
Actually… this one isn’t bad, polluting the global namespace is something you should try to avoid, and keeping all of your config values in one place makes them easy to find.
6. If NOT Defined, Access Denied !
If you’re creating your pages the correct way, there will absolutely no reason for anybody to access any other php page other than index.php or home.php.
This goes back to #1, a horrible way to make an index page.
7. Create a Database Class
If you’re doing database programming (pretty common in PHP), it would be a very good idea to create a database class to handle any database management functions.
He then goes on to suggest you make a dbExec($query) function which calls $this->db->exec($query), and a sanitize($var1, $var2…) function which will not actually sanitize the input (it appears to just be making sure the input is numeric?). In his examples he is using the PEAR classes for his database abstraction, which already does this… so I am not sure what the point of putting a database abstraction ontop of a database abstraction is here. Also, use the escape functions that are already given to you by php (or the pear library so that your code is portable across database backends), do not write your own, you will get it wrong.
8. A php File Handles Input, a class.php File Handles Functionality
[...] The php file gets any input that we need and then redirects execution to a function residing to the class file. [...]
It almost seems like he is implementing a poorman’s MVC? I think? Mostly? A much better way would be to actually use an MVC framework (or to look at a tutorial online and see a much better way to do it).
9. Know Your SQL and Always Sanitize
Let me present you an example of a function that uses mySQL and sanitazes using the function seen on point #7private function getSentMessages($id) { $this->util->sanitizeInput($id); $pm_table = $GLOBALS['config']['privateMsg']; $users = $GLOBALS['config']['users']; $sql = "SELECT PM.*, USR.username as name_sender FROM $pm_table PM, $users USR WHERE id_sender = '$id' AND sender_purge = FALSE AND USR.id = PM.id_receiver AND is_read = TRUE ORDER BY date_sent DESC"; $result = $this->dbQueryAll($sql); return $result; }
The message is the right one. Sanitize your input. However, it would be awesome if he used some coding standards for naming his variables $user and $pm_table are both tables apparently. The well named function sanitizeInput should probably be renamed to checkInt or something similar since that is what it appears to do. He should also probably not be putting his variables straight in the string, to make it easier to change the query later on when he realises that he missed something. Don’t even get me started on the fact that this function is private and presumably extends his database abstraction class…
10. When You Need Just an Object, Use a Singleton Pattern
It happens pretty often in PHP that we just need a single object created one time and then used globally throughout our whole program. A good example of this is the smarty variable that has to be initialized once and then is used all over the place.
[..snip...]function smartyObject() { if ($GLOBALS['config']['SmartyObj'] == 0) { $smarty = new SmartyGame(); $GLOBALS['config']['SmartyObj'] = $smarty; } else $smarty = $GLOBALS['config']['SmartyObj']; return $smarty; }[.../snip...]
The singleton pattern: you’re doing it wrong.
This is not actually a singleton pattern, while yes it lets you get the instance that you created earlier, you can still create the object by normal means, so I could have $GLOBALS['config']['SmartyObj'], $GLOBALS['config']['SmartyObj2'], $GLOBALS['config']['SmartyObj3'] which would all be instances of the smarty object, but they can all have different properties and values. If it were a singleton this would not be the case. The proper way of doing this is to use the pattern described in the php.net manual under Patterns Singleton. That way it is always the same object everywhere that you use it, and you do not have to muck around with the $GLOBALS array (which I am pretty sure is a code smell…).
Read his full post here. If you think I may have been too harsh, or not harsh enough, on him, leave a comment.