PHP 2-мерный массив неопределенная ошибка смещения - PullRequest
0 голосов
/ 21 октября 2019

Я новичок в php, и я создал веб-страницу для ввода имени пользователя и пароля, а затем сравнил их со списком сохраненных, чтобы предоставить или запретить доступ к сайту. Мой код работает правильно для того, что я разработал, но я получаю неопределенные ошибки смещения.

<html lang="en">
<head>
    <title>Insecure System</title>
</head>
<body>
    <?php
        // read file and set text to string
        $myFile = fopen("includes/users.txt","r");
        $content = fread($myFile,filesize("includes/users.txt"));
        fclose($myFile);

        // set string to two dimensional array
        $contentArray = explode("||>><<||",$content);
        foreach ($contentArray as $cArr) {
            $contentArray2[] = explode(",",$cArr);
        }
        //print_r($contentArray2);

        // retrieve user input values
        if (isset($_POST['user']) && isset($_POST['pass'])) {
            $enteredUser = $_POST['user'];
            $enteredPass = $_POST['pass'];


            // if statements to check user/pass combo
            for ($i=0;$i<=sizeof($contentArray2);$i++) {
                for ($i2=0;$i2<=sizeof($contentArray2[$i]);$i2++) {
                    if ($contentArray2[$i][$i2] == $enteredUser) {
                        $i2++;
                        if ($contentArray2[$i][$i2] == $enteredPass) {
                            echo "Access Granted";
                            break 2;
                        }
                        else {
                            echo "Access Denied"; 
                            break 2;
                        }
                    }
                    else continue;
                }
            }
        }
    ?>
    <form action="index.php" method="post">
        <input type="text" placeholder="Username" name="user">
        <input type="text" placeholder="Password" name="pass">
        <input type="submit" value="Submit">
        <input type="reset" value="Reset">
    </form>
</body>
</html>

Содержимое users.txt:

beavis,password||>><<||butthead,password2||>><<||dana,alien||>><<||fox,believe

Вывод результирующей ошибки: Не определеносмещение: 2 в index.php в строке 29

Строка 29 ссылается на эту строку в коде: if ($contentArray2[$i][$i2] == $enteredUser) {

Значение $ contentArray2: Array ( [0] => Array ( [0] => beavis [1] => password ) [1] => Array ( [0] => butthead [1] => password2 ) [2] => Array ( [0] => dana [1] => alien ) [3] => Array ( [0] => fox [1] => believe ) )

Ответы [ 4 ]

0 голосов
/ 21 октября 2019

Вы можете попробовать

<html lang="en">
    <head>
        <title>Insecure System</title>
    </head>
    <body>
        <?php
            // read file and set text to string
            $myFile = fopen("users.txt","r");
            $content = fread($myFile,filesize("users.txt"));
            fclose($myFile);

            // set string to two dimensional array
            $contentArray = explode(" ",$content);

            foreach ($contentArray as $key => $cArr) {
                $contentArray2[] = explode("||>><<||",$cArr);
            }

            if (isset($_POST['user']) && isset($_POST['pass'])) {
                $enteredUser = $_POST['user'];
                $enteredPass = $_POST['pass'];
                $flag = 0;
                foreach($contentArray2 as $value){
                    if(trim($value[0]) == trim($enteredUser) && trim($value[1]) == trim($enteredPass)){
                        echo "Access Granted";
                        break;
                    }else{
                        $flag = 1;
                    }
                }

                if($flag != 0){
                    echo 'Denied'; die;
                }
            }
        ?>
        <form action="" method="post">
            <input type="text" placeholder="Username" name="user">
            <input type="text" placeholder="Password" name="pass">
            <input type="submit" value="Submit">
            <input type="reset" value="Reset">
        </form>
    </body>
    </html>

поместить этот (shariful||>><<||123456 kabir||>><<||12345678 jack||>><<||987654) текст в файл users.txt

0 голосов
/ 21 октября 2019

Хотя вы решили свою проблему, я хотел показать альтернативный способ сделать это.

Основная идея заключается в том, чтобы не делать так много промежуточных шагов. Пока вы читаете файл, почему бы не проверить имя пользователя и пароль на этом этапе?

Пара других вещей - используйте file_get_contents() как сокращение для fopen/fread/fclose и читайте файл, только если вы собираетесьиспользовать его (внутри основного if)

if (isset($_POST['user']) && isset($_POST['pass'])) {
    $enteredUser = $_POST['user'];
    $enteredPass = $_POST['pass'];

    //read file and set text to string
    $content = file_get_contents("a.csv");

    // set string to two dimensional array
    $users = [];
    foreach ( explode("||>><<||",$content) as $user )   {
        list($name, $password) = explode(",", $user, 2);
        // If the user matches
        if ($enteredUser == $name )  {
            // Output depending on password matching
            if ($enteredPass == $password) {
                echo "Access Granted";
            }
            else {
                echo "Access Denied";
            }
            // Exit loop as checked user
            break;
        }
    }

}
0 голосов
/ 21 октября 2019

Вы также можете создать ассоциативный массив с именем пользователя и паролем, чтобы сделать его доступным простым, если * предоставлен.

$myFile = fopen("includes/users.txt","r");
$content = fread($myFile,filesize("includes/users.txt"));
fclose($myFile);

// set string to two dimensional array
$contentArray = explode("||>><<||",$content);
foreach ($contentArray as $cArr) {
     $temp = explode(",",$cArr);
     $contentArray2[$temp[0]] = $temp[1];
}
//print_r($contentArray2);

// retrieve user input values
if (isset($_POST['user']) && isset($_POST['pass'])) {
     $enteredUser = $_POST['user'];
     $enteredPass = $_POST['pass'];       

     if($contentArray2[$enteredUser] === $enteredPass){ 
         echo "Access Granted";
     }else{
         echo "Access denied";
     }
}

или, возможно, даже проще. Сделайте in_array на username,password

$myFile = fopen("includes/users.txt","r");
$content = fread($myFile,filesize("includes/users.txt"));
fclose($myFile);

// retrieve user input values
if (isset($_POST['user']) && isset($_POST['pass'])) {
     $enteredUser = $_POST['user'];
     $enteredPass = $_POST['pass'];       

     if(in_array($enteredUser . "," . $enteredPass, $content)){ 
         echo "Access Granted";
     }else{
         echo "Access denied";
     }
}
0 голосов
/ 21 октября 2019

используйте < вместо <= в обоих for loops


            // if statements to check user/pass combo
            for ($i=0; $i < sizeof($contentArray2); $i++) {
                for ($i2=0; $i2 < sizeof($contentArray2[$i]); $i2++) {
                    // your other code
                }
            }
...