dongshun1884 2019-03-30 20:53
浏览 73

单击登录后网站崩溃 - 未捕获错误:在null上调用成员函数prepare()

I am trying to add the login function to my website, but when I clicked on the login button, the page crashes and gives the following error message:

/index.php - Uncaught Error: Call to a member function prepare() on null in /Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php:56

Stack trace:

0 /Users/xx/Documents/INFO2300/xxproject-3/includes/init.php(82): exec_sql_query(NULL, 'SELECT * FROM u...', Array)

1 /Users/xx/Documents/INFO2300/xx-project-3/includes/init.php(199): log_in('xx333', 'xx')

2 /Users/xxDocuments/INFO2300/xx333-project-3/index.php(2): include('/Users/xx/D...')

3 {main} thrown in /Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php on line 56

Here is my code for index.php:

<?php
    include("includes/init.php");
$db = open_or_init_sqlite_db('secure/gallery.sqlite', 'secure/init.sql');
$messages = array();

// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
const MAX_FILE_SIZE = 1000000;

// Users must be logged in to upload files!
if ( isset($_POST["submit_upload"]) && is_user_logged_in() ) {

  // TODO: filter input for the "box_file" and "description" parameters.
  // Hint: filtering input for files means checking if the upload was successful
  $upload_info=$_FILES["box_file"];
  $upload_desc=filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
  if ($upload_info['error']==UPLOAD_ERR_OK){
    $upload_name=basename($upload_info["name"]);
    $upload_ext = strtolower( pathinfo($upload_name, PATHINFO_EXTENSION) );

    $sql="INSERT INTO documents(user_id,file_name,file_ext,description)VALUES(:user_id,:file_name,:file_ext,:description)";
    $params=array(
      ':user_id' => $current_user['id'],
      ':file_name'=> $upload_name,
      ':file_ext'=>$upload_ext,
      ':description'=>$upload_desc,
    );
    $result=exec_sql_query($db, $sql, $params);

    if ($result){
      $file_id=$db->lastInsertId("id");
      $new_path="uploads/documents/$file_id.$upload_ext";
      move_uploaded_file($upload_info["tmp_name"],$new_path);
    }
}

  // TODO: If the upload was successful, record the upload in the database
  // and permanently store the uploaded file in the uploads directory.
  // $box_file=filter_input(INPUT_POST, "box_file", FILTER_SANITIZE_STRING);
  // $description=filter_input(INPUT_POST,"description", FILTER_SANITIZE_STRING);
}
?>
<!DOCTYPE html>
<html>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<title>Home</title>
<link rel="stylesheet" type="text/css" href="style/all.css" media="all" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
</head>


<body>
<h1>Fine Art Photography</h1>

  <div id="content-wrap">

    <?php
    // If the user is logged in, let them upload files and view their uploaded files.
    if ( is_user_logged_in() ) {

      foreach ($messages as $message) {
        echo "<p><strong>" . htmlspecialchars($message) . "</strong></p>
";
      }
      ?>

      <h2>Upload a File</h2>

      <!-- TODO: Peer review this form checking to make sure it properly supports file uploads. -->
      <form id="uploadFile" action="index2.php" method="post" enctype="multipart/form-data">
        <ul>
          <li>
            <!-- MAX_FILE_SIZE must precede the file input field -->
            <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />

            <label for="box_file">Upload File:</label>
            <input id="box_file" type="file" name="box_file">
          </li>
          <li>
            <label for="box_desc">Description:</label>
            <textarea id="box_desc" name="description" cols="40" rows="5"></textarea>
          </li>
          <li>
            <button name="submit_upload" type="submit">Upload File</button>
          </li>
        </ul>
      </form>


      <?php
    } else {
      ?>
      <p><strong>You need to sign in before you can upload image.</strong></p>

      <?php
      include("includes/login.php");
    }
    ?>
<!-- <h2>Saved Files</h2> -->

<h2>Categories</h2>
<h2>Photos</h2>

<div class="img">
  <?php
  $records = exec_sql_query($db, "SELECT * FROM images")->fetchAll(PDO::FETCH_ASSOC);
  if (count($records) > 0) {
      foreach($records as $record) {
          echo "<div class=\"content\">";
          echo "<div class=\"block\">";
          echo "<img class=\"pic\" src=\"uploads/images/". $record["id"] . "." . $record["image_ext"]. "\"/>";
          echo "<a href=\"uploads/images/". $record["id"] . "." . $record["image_ext"] .
          "\"class=\"link\">" . htmlspecialchars($record["image_name"]) . "</a>";
          echo "<p class=\"link\">" . htmlspecialchars($record["description"]). "</p>";
          echo "</div>";
          echo "</div>";

      }
  }

  ?>
  </div>


</body>

</html>

And here is my code for init.php:

<?php
// vvv DO NOT MODIFY/REMOVE vvv

// check current php version to ensure it meets 2300's requirements
function check_php_version()
{
  if (version_compare(phpversion(), '7.0', '<')) {
    define(VERSION_MESSAGE, "PHP version 7.0 or higher is required for 2300. Make sure you have installed PHP 7 on your computer and have set the correct PHP path in VS Code.");
    echo VERSION_MESSAGE;
    throw VERSION_MESSAGE;
  }
}
check_php_version();

function config_php_errors()
{
  ini_set('display_startup_errors', 1);
  ini_set('display_errors', 0);
  error_reporting(E_ALL);
}
config_php_errors();

// open connection to database
function open_or_init_sqlite_db($db_filename, $init_sql_filename)
{
  if (!file_exists($db_filename)) {
    $db = new PDO('sqlite:' . $db_filename);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if (file_exists($init_sql_filename)) {
      $db_init_sql = file_get_contents($init_sql_filename);
      try {
        $result = $db->exec($db_init_sql);
        if ($result) {
          return $db;
        }
      } catch (PDOException $exception) {
        // If we had an error, then the DB did not initialize properly,
        // so let's delete it!
        unlink($db_filename);
        throw $exception;
      }
    } else {
      unlink($db_filename);
    }
  } else {
    $db = new PDO('sqlite:' . $db_filename);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $db;
  }
  return null;
}

function exec_sql_query($db, $sql, $params = array())
{
  $query = $db->prepare($sql);
  if ($query and $query->execute($params)) {
    return $query;
  }
  return null;
}
// ^^^ DO NOT MODIFY/REMOVE ^^^

// You may place any of your code here.

//  $db = open_or_init_sqlite_db('secure/site.sqlite', 'secure/init.sql');

 define('SESSION_COOKIE_DURATION', 60*60*1);
 $session_messages = array();

 function log_in($username, $password) {
   global $db;
   global $current_user;
   global $session_messages;

   if ( isset($username) && isset($password) ) {
     // check if username exists in the database
     $sql = "SELECT * FROM users WHERE username = :username;";
     $params = array(
       ':username' => $username
     );
     $records = exec_sql_query($db, $sql, $params)->fetchAll();
     if ($records) {
       // There shouldn't be repetitive username.
       $account = $records[0];

       // Check if password is correct
       if ( password_verify($password, $account['password']) ) {
         // Create session
         $session = session_create_id();

         // Store session ID in database
         $sql = "INSERT INTO sessions (user_id, session) VALUES (:user_id, :session);";
         $params = array(
           ':user_id' => $account['id'],
           ':session' => $session
         );
         $result = exec_sql_query($db, $sql, $params);
         if ($result) {
           // If result exists, session stored in DB

           // Send this back to the user.
           setcookie("session", $session, time() + SESSION_COOKIE_DURATION);

           $current_user = $account;
           return $current_user;
         } else {
           array_push($session_messages, "Log in failed. Something went wrong");
         }
       } else {
         array_push($session_messages, "Invalid username or password.");
       }
     } else {
       array_push($session_messages, "Invalid username or password.");
     }
   } else {
     array_push($session_messages, "No username or password given.");
   }
   $current_user = NULL;
   return NULL;
 }

 function find_user($user_id) {
   global $db;

   $sql = "SELECT * FROM users WHERE id = :user_id;";
   $params = array(
     ':user_id' => $user_id
   );
   $records = exec_sql_query($db, $sql, $params)->fetchAll();
   if ($records) {
     // users are unique, there should only be 1 record
     return $records[0];
   }
   return NULL;
 }

 function find_session($session) {
   global $db;

   if (isset($session)) {
     $sql = "SELECT * FROM sessions WHERE session = :session;";
     $params = array(
       ':session' => $session
     );
     $records = exec_sql_query($db, $sql, $params)->fetchAll();
     if ($records) {
       // No repetitive sessions
       return $records[0];
     }
   }
   return NULL;
 }

 function session_login() {
   global $db;
   global $current_user;

   if (isset($_COOKIE["session"])) {
     $session = $_COOKIE["session"];

     $session_record = find_session($session);

     if ( isset($session_record) ) {
       $current_user = find_user($session_record['user_id']);

       // The session will last for 1 more hour
       setcookie("session", $session, time() + SESSION_COOKIE_DURATION);

       return $current_user;
     }
   }
   $current_user = NULL;
   return NULL;
 }

 function is_user_logged_in() {
   global $current_user;

   // if $current_user is not NULL, then a user is logged in.
   return ($current_user != NULL);
 }

 function log_out() {
   global $current_user;

   // Remove the session from the cookie and fgo back in time to expire the session.
   setcookie('session', '', time() - SESSION_COOKIE_DURATION);
   $current_user = NULL;
 }

 // ---- Check for login, logout requests. Or check to keep the user logged in. ----

 // Check if we should login the user
 if ( isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password']) ) {
   $username = trim( $_POST['username'] );
   $password = trim( $_POST['password'] );

   log_in($username, $password);
 } else {
   // check if the user already logged in
   session_login();
 }

 // Check if we should logout the user
 if ( isset($current_user) && ( isset($_GET['logout']) || isset($_POST['logout']) ) ) {
   log_out();
 }

 ?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 stm32代码移植没反应
    • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
    • ¥100 连续两帧图像高速减法
    • ¥15 组策略中的计算机配置策略无法下发
    • ¥15 如何绘制动力学系统的相图
    • ¥15 对接wps接口实现获取元数据
    • ¥20 给自己本科IT专业毕业的妹m找个实习工作
    • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
    • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
    • ¥50 mac mini外接显示器 画质字体模糊