PHP Include - Error Fixing

60 views Asked by At

I have the following PHP code that produces an error as the include files don't exist. I have not yet made them but I want to stop errors being produced (not just hidden). Is there anything I can put into my code that says "don't record any errors if the file doesn't exist, just ignore the instruction"

<?php
  $PAGE = '';
  if(isset($_GET['page'])) {
    $PAGE = $_GET['page'];
  };

  switch ($PAGE) {
    case 'topic': include 'topic.php';
    break;
    case 'login': include 'login.php';
    break;
    default: include 'forum.php';
    break;
  };
?>
4

There are 4 answers

2
Sougata Bose On BEST ANSWER

Include the files only if they exist. You can add a check for existing file -

switch ($PAGE) {
    case 'topic': 
       if(file_exists(path_to_file)) {
           include 'topic.php';
       }
    break;
    ......
};

file_exists()

1
malarzm On

You seem to be looking for @ operator which silences any errors from an expression, you can read more about it here: http://php.net/manual/en/language.operators.errorcontrol.php

0
pakalbekim On

Use file_exists() function:

<?php
  $PAGE = '';
  if(isset($_GET['page'])) {
    $PAGE = $_GET['page'];
  };

  switch ($PAGE) {
    case 'topic': 
        if (file_exists("topic.php")){
            include 'topic.php';    
        }
        break;
    case 'login':
        if (file_exists("login.php")){
            include 'login.php';    
        }
        break;
    default:
        if (file_exists("forum.php")){
            include 'forum.php';    
        }       
        break;
  };
?>

Documentation http://php.net/manual/en/function.file-exists.php

0
Ammar Tahir On

use file_exists() to check if your file exists or not before calling include;

if (file_exists('forum.php')) {
    //echo "The file forum.php exists";
    include 'forum.php';
}
//else
//{
//    echo "The file forum.php does not exists";
//}