I found problem regarding my captcha validation form, for more detail here i show my code :
Captcha function
private function gbr_captcha()
{
$vals = array(
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'font_path' => './system/fonts/impact.ttf',
'img_width' => '150',
'img_height' => 40
);
$cap = create_captcha($vals);
$datamasuk = array(
'captcha_time' => $cap['time'],
'word' => $cap['word']
);
$expiration = time()-3600;
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
$query = $this->db->insert_string('captcha', $datamasuk);
$this->db->query($query);
return $cap['image'];
}
Captcha Validation Form
if(empty($cek))
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('captcha', 'Captcha', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$frm['gbr_captcha'] = $this->gbr_captcha();
$this->load->view("app_admin/login/index",$frm);
}
else
{
$u = $this->input->post('username');
$p = $this->input->post('password');
$this->app_model->getLoginData($u,$p);
}
}
It's working to show captcha in my web, but to validate captcha inputed from user was correct or not, it's not working, I think my problem come from my validation, if there any advice to fix my code, please share, thanks..
You are storing following data into your Database
$datamasuk = array(
'captcha_time' => $cap['time'],
'word' => $cap['word']
);
IMHO there is nothing which identifies the user (like the ip address.). You wont be able to get the already generated and stored text to compare. Because you dont have anything which points to the user.
Option 1: Store more information like ip address and when you trying to validate the captcha ask the database if there is any record for the ip address.
Option 2: Store the captcha in a session like
$this->session->set_userdata("captcha", ["expires"=> time()+3600, "data" => captcha_string])
That way is easier to validate (at least for me).
I hope it was clear enough.
I think you should have a callback function in your captcha to validate if it is correct.
$this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|callback_checkCaptcha');
function checkCaptcha($word){
$ip = $this->session->get_userdata("ip");
//check db/query db if the captcha word is correct
$sql = "SELECT id FROM captcha WHERE word = {$word} and ip={$ip}"
//return true or false if word exists or not
}
And secondly how can you determine that it is the exact captcha?
You can store the user ip address, or set cookies/session
Related
I have set the CI framework with database connection, put it on autoload and created a form, yet still, nothing is inserted into the Database!
I've tried using objects(classes) and different ways to pass information in an array
if (isset($_POST['register-submit'])) {
$this->load->model('Registermodel');
$this->load->library('form_validation');
$this->form_validation->set_rules('register-username', 'Username', 'required');
$this->form_validation->set_rules('register-password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('register-password-repeat', 'confirm passphrase', 'required|min_length[6]|matches[register-password]');
$this->form_validation->set_rules('register-pin', 'pin', 'required|regex_match[/^[0-9]{6}$/]');
//If form validation was successful
if ($this->form_validation->run() == TRUE) {
echo 'successfully registered!';
//Add user to database
$data = array(
'ci_useruniqid'=> $_POST['register-uniqid'],
'ci_userdate'=> $_POST['register-date'],
'ci_useruid'=> $_POST['register-username'],
'ci_userpwd'=> password_hash($_POST['register-password'], PASSWORD_DEFAULT),
'ci_usermnemonic'=> $_POST['register-mnemonic'],
'ci_usercurrentaddress'=> $_POST['register-address'],
'ci_useraccount'=> $_POST['register-account'],
'ci_useraccountbalance'=> $_POST['register-account-balance'],
'ci_userpin'=> $_POST['register-pin'],
'ci_userstatus'=> $_POST['register-status'],
'ci_usertype'=> $_POST['register-type'],
'ci_userinfo'=> $_POST['register-info'],
'ci_userpgp'=> $_POST['register-pgp'],
'ci_usercurrency'=> $_POST['register-currency']
);
$this->RegisterModel->adduser($data);
redirect("AuthController/loginview", "refresh");
}
What I expect to happen is for the data(as seen above) to be inserted into the DB. My actual result is no response even something as simple as echoing something out in an if statement.
My table structure:
ci_userid int(11)
ci_useruniqid
ci_userdate date
ci_useruid
ci_userpwd
ci_usermnemonic
ci_usercurrentaddress
ci_useraccount
ci_useraccountbalance decimal(12,8)
ci_userpin
ci_userstatus
ci_usertype
ci_userinfo
ci_userpgp
ci_usercurrency
The rest are text, here is my adduser model:
public function adduser($data) {
$insert = $this->db->insert('users', $data);
}
As this was too long for a comment, I present to you my quasi answer that will help you debug.
echo 'hello world <br><pre>';
print_r($_POST);
if (isset($_POST['register-submit'])) {
$this->load->model('Registermodel');
$this->load->library('form_validation');
$this->form_validation->set_rules('register-username', 'Username', 'required');
$this->form_validation->set_rules('register-password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('register-password-repeat', 'confirm passphrase', 'required|min_length[6]|matches[register-password]');
$this->form_validation->set_rules('register-pin', 'pin', 'required|regex_match[/^[0-9]{6}$/]');
//If form validation was successful
if ($this->form_validation->run() == TRUE) {
echo 'successfully registered!';
//Add user to database
$data = array(
'ci_useruniqid' => $_POST['register-uniqid'],
'ci_userdate' => $_POST['register-date'],
'ci_useruid' => $_POST['register-username'],
'ci_userpwd' => password_hash($_POST['register-password'], PASSWORD_DEFAULT),
'ci_usermnemonic' => $_POST['register-mnemonic'],
'ci_usercurrentaddress' => $_POST['register-address'],
'ci_useraccount' => $_POST['register-account'],
'ci_useraccountbalance' => $_POST['register-account-balance'],
'ci_userpin' => $_POST['register-pin'],
'ci_userstatus' => $_POST['register-status'],
'ci_usertype' => $_POST['register-type'],
'ci_userinfo' => $_POST['register-info'],
'ci_userpgp' => $_POST['register-pgp'],
'ci_usercurrency' => $_POST['register-currency']
);
$this->RegisterModel->adduser($data);
echo 'success';
//redirect("AuthController/loginview", "refresh");
} else {
echo validation_errors();
}
} else {
echo 'register-submit... well... does not exist';
}
Please note, use $this->input->post('somename'); for all your $_POST stuff. e.g. assume that register-uniqid doesn't exist (form validation won't catch it because it isn't required) you'll get an undefined index error; thus you'd have to do isset($_POST['register-uniqid']) ? $_POST['register-uniqid'] : null whereas $this->input->post() does that logic for you.
Now, even if you make this fix, if register-uniqid is absolutely critical (cannot be null) then make sure form validation covers it with a required. Even though you may have some hidden fields, it doesn't mean the user can't delete them if they want and post a null to that db column. I would suggest forgoing hidden fields entirely and coding any non-user-related input in to this controller or model.
I'm trying to check whether or not an email or username exists in the database before inserting data into the database. For a reason I do not understand, despite using the email_exists and username_exists functions, when inserting the data, the database throws a field not unique error for username and email fields.
The username_exists and email_exists functions gets any usernames or emails where they match the username or email submitted by the form. The functions then return true if there is a username or email that exists, or false if the opposite. When both functions return false (i.e. username and email don't exist in the database) it inserts the form data into the database.
Any help would be great!
Controller Function
public function register(){
if($this->session->userdata('loggedIn') == TRUE){
$this->session->set_flashdata('error_msg', 'please log out to access this page ');
echo 'Please log out to access this page!...';
sleep(2);
redirect('index.php/user/dashboard');
}
$data['session_data'] = array(
'userID' => $this->session->userdata('userID'),
'loggedIn' => $this->session->userdata('loggedID')
);
$this->load->view('navigation');
$this->load->view('register', $data);
echo 'registration page - ';
if($this->input->post('register')){
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('email', 'email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
if($this->form_validation->run() == true){
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
if($username_exists == false && $email_exists == false) {
$this->user_model->add_user_account($user_details);
echo 'user added successfully: '. $user_details[0];
$this->session->set_flashdata('success_msg', 'SUCCESSFULLY ADDED USER, username and email do not already exist!... ');
sleep(2);
redirect('index.php/user/login');
} else {
echo 'username or email already exists! try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED - username or email exists!...');
sleep(2);
redirect('index.php/user/register');
}
} else {
echo 'error occured, try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED- something didn\'t work');
sleep(2);
redirect('index.php/user/register');
}
}
}
Model Functions
public function add_user_account($user_details){
$this->db->insert('user_account', $user_details);
}
public function username_exists($username){
$this->db->select('username');
$this->db->from('user_account');
$this->db->where('username', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
public function email_exists($email){
$this->db->select('email');
$this->db->from('user_account');
$this->db->where('email', $email);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
$user_details[0] doesn't reference anything as you have non-numerical keys for the user_details array. I assume you mean to access the key username thus you should do $user_details['username'].
Like so:
$username_exists = $this->user_model->username_exists($user_details['username']);
$email_exists = $this->user_model->email_exists($user_details['email']);
To be honest I'm surprised this isn't giving you notice errors.
Further, you could easily make your username/email exists functions into a callback or simply use the is_unique feature of the form_validation library.
Also I'm pretty sure that you can apply strip_tags as a form_validation rule and it will remove the tags in the post variables.
Well to address your question via a means of simplification, you can use is_unique[table.field] as a validation rule.
That way you do not need to write any model methods for checking that your username or email is unique.
So in your form validation rules you can alter your username and email rules to include the is_unique rule.
$this->form_validation->set_rules('username', 'Username', 'required|is_unique[user_account.username]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user_account.email]');
Note: The 2nd Field is the Form Label and can be anything. In this case I uppercased it. The 1st field IS case sensitive.
As to why your existing code isn't working...
Try getting friendly using var_dump(); or print_r();
i.e.
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
// Debug these two and see what they are...
var_dump($username_exists);
var_dump($email_exists);
Now seeing you are using an associative array in setting up
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
And then referencing them like
$username_exists = $this->user_model->username_exists($user_details[0]);
Using the above var_dump's should give you an "Aha!!!" moment.
When in doubt var_dump();
I am developing an application in CI supported Grocery CRUD , but at the time of validation is not recognized , what I need is that a field is validated to accept only alphabetic characters , plus points , comma and space but does not work:
Function in controller
Lines of code in the function of Grocery CRUD in what I call the function solo_letras:
Lines of code in method of Grocery CRUD
What would be a validation that could take?
Use the built in form validation in CodeIgniter.
I do it like this.
At the beginning of your function set all the rules for your form inputs like this:
$this->form_validation->set_rules('inputFirstName', 'First Name', required|min_length[4]|max_length[16]|is_unique[users.username]');
This is a sample for a user name field. The first parameter is the form input name='inputFirstName', The second is a readable version of the first and is used for error reporting, then comes your validations which are separated by the pipe character. There is a validation for matching regex; regex_match[/regex/].
Place all your validations then use:
if($this->form_validation->run() == false) {
Do something here if validation fails
return false;
}
To test for validation.
Then continue on with the code if validation passes.
Here is a full sample of a simple registration function:
public function register()
{
$this->output->set_content_type('application_json');
$this->form_validation->set_rules('inputUsername', 'User Name', 'required|min_length[4]|max_length[16]|is_unique[users.username]');
$this->form_validation->set_rules('inputEmail', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('inputFirstname', 'First Name', 'required|max_length[20]');
$this->form_validation->set_rules('inputLastname', 'Last Name', 'required|max_length[20]');
$this->form_validation->set_rules('inputPassword', 'Password', 'required|min_length[6]|max_length[16]|matches[inputPasswordConfirm]');
$this->form_validation->set_rules('inputPasswordConfirm', 'Password Confirmation', 'required');
if($this->form_validation->run() == false) {
$this->output->set_output(json_encode(['result' => 0, 'error' => $this->form_validation->error_array()]));
return false;
}
$username = $this->input->post('inputUsername');
$email = $this->input->post('inputEmail');
$firstName = $this->input->post('inputFirstname');
$lastName = $this->input->post('inputLastname');
$password = $this->input->post('inputPassword');
$passwordConfirm = $this->input->post('inputPasswordConfirm');
$this->load->model('user_model');
$user_id = $this->user_model->insert([
'username' => $username,
'email' => $email,
'firstName' => $firstName,
'lastName' => $lastName,
'password' => hash('sha256', $password . PASSWORD_SALT)
]);
if($user_id) {
$this->session->set_userdata(['user_id' => $user_id]);
$this->output->set_output(json_encode(['result' => 1]));
return false;
}
$this->output->set_output(json_encode(['result' => 0, 'error' => "User not created."]));
}
I have a question, I am trying to create a way in which the user who is logged in can register multiple cards under his name. I understand the concept but just cannot apply it. So need help.
So basically I have 2 tables one for users and another for the cards, which are as shown.
new_users
user_money
So basically i created all this table and most of the information are inserted directly by me for example the orig_id.
So basically what I just want to do is that the user logged in can create multiple cards. Maybe the new_users.id could be equal to user_money.orig_id , but I am not sure how can I make them equal to each other and when a new user registers and enters more cards how can that user id and orig id equal to each other.
This is my controller for login and the controller when user adds a card.
public function login(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[32]');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('body_view');
$this->load->view('footer_view');
}else{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->model('main_page');
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$user_data = array(
'user_id' => $user_id,
'email' => $email,
'loggedin' => true
);
$this->session->set_flashdata('loggedin_success','you are loggedin');
redirect('main/Admin');
}else{
redirect('main/login');
}
}
}
And this is the function for the new card getting registered.
public function insertUserCard(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('cardname', 'CardName', 'required');
$this->form_validation->set_rules('iban', 'IBAN', 'required');
$this->form_validation->set_rules('cc', 'CC', 'required|max_length[4]');
$this->form_validation->set_rules('amount', 'Amount', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('admin_view');
$this->load->view('footer_view');
}else{
$data = array(
'card_type' => $this->input->post('cardname'),
'iban' => $this->input->post('iban'),
'cc' => $this->input->post('cc'),
'amount' => $this->input->post('amount'),
'orig_id' => 52
/*so the orig id here is randomly added by me */
);
$this->load->model('main_page');
$this->main_page->storeCardInfo($data);
redirect('main/Admin');
}
}
And just incase if needed the models for both the table data being inserted.
public function login_user($email , $password){
$this->db->where('email', $email);
$this->db->where('password', $password);
$result = $this->db->get('new_users');
if($result ->num_rows() == 1){
return $result->row(0)->id;
}else{
return false;
}
}
public function storeCardInfo($data){
$insert = $this->db->insert('user_money',$data);
return $insert;
}
So would like if someone could help me on how to get one user have multiple rows in the user_money table.
I am using codeigniter and mysql
Just use the user_id that is stored into $user_data inside of login().
First, to make user_data a session variable so that the whole controller can access it, change the line in login() which declares $user_data as a local variable to assign it to a session variable.
Change:
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$user_data = array(
...
To:
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$this->session->set_userdata(array(
...
Then... you can change the line in insertUserCard():
'orig_id' => 52
/*so the orig id here is randomly added by me */
to just use the session:
'orig_id' => $this->session->userdata('user_id');
I think, since you are "new to all this", you should perhaps ensure your MySQL database is setup properly with a Foreign Key Constraint. (and that you understand how that works)
Greetings,
I am setting up a pretty standard registration form with password field.
The problem is, after a failed submission (due to empty field, incorrect format etc), the controller reloads the registration page, but with the password field containing the hashed value of the previously entered password. How do I make it empty after each failed submission?
View:
echo $form->password('Vendor.password', array('class' => 'text-input'));
Controller:
Security::setHash('sha1');
$this->Auth->sessionKey = 'Member';
$this->Auth->fields = array(
'username' => 'email',
'password' => 'password'
);
Help is very much appreciated, thanks!
You may run into another problem down the road with cakePHP password validation.
The problem is that cake hashes passwords first, then does validation, which can cause the input to fail even if it is valid according to your rules. This is why the password is returned to the input field hashed instead of normal.
to fix this, instead of using the special field name 'password', use a different name like 'tmp_pass'. This way, cakePHP Auth won't automatically hash the field.
Here's a sample form
echo $form->create('Vendor', array('action' => 'register'));
echo $form->input('email');
echo $form->input( 'tmp_pass', array( 'label' => 'Password','type'=>'password' ));
echo $form->end('Register');
In your Vendor model, don't assign validation rules to 'password' instead assign these rules to 'tmp_pass', for example
var $validate = array('email' => 'email', 'password' => ... password rules... );
becomes
var $validate = array('email' => 'email', 'tmp_pass' => ... password rules... );
Finally, in your Vendor model, implement beforeSave().
First, see if the data validates ('tmp_pass' will be validated against your rules).
If successful, manually hash tmp_pass and put it in $this->data['Vendor']['password'] then return true. If unsuccessful, return false.
function beforeSave() {
if($this->validates()){
$this->data['Vendor']['password'] = sha1(Configure::read('Security.salt') . $this->data['User']['tmp_pass']);
return true;
}
else
return false;
}
this?
password('Vendor.password', array('class' => 'text-input','value'=>''))
In your controller:
function beforeRender() {
parent::beforeRender();
$this->data['Vendor']['password'] = '';
}