2016-05-06 6 views
-1

私はPHPを初めて使用しているので、次のコードが機能しない理由を知ることができません。これは簡単なはずですが、私はこれを理解できません。このコードはエラーを発生させず、phpAdmin SQLコンソールでSQL文が正しいことを示します。私はウェブ& StackOverflowを検索しましたが、良い答えが見つかりません。どうしましたか? すべてのユーザー(データベース内であろうとなかろうと)は無視され、ログインページではスタックされます。PHPログインコードが機能せず、ユーザーがログインページに固執しています

<?php 
session_start(); 

//create function to check login form for admin or other type of user.  
//Redirect the admin user to the welcome page. 

function login() 
    { 
     //strip login and password using in-build htmlspecialchars function 
     $value1 = htmlspecialchars($_POST['login']); 
     $value2 = htmlspecialchars($_POST['password']);  

     //set variables for the db connection 
     $servername = "localhost"; 
     $username = "root"; 
     $password = ""; 
     $dbname = "mydb"; 
     $loggedin = ''; 

     //Create new connection to db    
     $conn = new mysqli($servername, $username, $password, $dbname); 

     //Check connection and handle any error 
     if ($conn->connect_error) { 
      die("Connection failed: " . $conn->connect_error); 
      header('Locatin: login.php'); 
     } 
     else {    
      //check if super admin user exists in db  
      $sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1"; 
      $result = mysqli_query($conn,$sql); 

      //check to see if query returns any rows 
      if(mysql_num_rows(($result) > 0) { 
       include 'welcome.php'; 
      } 

      //check if the password and username match 
      if(($username === $value1) && ($password === $value2)) { 
       $_SESSION['loggedin'] = TRUE; 
       echo "Hello ".$value1.", you are logged in!<br>"; 
      } 
      //send user error message if login/username and password wrong 
      else { 
       echo "Incorrect username or password<br>"; 
       include 'login.php'; 
      } 

      //close the db connection    
      $conn->close(); 
     } 
?> 

ログインフォーム:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>Admin Login</title> 
<script> 

//function to check the form 
function chkForm() 
    { 
     //determine the number of elements in the user login form 
     var intFormLen = document.forms[0].elements.length; 

     //loop through the form fields to see that a value has been input 
     for (var i = 0; i < intFormLen; i++) { 
      if (document.forms[0].elements[i].value == "") { 
       //send user an error message if login field empty 
       document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field"; 
       document.forms[0].elements[i].focus();         
       return false; 
      } 
     } 

     //clear the form fields 
     function clearWarn(fieldName) 
      { 
       document.getElementById(fieldName).innerHTML = "";     
       return true; 
      } 

     return; 
    } 
</script> 
</head> 
<body> 
<h2>Admin Login</h2>   
<div class="phpEcho"> 
    <div class="formLayout"> 
     <form action="#" method="post" onsubmit="return chkForm();"> 
      <label for="login">Login:</label> 
      <input type="text"name="login" onchange="return clearWarn('fieldName')"> 
      <div id="login" style="color:red"></div><br> 
      <label for="password">Password:</label> 
      <input type="password" name="password" onchange="return clearWarn('fieldName')"> 
      <div id="password" style="color:red"></div><br><br> 
      <input type="submit" name="cmdSubmit" value="Log in"> 
     </form> 
    </div> 
</div> 
</body> 
</html> 
+0

'$ username'と' $ password'は間違った値ですか、いいえ?あなたはユーザーアカウントとdbの値をチェックしたいのですが、それとも... "welcome.php"には何がありますか? – chris85

+0

PHPスクリプトはどのセッションが使用されているかをどのように知っていますか?各JQuery AJAXリクエストに渡されますか? –

+0

@JuliePelletier jQueryはどこですか? – chris85

答えて

0

あなたのform action="#"を設定し、JavaScriptでそれを提出しないでください。

Jasonが指摘したように、chkForm()はtrueを返さないため、フォームの送信が妨げられます。

+0

ありがとうございました。私はこれらの提案を試みます。 – seaellen

+1

ありがとうございました! – seaellen

0

このスクリプトには、対処すべき多くの問題があります。

1)私は再利用可能な要素とセッションを含むドキュメントにいくつかの種類のconfig/bootstrapファイルを使用することをお勧めします。必須/包含は一度だけです。

/config.php

define("_DS_",DIRECTORY_SEPARATOR); 
define("DBUSER",'root'); 
define("DBPASS",''); 
define("DBHOST",'localhost'); 
define("DBDATABASE",'mydb'); 
// Start session 
session_start(); 

2)あなたは、クラス別や機能別かどうか、重要なのは、データベース接続、あなたの機能を分離することになるでしょう。タスクを別々にしておくことで、再利用が容易になります。ここで

は(私はそれに慣れていますが、原理は同じであるため、PDOを使用するつもりです)の例である:

/functions/connection.php

function connection() 
    { 
     // This is just a really basic connection, one could expand on this 
     return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS); 
    } 

/機能/ login.php

/* 
** @param $username [string] by making this a param, you can manually log in users outside of POST 
** @param $password [string] same as username 
** @param $conn [resource] You will want to inject your connection into this 
**       in order to use it. Don't make the connection 
**       inside. May as well reuse resources already active 
** @return [bool] If you return TRUE or FALSE, that will tell your script 
**    whether the login succeeded or failed for notification 
*/ 

function login($username,$password,$conn) 
    { 
     // Don't worry about stripping down the username/pass, just bind 
     // the username and match the password 
     // You need to select from your user table (or whatever table 
     // you are storing your usernames for your site) 
     $query = $conn->prepare("select * from `users` where `username` = :0"); 
     $query->execute(array(':0'=>$username)); 
     $result = $query->fetch(PDO::FETCH_ASSOC); 
     if(empty($result)) 
      return false; 
     // You will want to use password_hash to save passwords 
     if(!password_verify($password,$result['password'])) 
      return false; 
     // I use htmlspecialchars here so I don't forget when echoing to page 
     // but you can do it at the time you echo to browser 
     $_SESSION['first_name'] = htmlspecialchars($result['first_name']); 
     //etc.... 
     return true; 
    } 

使用するには:

クライアント側の検証のために

/index.php

// Include our soon-to-be-used files 
require_once(__DIR__._DS_.'config.php'); 
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php'); 
require_once(__DIR__._DS_.'functions'. _DS_.'login.php'); 

// Set connection 
$con = connection(); 

// See if a post has been made 
if(isset($_POST['login'])) { 
    $loggedin = login($_POST['login'],$_POST['password'],$con); 
} 

// If the login attempt made 
if(isset($loggedin)) { 
    // If successful 
    if($loggedin) { 
     header('Location: welcome.php'); 
     exit; 
    } 
    else 
     // If failed, you can note in a variable an echo in the html section 
     $error = 'Login failed'; 
} 

、私はjQueryの検証を示唆している、それは簡単だし、非常によく動作します。

+0

ありがとう! – seaellen

関連する問題