【问题标题】:Session cookie issue in the following codes. which is throwing Cannot send session cookie.. warning in php?以下代码中的会话 cookie 问题。在 php 中抛出无法发送会话 cookie.. 警告?
【发布时间】:2015-05-21 15:46:10
【问题描述】:

我正在开发一个注册和登录系统。幸运的是,通过谷歌搜索,我从某个贡献者那里得到了一些现成的代码。但是我在尝试执行相同操作时收到警告消息。我在这里给出两个代码 sn-ps。另外,我想在这里补充一下,我收到了三个警告消息:

警告:session_start() [function.session-start]:无法发送会话 cookie - 标头已由(输出开始于 /home/dchcov5r/public_html/demo/application/includes/register.inc.php:1)在 /home/dchcov5r/public_html/demo/application/functions.php 第 22 行

警告:session_start() [function.session-start]:无法发送会话缓存限制器 - 标头已发送(输出开始于 /home/dchcov5r/public_html/demo/application/includes/register.inc.php:1)在 /home/dchcov5r/public_html/demo/application/functions.php 第 22 行

警告:session_regenerate_id() [function.session-regenerate-id]:无法重新生成会话 ID - 标头已在第 23 行的 /home/dchcov5r/public_html/demo/application/functions.php 中发送

functions.php

            <?php
            ob_start();
            function sec_session_start() {
                $session_name = 'sec_session_id';   // Set a custom session name
                $secure = SECURE;
                // This stops JavaScript being able to access the session id.
                $httponly = true;
                // Forces sessions to only use cookies.
                if (ini_set('session.use_only_cookies', 1) === FALSE) {
                    header("Location: error.php?err=Could not initiate a safe session (ini_set)");
                    exit();
                }
                // Gets current cookies params.
                $cookieParams = session_get_cookie_params();
                session_set_cookie_params($cookieParams["lifetime"],
                    $cookieParams["path"], 
                    $cookieParams["domain"], 
                    $secure,
                    $httponly);
                // Sets the session name to the one set above.
                session_name($session_name);
                session_start();            // Start the PHP session 
                session_regenerate_id(true);    // regenerated the session, delete the old one. 

            }

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // database connection files
            include '../lib/config.php';
            include '../lib/opendb.php';

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            function dLookUp($tablename,$fieldnamereq,$fieldnamegiven,$value){
            $st_rs = mysql_query("select $fieldnamereq from $tablename where $fieldnamegiven='$value'") or die("dLookUp fetch error:".mysql_error());
                if(mysql_num_rows($st_rs) == 1){
                $data = mysql_fetch_array($st_rs);
                echo $data[$fieldnamereq]; 
                }
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            function login($form_no, $password, $conn) {
                // Using prepared statements means that SQL injection is not possible. 
                    $stmt = mysql_query("SELECT sl_no, name, password, salt FROM application_form_i WHERE form_no = '$form_no' LIMIT 1") or die("Error Login :".mysql_error());

                    while($row = mysql_fetch_assoc($stmt)) {
                    // get variables from result.
                    $user_id = $row['sl_no']; 
                    $db_password = $row['password']; 
                    $salt = $row['salt']; 
                    }

                    // hash the password with the unique salt.
                    $password = hash('sha512', $password . $salt);
                    if (mysql_num_rows($stmt) == 1) {
                        // If the user exists we check if the account is locked
                        // from too many login attempts 

                        if (checkbrute($user_id, $conn) == true) {
                            // Account is locked 
                            // Send an email to user saying their account is locked
                            return false;
                        } else {
                            // Check if the password in the database matches
                            // the password the user submitted.
                           if ($db_password == $password) {
                                // Password is correct!
                                // Get the user-agent string of the user.
                                $user_browser = $_SERVER['HTTP_USER_AGENT'];
                                // XSS protection as we might print this value
                                $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                                $_SESSION['user_id'] = $user_id;
                                // XSS protection as we might print this value
                                $_SESSION['login_string'] = hash('sha512',$password . $user_browser);
                                // Login successful.
                                return true;
                            } else {
                                // Password is not correct
                                // We record this attempt in the database
                                $now = time();
                                mysql_query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
                                return false;
                            }
                        }
                    } else {
                        // No user exists.
                        return false;
                    }
            }

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            function checkbrute($user_id, $conn) {
                // Get timestamp of current time 
                $now = time();

                // All login attempts are counted from the past 2 hours. 
                $valid_attempts = $now - (2 * 60 * 60);

                $stmt = mysql_query("SELECT time FROM login_attempts WHERE user_id = $user_id AND time > '$valid_attempts'") or die("Error :".mysql_error());

                    // If there have been more than 5 failed logins 
                    if (mysql_num_rows($stmt) > 5) {
                        return true;
                    } else {
                        return false;
                    }
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            function login_check($conn) {
                // Check if all session variables are set 
                if (isset($_SESSION['user_id'], $_SESSION['login_string'])) {

                    $user_id = $_SESSION['user_id'];
                    $login_string = $_SESSION['login_string'];

                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];

                    $stmt = mysql_query("SELECT password FROM application_form_i WHERE sl_no = $user_id LIMIT 1");
                        if (mysql_num_rows($stmt) == 1) {
                            while($row = mysql_fetch_assoc($stmt)){
                            // If the user exists get variables from result.
                            $password = $row['password'];
                            }
                            $login_check = hash('sha512', $password . $user_browser);

                            if ($login_check == $login_string) {
                                // Logged In!!!! 
                                return true;
                            } else {
                                // Not logged in 
                                return false;
                            }
                        } else {
                            // Not logged in 
                            return false;
                        }
                } else {
                    // Not logged in 
                    return false;
                }
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            function esc_url($url) {

                if ('' == $url) {
                    return $url;
                }

                $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

                $strip = array('%0d', '%0a', '%0D', '%0A');
                $url = (string) $url;

                $count = 1;
                while ($count) {
                    $url = str_replace($strip, '', $url, $count);
                }

                $url = str_replace(';//', '://', $url);

                $url = htmlentities($url);

                $url = str_replace('&amp;', '&#038;', $url);
                $url = str_replace("'", '&#039;', $url);

                if ($url[0] !== '/') {
                    // We're only interested in relative links from $_SERVER['PHP_SELF']
                    return '';
                } else {
                    return $url;
                }
            }

            ?>

login.php

                <?php
                include_once 'functions.php';
                sec_session_start();

                if (login_check($conn) == true) {
                    $logged = 'in';
                    header("Location: ./successpage.php?form_no=$form_no");
                    exit;
                } else {
                    $logged = 'out';
                }
                ?>

提前致谢。

【问题讨论】:

    标签: php


    【解决方案1】:

    在使用会话变量之前,您需要使用 session_start();开始会话。在调用 session_start() 之前;如果有任何回显或打印,则可以显示错误“标头已发送”。所以一开始你可以调用 session_start();

    为了安全起见,您可以这样调用 if(!isset($_SESSION)) session_start();

    我看到代码中的第 4 行或第 5 行 $secure = SECURE;我认为 SECURE 不是像“SECURE”这样的字符串,或者它没有定义。请也检查一下。谢谢

    【讨论】:

    • 谢谢,但在调用函数 session_start() 之前我没有打印任何内容。但是,我正在调用函数 sec_session_start(),其中调用了 session_start()。那怎么了?
    猜你喜欢
    • 2015-06-29
    • 2013-02-28
    • 2014-03-22
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    相关资源
    最近更新 更多