I am new to PHP. I am facing an issue while login.
login.php
$email = $password = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = filter_var($_POST["email"], FILTER_SANITIZE_STRING); $password = filter_var($_POST["password"], FILTER_SANITIZE_STRING); require_once './Model/Member.php'; $member = new Member(); $isValidLogin = $member->loginMember($email, $password); if($isValidLogin==true) // getting the exception here { // redirect to dashboard page } else{ // Invalid login } }
Member Service
public function loginMember($email, $password) { $loginUserResult = $this->ValidateUser($email, $password); return $loginUserResult; }
When I click on the login button, I am getting the following error message:
Trying to access array offset on value of type null
What am I doing wrong here?
Advertisement
Answer
You’re trying to use a variable as an array while it is a null (most possibly not declared/instantiated). An example is :
$_SERVER['REQUEST_METHOD']; // you expect $_SERVER to be an array and have a key 'REQUEST_METHOD'. $_SERVER is most probably not throwing an error as this can be expected to be set. $_POST['email']; // you expect $_POST to be an array that has 'email' as a key. This is most likely your culprit, as this variable is null when you have no post.
To avoid this error being thrown, check if the variables are indeed set and if they are an array before using it as an array.
if(is_array($_POST)) { if(isset($_POST['email'])) //do something }
If you don’t have a post as your form action, it will be obvious as your form will post the variables using a GET, which will most likely put the variables in your url (eg. www.example.com/login?email=user@example.com)