enloz
enloz

Reputation: 5824

custom error when trying to include/require

How to print custom error when trying to include/require a php file ?

This was my idea:

<?php 

try{
    include "template/".$_GET['view'].".php"; 
}
catch (Exception $e){
    echo 'some error code'; 
};

?>

But, still I'm getting default error if required file don't exist.

Upvotes: 1

Views: 446

Answers (6)

adilbo
adilbo

Reputation: 970

If you want your own error Message you can do it like this:

<?php
$file = "template/".$_GET['view'].".php";
if ( error_reporting() == 0 ){
    ( @include_once($file) ) OR die("<tt><p><b>ERROR</b> $file file not found!</p>");
}else{
    require_once($file);
}
?>

So if there is no error reporting (as most time in productiv enviroment) you can print your own Error Message. If you are in Development Mode (ans error_reporting is on) the you get PHP Error Message!

HINT Never use $_GET Input from user direct for an Include - this is a Black XSS Hole :-D

Upvotes: 0

KryptoniteDove
KryptoniteDove

Reputation: 1268

if ((include "template/".$_GET['view'].".php") != 'OK') {
    echo "My custom error message";
}

Upvotes: 1

jeroen
jeroen

Reputation: 91734

I would not recommend using just file_exist. You don't want your visitor to have access to any file on your file-system so I would recommend a white-list; if the file-name is in the white-list, only then display / include it.

Upvotes: 1

Shawn Lehner
Shawn Lehner

Reputation: 1323

The include errors are not going to be caught by your try/catch, however, I believe that errors inside the included script would be caught correctly. A better solution would be to use the file-exists function, see this post for an example: Optional include in PHP

Once you perform your own verification for the existence for the file you can wrap the executing code in a try catch to ensure errors in that code are caught.

Upvotes: 1

Blake
Blake

Reputation: 2314

Decided the comment was worth changing to answer:

Use file_exists() to see if file exists.

If it does, include, else echo your custom error message.

Upvotes: 4

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

Use file_exists() to check if the file is there before including. That way you can handle the error.

<?php

if(file_exists('asd.php')){
    include "asd.php";
}else{
    echo "Oh no! The file doesn't exist!";
}

?>

Upvotes: 1

Related Questions