[해결로 표시] 로그인 - PHP(예제가 있는 작업)

  

3
주제 스타터

You will be given a string representing a username. The password will be that username reversed. Until you receive the correct password print on the console "Incorrect password. Try again.". When you receive the correct password print "User {username} logged in." However on the fourth try if the password is still not correct print "User {username} blocked!" and end the program.

Examples:

login php task

2개 답글
3

My solution:

<?php
 
$user = readline();
$length = strlen($user); //the length of the string
$pass = '';
 
for ($i = $length - 1; $i >= 0; $i--) {
    $pass .= $user[$i];
}
 
$attempts = 0;
 
while ($attempts++ < 6) {
    $input = readline();
    if ($input === $pass) {
        echo "User $user logged in." . PHP_EOL;
        break;
    }
 
    if ($attempts === 4) {
        echo "User $user blocked!" . PHP_EOL;
        break;
    } else {
        echo "Incorrect password. Try again." . PHP_EOL;
    }
}
1

Instead og using reversed for loop, you can use strrev() PHP function/method to reverse the string (on line 4):

<?php
 
$user = readline();
$pass = strrev($user);
 
$attempts = 0;
 
while ($attempts++ < 6) {
    $input = readline();
    if ($input === $pass) {
        echo "User $user logged in." . PHP_EOL;
        break;
    }
 
    if ($attempts === 4) {
        echo "User $user blocked!" . PHP_EOL;
        break;
    } else {
        echo "Incorrect password. Try again." . PHP_EOL;
    }
}
공유: