require_once help needed

Discussion in 'PHP' started by jumpenjuhosaphat, Feb 7, 2007.

  1. #1
    If I include a file using the require_once function, and that file doesn't exist, or an error is returned, is there a way that I could include a different file in it's place?
     
    jumpenjuhosaphat, Feb 7, 2007 IP
  2. picouli

    picouli Peon

    Messages:
    760
    Likes Received:
    89
    Best Answers:
    0
    Trophy Points:
    0
    #2
    you can do a file_exists() first
    http://php.net/file_exists

    ...or you can use @include_once() (notice the @ to prevent warnings to be shown) since this doesn't throws a Fatal Error and then conditionally include other files

    Just my .2 €... :)
     
    picouli, Feb 7, 2007 IP
  3. jumpenjuhosaphat

    jumpenjuhosaphat Peon

    Messages:
    229
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    So if I do this

    
    $a=@require_once('somefile.php');
    if(!($a)) require_once('thisotherfile.php');
    
    Code (markup):
    would that work?
     
    jumpenjuhosaphat, Feb 7, 2007 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    Just curious, where would you run into the situation where you are returning a file that doesn't exist?

    But, i agree using the file_exists or the @ would be the best way to prevent the error.

    You could do something like:
    
    if(file_exists(myfile.php)){
    include_once(myfile.php);
    } else {
    include (yourfile.php);
    }
    
    PHP:
     
    jestep, Feb 7, 2007 IP
  5. jumpenjuhosaphat

    jumpenjuhosaphat Peon

    Messages:
    229
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Well, I'm just trying to slim down some code that would, based on the $_GET['action'] value, include a file named the same as the variable. So if $_GET['action']="somefile", then somefile.php would be included. but if the action value was somefilethatdoesntexist, then I want to default to using a standard file. I had it set up using the switch case construct, but it was long. I wanted to shrink the code up a bit by including $action.'.php' Did that make sense? I like your solution though, it should work perfectly.

    Here's how it looks, this will give you a better idea of what I mean:
    
    if(!isset($_COOKIE['admin_name']) || !isset($_COOKIE['admin_pass']) ||
       $_COOKIE['admin_name']!=ADMINNAME || 
       $_COOKIE['admin_pass']!=ADMINPASS)
      {
      header('Location: http://[edit]');
      die();
      }
    
    if(isset($_GET['action']))
      {
      $action=validate($_GET['action'],'','','');
    
      if(file_exists($action.'.php'))
        {
        require_once($action.'.php');
        }
    
      else
        {
        require_once('admin_panel.php');
        }
      }
    Code (markup):
     
    jumpenjuhosaphat, Feb 7, 2007 IP