1

So, I have a file called init.php that is supposed to go on top of every page on my website. In this case it is in my index.php. Inside that init.php is a piece of code that includes all files in a folder called include. When I try to call a function within the index.php file that is defined in a file that is supposed to be included I just get an error saying Call to undefined function errors_return(). Any idea what's wrong here?

//index.php
<?php
include "php\init.php";
//errors_return(); is a defined function in functions.php
?>

//init.php
<?php
//error_reporting(0);
foreach (glob("include\*.php") as $filename) {
     include $filename;
}
$GLOBALS["errors_log"] = array();
session_start();
?>

//sample of functions.php
<?php
function error($msg = "default error"){
    array_push($GLOBALS["errors_log"],$msg);
}
function errors_return(){
    if(!empty($GLOBALS["errors_log"])){
        foreach($GLOBALS["errors_log"] as $e){
            echo '<p style="position:relative;">'.$e.'</p>';
        }
    }
    else {
        return null;
    }
}
?>

folder structure
root (folder)
   index.php
   php (folder)
      init.php
      include (folder)
          functions.php
Somebody
  • 333
  • 3
  • 12

3 Answers3

1

You are using a backslash \ inside of double quotes in your code. The backslash in PHP tells the interpreter that an escape sequence begins and the character(s) after the backslash will be tried to be interpreted as such an escape sequence.

As a solution, try replacing your backslash with a double backslash \\ which would escape the backslash itself and interpret it as a normal character or just use slashes / instead of backslashes.

Niklas S.
  • 1,046
  • 10
  • 22
  • It still gives me the call to an undefined function error, But only on the index.php page. If I go to init.php via browser and make it call a function, That works for some reason. But when it's included in an another page the functions that are supposed to be defined won't work. – Somebody Feb 17 '16 at 05:53
  • Did you try replacing also the `include` in your init.php with require? I think the loop there might have path issues. – Niklas S. Feb 17 '16 at 22:23
1

All you have to do is change the directory separator from a forward slash / to a backslash \. I have tested this on my machine and it has worked.

Chris Rutherfurd
  • 1,617
  • 1
  • 15
  • 32
0

So I found out what the problem here is. It seems that when the include happens in the foreach loop, It's not in the right scope to be included with the file itself. I have no idea how to fix this though.

foreach (glob("include\*.php") as $filename) {
     include $filename; //not included with the file
}
include "sample/dir/sample.php"; //included the with file
Somebody
  • 333
  • 3
  • 12