“include"不能在PHP文件中工作,不能引用函数


"include" not working in php file cant reference the function

我试图将一个我通常会在自己的文件中使用的函数。然后,我想包含该文件,以便我可以访问该函数(或我认为)。

activity.php(这是我想要能够使用的函数)

<?php
function activity() {
$inactive = 600;
    // check to see if $_SESSION["timeout"] is set
    if (isset($_SESSION["timeout"])) {
        // calculate the session's "time to live"
        $sessionTTL = time() - $_SESSION["timeout"];
        if ($sessionTTL > $inactive) {
            $_SESSION["loggedIn"] = false;
            session_destroy();
            echo "session destroyed";
        }
    }
    else {
        echo "You need to log in.";
    }
}
?>
下面是showuser.php(错误发生的文件):
<?php
    include ('activity.php');
    session_start();
    // check to see if $_SESSION["timeout"] is set
    activity();
    $host="localhost"; // Host name
    $uname="root"; // Mysql username
    $password="xxx"; // Mysql password
    $db_name="itit"; // Database name
    $tbl_name="users"; // Table name
    // Connect to server and select database.
    $mysqli = mysqli_connect($host, $uname, $password, $db_name);
    if($_SESSION["loggedIn"]) {
        $stmt = $mysqli->prepare("SELECT email FROM users WHERE username = ?");
        $stmt->bind_param("s", $_SESSION["username"]);
        $stmt->execute();
        $stmt->bind_result($em);
        $stmt->fetch();
    }
    else {
        echo "You are not logged in.";
    }
?>
<h2>Username - Email</h2>
<div id="userinfo"><? echo $_SESSION["username"] ?> - <? echo $em ?></div>
<? 
    $stmt->close();
    mysqli_close($mysqli);
?>

函数应该检查会话是否已经超时,除非我做了一些错误的代码…

当运行包含以下文件的脚本时,我得到这些错误:

Warning: include(activity.php) [function.include]: failed to open stream: No such file or directory in /Users/Eamon/Sites/templates/showuser.php on line 2
Warning: include() [function.include]: Failed opening '/activity.php' for inclusion (include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear') in /Users/Eamon/Sites/templates/showuser.php on line 2
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /Users/Eamon/Sites/templates/showuser.php:2) in /Users/Eamon/Sites/templates/showuser.php on line 3
Fatal error: Call to undefined function activity() in /Users/Eamon/Sites/templates/showuser.php on line 6

我这样做了

include ('../activity.php');

这消除了所有的错误,除了"Warning: session_start"错误。

看起来像是PHP查找文件的目录有问题。
尝试将其更改为include ('./activity.php');

如果activity.php在/Users/Eamon/Sites/templates/中,您可以将include更改为

include (__DIR__'."/activity.php');

,它应该为你工作。