Reputation: 11
This is a controller I just made that will check the input password. It's seemed to be no mistakes. But, when I run it, it didn't receive the result (echo "Right password") although I entered the right input.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MainController extends Controller
{
private $data = array(
array("TestUser","Password"),
array("Admin","BigA1r")
);
//$this->log($u,$p);
public static function log($username,$pass) { //login
echo "<title>Processing request...</title>";
echo "Logging in... Please wait.";
for ($i = 1;$i == 35;$i++){
$u = $data[$i][1];
if ($u == $username){
$p = $data[$i][2];
if ($p == $pass){
setcookie("username="+$u);//+";password="+p;
echo "Right password";
}else{echo "Wrong password";};
}else{
echo "Can't find this username. Please try a different
name.";
}
}
}
What's the mistake here? I can't find it. And it didn't throw any. It just stopped at echo "Logging in... Please wait.";
Upvotes: 0
Views: 319
Reputation: 40639
You have several issues in your code like,
self::$data
instead of $data
. Read How to access private variable in static function count(self::$data)
So, try the below code
for ($i = 0,$l=count(self::$data);$i < $l;$i++){
$u = self::$data[$i][0]; // use 0 not 1 for username, as index start from 0
if ($u == $username){
$p = self::$data[$i][1]; // use 1 not 2, as index start from 0
if ($p == $pass){
setcookie("username="+$u);//+";password="+p;
echo "Right password";
} else{echo "Wrong password";};
} else{
echo "Can't find this username. Please try a different name.";
}
} //end for
And make your private variable $data
to be static
like,
private static $data = array(
array("TestUser","Password"),
array("Admin","BigA1r")
);
Full code,
class MainController extends Controller {
private static $data = array(
array("TestUser","Password"),
array("Admin","BigA1r")
);
//$this->log($u,$p);
public static function log($username,$pass) { //login
echo "<title>Processing request...</title>";
echo "Logging in... Please wait.";
for ($i = 0,$l=count(self::$data);$i < $l;$i++){
$u = self::$data[$i][0];
if ($u == $username){
$p = self::$data[$i][1];
if ($p == $pass){
setcookie("username="+$u);//+";password="+p;
echo "Right password";
} else {
echo "Wrong password";
}
} else {
echo "Can't find this username. Please try a different name.";
}
} // end for loop
} // end function log
} // end class MainController
Upvotes: 2
Reputation: 783
Try to use:
self::$data[$i][1] and self::$data[$i][2]
To access a private variable of a class from static method you need to use self keyword.
Also, in the loop you have
for ($i = 1;$i == 35;$i++)
This might fail running as the condition is $i==35 and your are starting with $i=1 which is never satisfied it should be $i<=35.
Upvotes: 0