Ahhh some progress seems to be there after changing header to redirect. Now what is happening when i login after and unsuccessful login, it is giving one error "session not created" i.e. $SESSION->wantsurl is coming empty. And after that if i relogin then it is redirecting. But it is confusing why it is redirecting on the third attempt and why $SESSION->wantsurl is empty. The error is coming at:
else if (empty($SESSION->wantsurl)) {
echo "Session not created";
session_write_close();
//header("Location: $CFG->wwwroot");
redirect(
"$CFG->wwwroot");