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;
  };
?>
0

4 Answers 4

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";
//}
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Thank you very much! PHP is still very new to me so this was a massive help
Glad it helped. :)
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

1 Comment

Please note that @Sougata Bose approach is better than silencing errors
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.