2014-09-24 125 views
0

我對php編程非常陌生。我已經寫了一個註冊html文件,用戶輸入他的電子郵件和密碼。如果用戶已經註冊,我正在重定向到登錄屏幕,如果用戶是新用戶,我堅持數據庫。現在,如果用戶輸入了錯誤的密碼,他將再次被重定向到登錄屏幕,但這次我想在屏幕上顯示一條消息,輸入的密碼不正確。當用戶直接導航到登錄屏幕時,登錄屏幕不應顯示消息。在php中顯示服務器錯誤消息

的代碼片段如下:

<?php 
     define('DB_HOST', 'hostname'); 
     define('DB_NAME', 'db_name'); 
     define('DB_USER','username'); 
     define('DB_PASSWORD','password'); 
     $con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); 

     $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); 

     function NewUser() { 
     $email = $_POST['email']; 
     $password = $_POST['password']; 
     $query = "INSERT INTO WebsiteUsers (email,pass) VALUES ('$email','$password')"; 

     $data = mysql_query ($query)or die(mysql_error()); 
     if($data) { 
      header('Location: reg-success.html'); 
     } 
     } 

     function SignUp() { 
     if(!empty($_POST['email'])){ 
      $emailQuery = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]'"); 
      if($row = mysql_fetch_array($emailQuery)) { 
      $query = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]' AND pass = '$_POST[password]'"); 
      if($row = mysql_fetch_array($query)) { 
       echo 'validated user. screen that is accessible to a registered user'; 
      }else{ 
      echo 'Redirect to the sign in screen with error message'; 
      } 
     }else{ 
      NewUser(); 
     } 
     } 
     } 
if(isset($_POST['submit'])) 
{ 
    SignUp(); 
} 
?> 

請讓我知道如何使用PHP

+0

無關的注意:您的代碼*對SQL注入攻擊廣泛開放。你可能想開始閱讀這裏:http://php.net/manual/en/security.database.sql-injection.php – David 2014-09-24 16:46:54

+2

有**沒有更多的支持** mysql_ *'功能,他們是[* *正式棄用**](https://wiki.php.net/rfc/mysql_deprecation),**不再維護**,並將[**刪除**](http://php.net/manual/ en/function.mysql-connect.php#warning)。您應該使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/mysqli)更新您的代碼,以確保您的項目未來的功能。 – Kermit 2014-09-24 16:47:23

+0

一個簡單的解決方案是在查詢字符串中傳遞錯誤消息,如'?error = 1&message = Invalid%20Login' 然後檢查'$ _GET' params – 2014-09-24 16:47:48

回答

1

這裏得到這個實現是幾個類,可以幫助你預防注射黑客加上讓你去關於如何做一般你想做的事情。如果您爲任務創建類,則可以更輕鬆地在別處重用您的代碼。我個人喜歡PDO方法來連接並從數據庫中獲取信息(您將希望查找「綁定」以幫助進一步防止注入攻擊),但這將有助於降低基礎知識。這是非常粗糙的,你會想擴大到創建一些錯誤報告和更多可用的功能。

<?php 
    error_reporting(E_ALL); 
    // Create a simple DB engine 
    class DBEngine 
     { 
      protected $con; 
      // Create a default database element 
      public function __construct($host = '',$db = '',$user = '',$pass = '') 
       { 
        try { 
          $this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING)); 
         } 
        catch (Exception $e) { 
          return 0; 
         } 
       } 

      // Simple fetch and return method 
      public function Fetch($_sql) 
       { 
        $query = $this->con->prepare($_sql); 
        $query->execute(); 

        if($query->rowCount() > 0) { 
          $rows = $query->fetchAll(); 
         } 

        return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0; 
       } 

      // Simple write to db method 
      public function Write($_sql) 
       { 
        $query = $this->con->prepare($_sql); 
        $query->execute(); 
       } 
     } 

    // Your user controller class 
    class UserControl 
     { 
      public $_error; 
      protected $db; 
      // Save the database connection object for use in this class 
      public function __construct($db) 
       { 
        $this->_error = array(); 
        $this->db  = $db; 
       } 

      // Add user to DB 
      protected function Add() 
       { 
        $email  = htmlentities($_POST['email'],ENT_QUOTES); 
        // Provided you have a php version that supports better encryption methods, use that 
        // but you should do at least a very basic password encryption. 
        $password = hash('sha512',$_POST['password']); 
        // Use our handy DBEngine writer method to write your sql 
        $this->db->Write("INSERT INTO WebsiteUsers (`email`,`pass`) VALUES ('$email','$password')"); 
       } 

      // Fetch user from DB 
      protected function Fetch($_email = '') 
       { 
        $_email  = htmlentities($_email,ENT_QUOTES); 
        $password = hash('sha512',$_POST['password']); 
        // Use our handy DBEngine fetcher method to check your db 
        $_user  = $this->db->Fetch("SELECT * FROM WebsiteUsers WHERE email = '$_email' and password = '$password'"); 
        // Return true if not 0 
        return ($_user !== 0)? 1:0; 
       } 

      // Simple fetch user or set user method 
      public function execute() 
       { 
        // Check that email is a valid format 
        if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { 
          // Save the true/false to error reporting 
          $this->_error['user']['in_db'] = $this->Fetch($_POST['email']); 
          // Asign short variable 
          $_check = $this->_error['user']['in_db']; 

          if($_check !== 1) { 
            // Add user if not in system 
            $this->Add(); 
            // You'll want to expand your add feature to include error reporting 
            // This is just returning that it made it to this point 
            $this->_error['user']['add_db'] = 1; 
           } 
          else { 
            // Run some sort of login script 
           } 
          // Good email address 
          $this->_error['email']['validate'] = 1; 
         } 
        else 
         // Bad email address 
         $this->_error['email']['validate'] = 0; 
       } 
     } 

// $_POST['submit'] = true; 
// $_POST['email']  = 'jenkybad<script>email'; 
// $_POST['password'] = 'mypassword'; 

    if(isset($_POST['submit'])) { 
     // Set up a db connection 
     $db  = new DBEngine('hostname','dbname','dbuser','dbpass'); 
     // Create instance of your user control 
     $_user = new UserControl($db); 
     // Execute instance 
     $_user->execute(); 

     // Check for basic erroring 
     print_r($_user->_error); 
    } ?>