-1

I have a function forbid() that is supposed to write to a log file that access was denied, along with a reason for the denial. For some reason, it's not writing to the logfile.

// function to forbid access
function forbid($reason) {
    // explain why
    if ($reason) fputs($file, "=== ERROR: " . $reason . " ===\n");
    fputs($file, "*** ACCESS DENIED ***" . "\n\n\n");
    fclose($file);

    // forbid
    header("HTTP/1.0 403 Forbidden");
    exit;
}

$file is defined earlier in the code, and other fputs() prior to this function are working correctly; I think it's something about the 403 header causing it to not write.

JacobTheDev
  • 17,318
  • 25
  • 95
  • 158
  • 3
    And I think that it's something about `$file` not defined in a function scope. – u_mulder Apr 26 '17 at 14:15
  • If you want to use `$file` within the function you should use a `use` statement or pass it directly to your function as a parameter. – Tobias F. Apr 26 '17 at 14:20
  • It's a named function definition, `use` is for anonymous functions. – Brett Santore Apr 26 '17 at 14:23
  • I cannot see any definition/initialization of variable `$file` in the posted function. It is `NULL` and that's why `fputs()` fails. Read about [variable scope](http://php.net/manual/en/language.variables.scope.php). I would pass `$file` as the first argument to function `forbid()` and **not** use `global`. The `header()` function is *not guilty* (this also applies to `403`.) – axiac Apr 26 '17 at 14:57

1 Answers1

2

Looks like a scope issue. Since it's a function, it's looking for the file handle $file in the functions scope, not global. You need to pass the file handle into the function.

I'm also going to assume that error reporting is turned off, suppressing the problem from you.

Brett Santore
  • 799
  • 6
  • 14