$node->type throwing PHP errors, occasionally I've created some PHP code to get the node type, use it to get a filename, check if there is a banner image existing by that name; if the file doesn't exist, I render the default image.

In the images folder I'd have the following images.


images/content_type.jpg
images/default.jpg
images/careers.jpg


If the content type is careers, and there is an image called careers.jpg, then that image is displayed, but if that image isn't found then default.jpg is displayed.

    $type = $node-&gt;type;  // This is line 131.
    $type = preg_replace('/\s+/', '-', $type);
    $type = strtolower($type);

    $base_path_trimmed = $base_path;
    $base_path_trimmed = rtrim($base_path_trimmed, '/');


    $img_url = "$base_path_trimmed/sites/default/files/images/banners/sub-banners/$type.jpg"; //placed in variable so it's rendered out in $image
    $image = $_SERVER['DOCUMENT_ROOT'] . $img_url; //php is weird and checks from the server root rather than web root. 

    if (file_exists($image)) {
      print "&lt;img src=\"$img_url\"/ &gt;\n";
    }
    else {
      print "&lt;img src=\"$base_path_trimmed/sites/default/files/images/banners/sub-banners/sub-page-banner.jpg\"/&gt;\n";
    } 


The code works, except I sometimes get the following errors:


  Notice: Undefined variable: node in include() (line 131 of templates/page.tpl.php).
  Notice: Trying to get property of non-object in include() (line 131 of templates/page.tpl.php).


What can I do to avoid those errors? Is there a better way to write the code I need?

EDIT: Better way is to use the Dynamic Banner Module.
If your site is barfing on

$type = $node-&gt;type;


then it more than likely means that $node isn't a real node.  If you are using this in page.tpl.php, then I would guess it is because the code is being called on a non-node page.

BTW, you shouldn't need to place any code in template files.  That is what the preprocess functions are for.  If you need to do things with the page template, then check out template_preprocess_page.