2017-11-13 1 views
0

텍스트 파일의 문자열 목록을 스크롤하고 각 문자열을 HTML 양식의 사용자 입력과 비교하는 PHP 스크립트를 작성하려고합니다. 일치하는 항목이 있으면 사용자가 입력 한 문자열을 화면에 게시해야합니다. 어떻게 든 두 문자열의 비교는 동일한 문자열이 있더라도 일치하는 문자열을 생성하지 않습니다. 여기 PHP 스크립트가 일치하는 문자열을 인식하지 못합니다.

는 HTML 코드

<html> 
<head></head> 
<body> 
<form action="myshopping.php" method="post"> 
Log in with User ID: 
<input type="text" name="userid"> 
<br> 
<input type="submit"> 
<br> 
Sign up for a brand new account: 
<input type="text" name="originaluserid"> 
<br> 
<input type="submit"> 
</form> 

</body> 
</html> 

PHP 코드 여기

<?php 
session_start(); 
$myFile = "usernamelist.txt"; 

if (isset($_POST['originaluserid'])){//verifies the creation user input from the html page(for users signing up for the first time) 
    $userid = $_POST['originaluserid'] . PHP_EOL; 
    $fh = fopen($myFile, 'a') or die("can't open file");  
    fwrite($fh, $userid); 
} 

if(isset($_POST['userid'])){//verifies the existence of username information for an old user logging back in 
    $userid = $_POST['userid']; 
    $fh = fopen($myFile, 'r'); 
} 

$theData = fgets($fh); 

$_SESSION['id'] = $userid;//so that userid can be called in another page 

if ($fh) { 
    while (($line = fgets($fh)) !== false) { 
     if($userid == $theData){//errors in matching input with collected data in text file 
      echo "<html> 
      <head></head> 
      <body> 
      <p>the ID of the user is: $userid</p> <!--I want userid to be displayed here--> 
      <p>welcome to My Shopping Page</p> 
      </body> 
      </html>"; 
      exit; 
     } 
    } 
    fclose($fh); 
} else { 
    echo "error"; 
    exit; 
} 

echo "access not granted"; 
?> 

되어 있으며 모든 텍스트 파일 ("usernamelist.txt")에 있습니다 :

username1 
username2 
username3 
username4 
+0

사실 거기에는 개행과 캐리지 리턴과 같은 일부 숨겨진 문자가 있습니다. 'if ($ userid == trim ($ theData))' –

+2

이것은 DB를 사용하면 훨씬 쉽습니다. – chris85

+0

루프에서 fgets를'$ line'으로 되 돌렸지 만'$ userid'를'$ theData'와 대조하여 검사합니다. 그게 네가하려는 의도 야? –

답변

3

우선 $line 변수 대신 $theData 변수를 사용하고 있습니다. 또한 fgets은 줄 바꿈을 포함하여 공백 문자를 제거하지 않으므로 trim을 사용해야합니다. 이 시도하고 그것이 작동하는지 확인 :

if (trim($userid) == trim($line)) { 

당신은 또한 첫 번째 줄을 가져 오는 있기 때문에 $theData = fgets($fh);를 제거해야하고 그것이 위의 논리를 검사하지 않습니다.

+3

'$ theData = fgets ($ fh);도 제거해야한다. 그렇지 않으면 이름과 결코 일치하지 않을 것이다. – AbraCadaver

+0

@AbraCadaver - 좋은 지적 – DataHerder

+0

좋은 눈'(';.;')' –

관련 문제