So, I have 3 forms on the same page and same controller action, when I click on one of the submit button, it validates all forms instead of the one I clicked.
how can I separate it from validation??
here my code:
public function signUpAction()
{
$firstName = $this->getRequest()->getParam('firstName');
$lastName = $this->getRequest()->getParam('lastName');
$email = $this->getRequest()->getParam('email');
$emailAdrress = $this->getRequest()->getParam('Email_Address');
$password = $this->getRequest()->getParam('password');
$signupForm = new Application_Form_UserSignUp();
$loginForm = new Application_Form_UserLogin();
$retreivePasswordForm = new Application_Form_UserRetreivePassword();
if ($this->getRequest()->isPost('signupForm'))
{
/*********** Sign Up Form ***********/
if ($signupForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($signupForm->getValues());
if ($user->save())
{
Zend_Session::rememberMe(186400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendSignUpEmail();
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else
{
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('loginForm'))
{
/************ Login Form ************/
if ($loginForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($loginForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $email, 'hash' => $password));
if($user)
{
Zend_Session::rememberMe(86400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else {
// Error message
$this->view->errorMsg = "<b>password</b> - invalid, please try again! *";
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('retreivePasswordForm'))
{
/****** Retreive Password Form ******/
if ($retreivePasswordForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($retreivePasswordForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $emailAdrress));
if($user)
{
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendRetreiveEmail();
$_SESSION['email'] = $emailAdrress;
$redirector = $this->_helper->getHelper('redirector');
$redirector->setCode(301)->setUseAbsoluteUri();
$newPath = 'http://refer.lavasoft.com/#retreive_sent';
$redirector->gotoUrl($newPath);
//$this->view->assign('sendEmail', $emailAddress);
}
else
{
}
}
else
{
// something
}
}
$this->view->retreivePasswordForm = $retreivePasswordForm;
$this->view->loginForm = $loginForm;
$this->view->signupForm = $signupForm;
}
This is not how it works in ZF. You cannot pass the form name to isPost() unless you override isPost() in your code.
What you could do is Define all your fields like:
loginForm[name]
loginForm[password]
and
signupForm[name]
etc
then just check for isset($_POST['loginFom'])
This should work fine.
Or use a hidden field named formName and check in your code what's its value is.
You can also use a different action for each form and in the end redirect to the signUpAction wich would yeld the same result without the hassle.
Related
So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>
I have a application based on CodeIgniter . I tried to set cookie in on of my controller functions. Here is the part of my code
private function login_core($username, $user_pass){
//Get value from database
$this->load->model('user_model');
if($this->user_model->init($username) == 1){
$pass = $this->user_model->getPassword();
$this->e['db_pass'] = $pass;
//Now encrypt th real password
//Make thisL
$e_p = $username. $user_pass . $this->user_model->getEmail();
$e_p = sha1($e_p);
$this->e['act_pass'] = $e_p;
//Whenever the email is changed, update the password. (Require password to change the email)
$this->load->library('encrypt');
$this->load->library('xsecurity');
//cookie not set :( . And i don't know the reason
if($pass == $e_p){
$this->xsecurity->SetInfoLocal($e_p);
setcookie('y',$this->encrypt->encode($username, $_SERVER['HTTP_USER_AGENT']),60*60*24*3);
return true;
} else {
return false; //false'
}
} else {
return false;
}
}
public function login(){
if(!isset($_POST['user'], $_POST['pass'])){
$this->load->view('header');
$this->load->view('content/errorError');
$this->load->view('footer');
return false;
}
$user = $_POST['user'];
$pass = $_POST['pass'];
if(self::login_core($user, $pass)){
$d['a'] = $this->e;
$this->load->view('header', $d);
if(isset($_GET['redirect_to'])) {
ob_start();
header('location:'. $_GET['redirect_to']);
return true;
}
$data['userloggedOn'] = true;
$this->load->view('main', $data);
}
else
{
$data['userloggedOn'] = false;
$this->load->view('main', $this->e);
}
$this->load->view('footer');
}
The user points to login via a form, and to my thinking, no any headers are sent before setting cookie (for the login page).when i wrap if around setcookie, the result is true, but the cookie does not set? Why?
don't you need to added the current time to the expire date?
for example
setcookie("y", $unique_string, time() + (60*60*24*30), '/');
I try to load a session as I want with me into my handler. But the line 8 says that "during the find index" what is the error in my controller? It is a user name that I want to use a database to retrieve the id of the person.
Controller:
<?php
require_once ("View/PersonInfoView.php");
require_once ("Handler/UserHandler.php");
class PersonInfoController{
public function DoPersonInfo(){
$Personinfoview = new PersonInfoView();
$UserHandler = new UserHandler();
$PK = $UserHandler->GetUserID($_SESSION['Person']);
$Person_array = $UserHandler->ListPerson($PK);
$Personinfoview->Personbox($Person_array);
}
}
I set Session :
<?php
require_once ("Handler/Userhandler.php");
require_once ("Controller/LoginController.php");
class DologinHandler{
public function Login(){
if(isset($_REQUEST['is_ajax']))
{
$LoginController = new LoginController();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$_SESSION['Person'] = $username;
$UserHandler = new UserHandler();
$sign = $UserHandler -> controllDB($username,$password);
if($sign == true)
{
echo 'success';
return true;
}
else
{
echo 'error';
return false;
}
}
}
}
$loginclass = new DologinHandler();
$loginclass->Login();
I'm guessing your $_REQUEST doesn't contain the key Person. Try doing a var_dump() on $_REQUEST to see what it contains.
Other than that, I suggest you implement some kind of error handeling when calling $UserHandler->GetUserID()
For instance.
try {
$PK = $UserHandler->GetUserID($_SESSION['Person']);
} catch(Exception $e) {
echo($e->getMessage());
}
Read about exceptions.
here is the case guys, I'm trying to check username on onblur event with help of ajax , which is checking username availability in mysql database.
here is ajax script =>
document.getElementById("r_username").onblur = function(){
var http = false;
var error = document.getElementById("error_username");
var numLetter = /^[a-zA-Z-0-9]+$/;
if (this.value==""){
error.innerHTML = "Empty Field !!!";
error.style.display = "inline";
} else {
if (this.value.match(numLetter)){
if (window.XMLHttpRequest){
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
if (http){
http.open("POST","./config/AjaxUsernameEmail.php",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(){
if (http.readyState==4 && http.status==200){
}
};
http.send("r_username=" + document.getElementById("r_username").value);
}
error.innerHTML = "";
error.style.display = "none";
} else {
error.innerHTML = "Invalid Number !!!";
error.style.display = "inline";
}
}
};
ajax working successfully and .php file too which script is below =>
class Checking{
private $con,$query,$flag;
public function __construct($con,$query){
$this->con = $con;
$this->query = $query;
}
public function func(){
if (mysqli_connect_errno()==0){
if ($result = mysqli_query($this->con,$this->query)){
if ($data = mysqli_fetch_assoc($result)){
return $this->flag = true;
} else {
return $this->flag = false;
}
}
}
}
}
if (isset($_POST['r_username'])){
$check = new Checking($connection,"SELECT username FROM users WHERE username='" . $_POST['r_username'] . "'");
} else {
header("Location: http://" . $mysql->host . "/index.php");
}
everything is working just fine , but here is the problem , i want to connect somehow this files , I mean that I want to know in .js file when username is matching in database and when not , because I want to do more action in .js file , but I can not set "flag" (variable which will help me for that).
Any ideas ? thanks :)))
In more details , .js file is in registration.php file , and how you can see guys .js file is invoking with ajax AjaxUsernameEmail.php file, so I want to do somehow to know when username is matching and when not , because I want in registration.php file to do more actions (notifications) during matching
The code could be a bit more like so:
$return = 'fail';
class Checking {
public function __construct($con, $query)
{
$this->con = $con;
$this->query = $query;
self::func()
}
public function func()
{
$result = 'ok';
if (mysqli_connect_errno()==0){
if ($result = mysqli_query($this->con,$this->query)){
$result = mysqli_num_rows($result) > 0? 'user_exists' : 'user_doesnt_exist';
}
}
return $result;
}
}
if( $_POST['r_username'] ){
$desired = mysqli_real_escape_string($_POST['r_username']);
$return = new Checking($connection,"SELECT username FROM users WHERE username='$desired'");
}
echo $return;
Also, you should be worried about escaping user input, and may want to look into jQuery for your ajax stuff.
The checking on the client side, should go something like this:
if (http.readyState==4 && http.status==200){
switch (http.responseText){
case 'fail':
//the username was not provided
break;
case 'user_exists':
//the username already exists
break;
case 'user_doesnt_exist':
//the username was not found on the database, continue
break;
}
}
For ajax request you must not return the value but print or echo it. Try
if ($data = mysqli_fetch_assoc($result)){
echo $this->flag = true; exit;
} else {
echo $this->flag = false; exit;
}
Evaluationg response:
if ( http.readyState == 4 && http.status == 200 ) {
switch ( http.responseText ) {
case 1: //user name taken, diplay error message
break;
case 0: //user name available, no action required
break;
}
}
So after debugging my session array while logging into my website, I find that when posting a form, all session data is lost. The session data is wiped when the updateDetails and changePassword methods are called. Why is this?
session_start() is called before any data processing
Upon a POST request, session data is set and unset (but not the entire $_SESSION variable)
I use the following code to check for POST requests:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
}
It only happens once: Once the session has been lost, the methods can be called without the issue occuring any further (until they lose the session through expiration or closing their browser).
index.php (part)
session_start();
$page = $_GET['p'];
$query = $_GET['q'];
$req = $_GET['req'];
$user = new User();
switch($page) {
case 'account':
if($req=="logout") {
if($user->isLoggedIn())
$user->logout();
header("Location: /?p=account");
exit();
}
else if($req=="signup") {
if($user->isLoggedIn()) {
header("Location: /?p=account");
exit();
}
else {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$form_data = array('username' => $_POST['username'],
'password' => $_POST['password'],
'password_repeat' => $_POST['password_repeat'],
'title' => $_POST['title'],
'first_name' => $_POST['first_name'],
'surname' => $_POST['surname'],
'dob_day' => $_POST['dob_day'],
'dob_month' => $_POST['dob_month'],
'dob_year' => $_POST['dob_year'],
'gender' => $_POST['gender'],
'email' => strtolower($_POST['email']),
'email_repeat' => strtolower($_POST['email_repeat']));
if($user->signup($form_data)) {
header("Location: /?p=account");
exit();
}
}
}
}
else {
if($user->isLoggedIn()==true) {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($req=='editdetails') {
$form_data = array(
'title' => $_POST['title'],
'first_name' => $_POST['first_name'],
'surname' => $_POST['surname'],
'gender' => $_POST['gender'],
'phone' => $_POST['phone'],
'email' => strtolower($_POST['email']),
'password' => $_POST['password']
);
if($user->updateDetails($form_data)) {
header("Location: /?p=account");
exit();
}
}
else if($req=='changepassword') {
$form_data = array(
'old_password' => $_POST['old_password'],
'password' => $_POST['password'],
'password_repeat' => $_POST['password_repeat'],
);
if($user->changePassword($form_data)) {
header("Location: /?p=account");
exit();
}
}
}
$user->retrieveUserDetails();
$details=$user->getUserDetails();
}
else {
if($req) {
header("Location: /?p=account");
exit();
}
else if($_SERVER['REQUEST_METHOD'] == 'POST') {
$form_data = array('username' => $_POST['username'], 'password' => $_POST['password']);
if($user->login($form_data)) {
$user->retrieveUserDetails();
$details=$user->getUserDetails();
}
}
}
}
break;
}
user.php (part)
class User {
private $auth;
private $details;
private $session_alert;
function User() {
if(isset($_SESSION['alert']))
$this->session_alert = $_SESSION['alert'];
$this->auth = isset($_SESSION['auth']) ? $_SESSION['auth'] : null;
if(isset($this->auth)) {
$database= new Database;
if($database->checkUserSession($this->auth['user_id'],session_id())) {
$this->logged_in=true;
}
else {
$this->addSessionAlert('global','Your login session has possibly timed out, you may login again by clicking here.',true);
unset($_SESSION['auth']);
}
}
}
function login($data) {
$return = false;
$this->form = new Form($data,0);
if(!$this->form->getError()) {
$database= new Database;
$error_msg = "The username/password entered was invalid. Please check to see if they are correct and try again, or use the relevant links to recover your account.";
$salt = $database->getSaltByUsername($data['username']);
if($salt) {
$hash = $this->hashpwd($data['password'],$salt);
// Do login
$this->auth = array();
$this->auth['user_id'] = $database->checkUserByHash($data['username'],$hash);
if($this->auth['user_id']) {
session_regenerate_id();
if($database->doLogin($this->auth['user_id'],session_id())) {
$details=$database->getUserDetailsById($this->auth['user_id']);
$this->auth['first_name'] = $details['first_name'];
$_SESSION['auth']=$this->auth;
$this->logged_in=true;
$return = true;
}
else
$this->form->pushError('Something went wrong, please try again.');
}
else
$this->form->pushError($error_msg);
}
else
$this->form->pushError($error_msg);
}
return $return;
}
function logout() {
$return = false;
if(isset($this->auth)) {
$database= new Database;
if($database->clearUserSession($this->auth['user_id'],session_id())) {
unset($_SESSION['auth']);
$this->logged_in=false;
session_regenerate_id();
$return = true;
}
}
return $return;
}
function signup($data) {
$return = false;
$this->form = new Form($data,1);
if(!$this->form->getError()) {
$database= new Database;
if($database->checkUserByUsername($data['username']))
$this->form->pushError("The username entered already exists, please try again.");
else if($database->checkUserByEmail($data['email']))
$this->form->pushError("The e-mail address entered is already in use, please try again.");
else {
$dbarray = $data;
unset($dbarray['password'],$dbarray['password_repeat'],$dbarray['dob_month'],$dbarray['dob_day'],$dbarray['dob_year']);
$dbarray['dob']=date("Y-m-d", mktime(0,0,0,$data['dob_month'], $data['dob_day'], $data['dob_year']));
$dbarray['salt']=strtoupper(md5(mt_rand()));
$dbarray['hash'] = $this->hashpwd($data['password'],$dbarray['salt']);
// Do signup
$this->auth = array();
$this->auth['user_id'] = $database->newUser($dbarray);
if($this->auth['user_id']) {
session_regenerate_id();
if($database->doLogin($this->auth['user_id'],session_id())) {
$details=$database->getUserDetailsById($this->auth['user_id']);
$this->auth['first_name'] = $details['first_name'];
$_SESSION['auth']=$this->auth;
$this->logged_in=true;
}
$return=true;
}
else {
$this->form->pushError("Something went wrong, please try again.");
}
}
}
return $return;
}
function updateDetails($data) {
$return = false;
$this->form = new Form($data,2);
if(!$this->form->getError()) {
$database= new Database;
if( $database->checkUserByEmailNotById($data['email'],$this->auth['user_id']) ) {
$this->form->pushError("The e-mail address entered is already in use, please try again.");
}
else {
$salt = $database->getSaltById($this->auth['user_id']);
if($salt) {
$hash = $this->hashpwd($data['password'],$salt);
if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
$database->updateUserById($this->auth['user_id'],$data);
$return = true;
}
else
$this->form->pushError("The password entered was incorrect, please try again.");
}
}
}
return $return;
}
function changePassword($data) {
$return = false;
$this->form = new Form($data,3);
if(!$this->form->getError()) {
$database= new Database;
$salt = $database->getSaltById($this->auth['user_id']);
if($salt) {
$hash = $this->hashpwd($data['old_password'],$salt);
if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
$salt=strtoupper(md5(mt_rand()));
$hash = $this->hashpwd($data['password'],$salt);
if($database->updateSaltHashById($this->auth['user_id'],$salt,$hash)) $this->addSessionAlert('yourdetails','Your password has been changed successfully.',false);
$return = true;
}
else
$this->form->pushError("The old password entered was incorrect, please try again.");
}
}
return $return;
}
function isLoggedIn() {
return $this->logged_in;
}
function getUserDetails() {
return $this->details;
}
}
Starting a session inside a class's contructor method, just does not sound nice.
Use session_start(); at the top of the index.php page instead.
in each page where you want to use sessions you must call session_start ();
See here:
http://codex.wordpress.org/Function_Reference/wp_update_user
Note: If current user's password is being updated, then the cookies
will be cleared!
Now, why WordPress will do this is not clear, but it is clearly stated that cookies, and therefore sessions, will be removed on setting a password through wp_update_user().
Some people have found that applying an exit(); immediately after a redirect when setting the password, will prevent the cookies from being lost.