0

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 Answers4

1

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";
//}
Ammar Tahir
  • 312
  • 4
  • 19
0

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()

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

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

malarzm
  • 2,831
  • 2
  • 15
  • 25
0

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

pakalbekim
  • 139
  • 3
  • 12