settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Login - PHP Task (Solved)

+3 votes

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

asked in PHP category by user eiorgert

2 Answers

+2 votes

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;
    }
}
answered by user ak47seo
+1 vote

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;
    }
}
answered by user andrew
...