php - 每次输入PHP代码时页面崩溃

标签 php mysql

不太确定这里发生了什么,但是每次我在页面中输入代码时它都会崩溃,我试图从我的 mysql 表中提取数据,每次它都会崩溃。我尝试了几段代码以及不同的位置

在页面的最顶部:

include 'dbc.php';
page_protect();

 $query = "
        SELECT
            id,
            user_name,
            suta,
        FROM users
    ";

    try
    {
        $stmt = $db->prepare($query);
        $stmt->execute();
    }
    catch(PDOException $ex)
    {
        die("Failed to run query: " . $ex->getMessage());
    }
    $rows = $stmt->fetchAll();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Account Page</title>

以及我想要显示数据的正文:

<div id="memdocs">

            <p>Pending Documents</p>

    <?php

     $query = "
            SELECT
                id,
                user_name,
                suta,
            FROM users
        ";

        try
        {
            $stmt = $db->prepare($query);
            $stmt->execute();
        }
        catch(PDOException $ex)
        {
            die("Failed to run query: " . $ex->getMessage());
        }
        $rows = $stmt->fetchAll();
    ?>
        <p><?php echo htmlentities($rows['user_name'], ENT_QUOTES, 'UTF-8'); ?></p>
        <p><?php echo htmlentities($rows['suta'], ENT_QUOTES, 'UTF-8'); ?></p>



            </div>  

这里是页面保护功能

function page_protect() {
session_start();

global $db; 

/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
    {
        logout();
        exit;
    }
}

dbc.php

<?php


define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", "trin6_slogin"); // set database user
define ("DB_PASS","Father11!!"); // set database password
define ("DB_NAME","trin6_slogin"); // set database name

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

/* Registration Type (Automatic or Manual) 
 1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
 0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1;  // set 0 or 1

define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password

//define ("ADMIN_NAME", "admin"); // sp

/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);




/**** PAGE PROTECT CODE  ********************************
This code protects pages to only logged in users. If users have not logged in then it will redirect to login page.
If you want to add a new page and want to login protect, COPY this from this to END marker.
Remember this code must be placed on very top of any html or php page.
********************************************************/

function page_protect() {
session_start();

global $db; 

/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
    {
        logout();
        exit;
    }
}

// before we allow sessions, we need to check authentication key - ckey and ctime stored in database

/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) ) 
{
    if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){
    /* we double check cookie expiry time against stored in database */

    $cookie_user_id  = filter($_COOKIE['user_id']);
    $rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
    list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
    // coookie expiry
    if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {

        logout();
        }
/* Security check with untrusted cookies - dont trust value stored in cookie.       
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/

     if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey)  ) {
          session_regenerate_id(); //against session fixation attacks.

          $_SESSION['user_id'] = $_COOKIE['user_id'];
          $_SESSION['user_name'] = $_COOKIE['user_name'];
        /* query user level from database instead of storing in cookies */  
          list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));

          $_SESSION['user_level'] = $user_level;
          $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);

       } else {
       logout();
       }

  } else {
    header("Location: login.php");
    exit();
    }
}
}



function filter($data) {
    $data = trim(htmlentities(strip_tags($data)));

    if (get_magic_quotes_gpc())
        $data = stripslashes($data);

    $data = mysql_real_escape_string($data);

    return $data;
}



function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}

function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}

function ChopStr($str, $len) 
{
    if (strlen($str) < $len)
        return $str;

    $str = substr($str,0,$len);
    if ($spc_pos = strrpos($str," "))
            $str = substr($str,0,$spc_pos);

    return $str . "...";
}   

function isEmail($email){
  return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}

function isUserID($username)
{
    if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
        return true;
    } else {
        return false;
    }
 }  

function isURL($url) 
{
    if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
        return true;
    } else {
        return false;
    }
} 

function checkPwd($x,$y) 
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }

if (strcmp($x,$y) != 0) {
 return false;
 } 
return true;
}

function GenPwd($length = 7)
{
  $password = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels

  $i = 0; 

  while ($i < $length) { 


    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);


    if (!strstr($password, $char)) { 
      $password .= $char;
      $i++;
    }

  }

  return $password;

}

function GenKey($length = 7)
{
  $password = "";
  $possible = "0123456789abcdefghijkmnopqrstuvwxyz"; 

  $i = 0; 

  while ($i < $length) { 


    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);


    if (!strstr($password, $char)) { 
      $password .= $char;
      $i++;
    }

  }

  return $password;

}


function logout()
{
global $db;
session_start();

$sess_user_id = strip_tags(mysql_real_escape_string($_SESSION['user_id']));
$cook_user_id = strip_tags(mysql_real_escape_string($_COOKIE['user_id']));

if(isset($sess_user_id) || isset($cook_user_id)) {
mysql_query("update `users` 
            set `ckey`= '', `ctime`= '' 
            where `id`='$sess_user_id' OR  `id` = '$cook_user_id'") or die(mysql_error());
}       

/************ Delete the sessions****************/
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy(); 

/* Delete the cookies*******************/
setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");

header("Location: login.php");
}

// Password and salt generation
function PwdHash($pwd, $salt = null)
{
    if ($salt === null)     {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    }
    else     {
        $salt = substr($salt, 0, SALT_LENGTH);
    }
    return $salt . sha1($pwd . $salt);
}

function checkAdmin() {

if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}

}

?>

我做错了什么吗?这也不是我尝试过的唯一代码..请有人指出我正确的方向

最佳答案

在 dbc.php

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

在您的代码中

try
{
    $stmt = $db->prepare($query);
    $stmt->execute();
}
catch(PDOException $ex)
{
    die("Failed to run query: " . $ex->getMessage());
}

您正在将(已弃用的)mysql_* 函数与 PDO 混合使用;此外,mysql_select_db()只是选择数据库并返回一个 bool 值,因此$db->prepare()相当于true->prepare() 这就是为什么您会收到有关 $db 不是对象的错误。

尝试将 dbc.php 中的连接设置更改为:

try {
    $sDSN = "mysql:dbname=" . DB_NAME. ";host= " . DB_HOST;
    $db = new PDO($sDSN, DB_USER, DB_PASS);
}

catch(PDOException $e) {
    die($e->getMessage());
}

关于php - 每次输入PHP代码时页面崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401240/

相关文章:

php - SoapFault 异常 : Could not connect to host

PHP 和 MySQL,获取 JSON 数据以提供 HighCharts

mysql - 通过一次查询获取最后订单日期、订单总数和总金额?

mysql - 在 MySQL 中按首字母选择最大数字组

php - 如何在子域上重写 Slim 的 url

php - 使用 PHP QrCode 生成二​​维码

php - 递归地倍数 foreach 或 RecursiveIteratorIterator

php - 使用 PHP 使用 HTML 表单在新页面中编辑填充有 MySQL 数据库的 HTML 表行

mysql - 如何使用值填充 MySQL 表中的一列而不出现 "Not all parameters were used"编程错误?

mysql - 如何使用 GUI 在两台运行 Windows 的未连接 PC 之间迁移 mysql 数据库