PHP mysql以前声明的函数问题

时间:2013-10-16 18:43:26

标签: javascript php mysql function session

我会尽可能简短而甜蜜。

我有一个名为usernameget.php的脚本,它回显当前登录的用户名:

<?php 
include 'functions.php';
include 'db_connect.php';
sec_session_start();

$userId = $_SESSION['user_id'];

if(login_check($mysqli) == true) {

$con=mysqli_connect("localhost","myusername","mypass","mysqldb");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


$result = mysqli_query($con,"SELECT members.username FROM members WHERE id= $userId");

while ($row = mysqli_fetch_assoc($result)) 
{
   echo $row['username'];
}

/* free result set */
mysqli_free_result($result);

mysqli_close($con);

} else {
   echo 'Null User <br/>';
}

?>

此脚本使用functions.php(位于此处的安全登录脚本的一部分:http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL#Create_PHP_Functions)以便运行。 sec_session_start();只是一个自定义的session_start,但functions.php也可以通过$ user_id获取用户名。

问题是,当我在主页面中包含usernameget.php(它也使用functions.php来保护)时,它会抛出错误,因为它正在尝试重新声明sec_session_start();

我可以删除此安全性的usernameget.php,但显然因为它存在于functions.php / sec_session_start();之后它不起作用。我已经尝试编写一个特定的USERNAMEGETfunctions.php而没有用于usernameget.php的会话内容,但我不够熟练,无法让它工作,这感觉就像一个不优雅的解决方案。

据我所知:functions.php和sec_session_start();用于保护主页面,因此主页面上的包含不能使用functions.php或它会发生冲突。是否有人能够告诉我如何在不重新声明/冲突的情况下使用此脚本?

下面是整个functions.php

<?php
function sec_session_start() {
        $session_name = 'sec_session_id'; // Set a custom session name
        $secure = false; // Set to true if using https.
        $httponly = true; // This stops javascript being able to access the session id. 

        ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. 
        $cookieParams = session_get_cookie_params(); // Gets current cookies params.
        session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); 
        session_name($session_name); // Sets the session name to the one set above.
        session_start(); // Start the php session
        session_regenerate_id(); // regenerated the session, delete the old one.  
}




function login($email, $password, $mysqli) {
   // Using prepared Statements means that SQL injection is not possible. 
   if ($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1")) { 
      $stmt->bind_param('s', $email); // Bind "$email" to parameter.
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
      $stmt->fetch();
      $password = hash('sha512', $password.$salt); // hash the password with the unique salt.

      if($stmt->num_rows == 1) { // If the user exists
         // We check if the account is locked from too many login attempts
         if(checkbrute($user_id, $mysqli) == true) { 
            // Account is locked
            // Send an email to user saying their account is locked
            return false;
         } else {
         if($db_password == $password) { // Check if the password in the database matches the password the user submitted. 
            // Password is correct!


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

               $user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
               $_SESSION['user_id'] = $user_id; 
               $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
               $_SESSION['username'] = $username;
               $_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();
            $mysqli->query("INSERT INTO login_attempts (user_id, time) VALUES ('$user_id', '$now')");
            return false;
         }
      }
      } else {
         // No user exists. 
         return false;
      }
   }
}




function checkbrute($user_id, $mysqli) {
   // Get timestamp of current time
   $now = time();
   // All login attempts are counted from the past 2 hours. 
   $valid_attempts = $now - (2 * 60 * 60); 

   if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$valid_attempts'")) { 
      $stmt->bind_param('i', $user_id); 
      // Execute the prepared query.
      $stmt->execute();
      $stmt->store_result();
      // If there has been more than 5 failed logins
      if($stmt->num_rows > 5) {
         return true;
      } else {
         return false;
      }
   }
}




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

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

     if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) { 
        $stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
        $stmt->execute(); // Execute the prepared query.
        $stmt->store_result();

        if($stmt->num_rows == 1) { // If the user exists
           $stmt->bind_result($password); // get variables from result.
           $stmt->fetch();
           $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;
     }
   } else {
     // Not logged in
     return false;
   }
}

?>

2 个答案:

答案 0 :(得分:1)

不要将普通include用于核心函数库,这种函数库往往包含在所有脚本中。请改用include_once,以便PHP只包含一次文件,然后忽略任何进一步的包含尝试。这将阻止您的功能重新声明错误。

答案 1 :(得分:1)

您必须使用require_once而不是include_once,因为如果没有该文件,您的程序将无法运行...

include_once在尝试包含文件时发出警告并且失败。 在尝试包含它时,require_once会产生致命错误,并且失败。

对于核心库,您应该使用require_once。 (http://www.php.net/manual/pt_BR/function.require.php

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.