1

我正在尝试将一个我常用的函数放在它自己的文件中。然后,我想包含该文件,以便我可以访问该功能(或者我认为)。

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');

除了“警告:session_start”错误之外,这消除了所有错误。

4

2 回答 2

1

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

于 2013-06-11T21:48:32.230 回答
0

如果 activity.php 在/Users/Eamon/Sites/templates/您可以将您的包含更改为

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

它应该适合你。

于 2013-06-11T21:47:08.947 回答