在外部php文件上返回函数

时间:2016-04-08 08:12:29

标签: php html mysql

我正在尝试开发一个简单的登录表单来学习php。

我创建了一个表单和一个函数,它将查询发送到mysql数据库以检索用户名和密码(存​​储在md5加密中)并使用用户插入的数据对其进行控制。

问题是这个函数(login())在一个名为fun_login.php的外部文件中,当我从页面login.php调用它时,它打开页面fun_login.php并且它不会返回登录.php(我认为因为返回值存在一些问题)

在login.php中,我已将文件fun_login.php与

一起包含在内
<?php

include "fun_login.php";

?>

的login.php

  <div class="container">
    <div class="row">
        <div class="col-sm-2 col-sm-offset-5">
            <form action="fun_login.php" role="form" method="post">
                <div class="form-group">
                    <label for="nome">Username:</label>
                    <input type="textarea" class="form-control" id="username" name="username">
                </div>
                <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="password" class="form-control" id="password" name="password">
                </div>
                <button type="submit" class="btn btn-default" id="submitlogin" name="submitlogin">Log In</button>
            </form>
            <?php
            if(isset($_POST['submitlogin'])) {
                $control = login($_POST['username'], md5($_POST['password']));
            if($control) header("Location: ./index.php");
            else header("Location: ./login.php");
                }
            ?>
        </div>
    </div>
</div>

fun_login.php

    <?php

function login($username, $password) {
    $myconn = mysql_connect(localhost, root, password);
    mysql_select_db('portfolio', $myconn);
    $query = "SELECT username,password,admin FROM utenti WHERE username = '" . $username . "' AND password = '" .$password . "';";
    $result = mysql_query($query, $myconn)or die('Error, insert query failed');  
        // conto il numero di occorrenze trovate nel db
$numrows = mysql_num_rows($result);

// se il database è vuoto lo stampo a video
if ($numrows == 0) return false;
// se invece trovo delle occorrenze...
else return true;   
}
?>

2 个答案:

答案 0 :(得分:0)

当你打电话时

<?php
if(isset($_POST['submitlogin'])) {
    $control = login($_POST['username'], md5($_POST['password']));
if($control) header("Location: ./index.php");
else header("Location: ./login.php");
    }
?>

在您的login.php标题已经发送,因此header('Location:')无效。

您需要在显示任何输出(echo或html)之前放置它。 如果查看错误日志,您可能会看到Warning: Cannot modify header information - headers already sent by

根据它的外观,该文件包含在布局或其他内容中,因此您的login()调用必须在此之前。

答案 1 :(得分:-2)

您收到的错误消息是什么? 在php文件的开头使用此命令:

o_c OUT INTEGER

然后你会知道发生了哪个错误,如果有的话。