best practice to post data on codeigniter controller with same url? - php

hello i have two route in codeigniter:
$route['register'] = 'Login/Register';
$route['login'] = 'Login/index';
for displaying login/register form
and form post routes:
$route['loginprocess'] = 'Login/LoginProcess';
$route['registerprocess'] = 'Login/RegisterProcess';
it's ok, but while using form_validation class in
$this->form_validation->set_error_delimiters('<span class="help-block">', '</span>');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('pwd', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('login');
} else {
validation success
}
problem is when i get error in form validation it goes in
http://localhost/logincode/loginprocess
is so it's not url friendly. it should post in same controller method where form already display :
http://localhost/logincode/login
so is there any way to post form in same url. with form validation error comes together

Posting to Same URL in CodeIgniter
You've described a common scenario. You want to load a page with a form, perform a POST request, validate the request, then show errors if there is a problem. There are some potential issues to be aware of if you're doing this:
After a successful post, what happens if the browser performs a page refresh?
After a successful post, what happens if the user navigates away to another page, but then travels backwards in history?
Both of these issues present a duplicate post issue, and that's never desirable. The way to solve this is to use a form token. A form token is generated during the loading of the page where the form is present. The value is commonly a random string of characters, and it is put in two places:
In the form as a hidden form field.
In a session or cookie.
When the form is posted, the token value in the hidden form field is passed along with the rest of the posted data. Since there is a session or cookie containing the same value, the controller/method being posted to can check if they match, and if they do then validation can be performed, and errors or success message output. In any case, a new form token is generated, so two posts will never contain the same form token.
Summary of The Basic Concept
// You of course have to start the
// session for this to work.
$this->load->library('session');
if(
isset( $_POST['token'] ) &&
isset( $_SESSION['token'] ) &&
$_POST['token'] == $_SESSION['token']
){
// Do validation ...
// ...
// If validation passes
if( $this->form_validation->run() ){
$valid = TRUE;
}
// If there were validation errors
else{
$errors = validation_errors();
}
}
if( isset( $errors ) )
{
// Display the errors
}
if( isset( $valid ) )
{
// Display a thank you message
}
// Always refresh the token
$token = substr(md5(uniqid() . microtime() . rand()), 0, 8);
$_SESSION['token'] = $token;
?>
<form method="POST">
<input type="text" name="x" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="submit" value="submit" />
</form>
In practice this concept of tokens can be much more elaborate. For instance, you may choose to encrypt the token values and then decrypt them when checking if they match. You might also create an array of tokens in your session/cookie, and check your posted token against the array of tokens. You may have other ideas on how to customize form tokens, but the basics have been presented here, and I hope it helps you achieve your goal of posting to the same URL in CodeIgniter.

Related

Save wordpress user ID in session, match the ID to a form input, then authenticate user, PHP

I know PIN login in wordpress is still an issue, but we can always try. Am trying to achieve the same by:
Step 1: Storing user ID(or may be username) in WP session after the user completes registration.During registration, users can create a PIN, which is stored as meta. This meta field is also stored in the session alongside user ID.
Step 2: Create a login form with one input field called "PIN", and a submit button.
Step 3: When a user (who already registered from the same device) enters PIN, php matches the entered PIN with the PIN stored in session, then authenticates the user with ID stored in the same session. DONE!
I just need to achieve this for now, I will handle logout in a different area.Also, please leave the security questions out of this for now. Just help me achieve it.
I got this code, which is now the basis of my approach. But as you can see, it compared the USERNAME entered in the input to usernames in the database to authenticate users. I could just do the same with a meta field called "PIN" instead of USERNAME, but the problem is, two or more users can set a similar PIN, and find themeselves logged in to accounts that don't belong to them. This is why I have to store the ID in session, alongsite the user meta called PIN. Then make sure the PIN entered by user matches the PIN stored in session alongside his user ID. Then autenticate the user ID stored in session.
global $user_id;
global $wpbd;
if (!$user_ID){
if($_POST){ //when form is submitted
$username = $wpdb->escape($_POST['username']);
$user = get_user_by( 'login', $username );
if ( $user === false ) {
echo 'no'; // add error message
} else {
//user id exists
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
// redirect to admin-area:
wp_redirect( home_url() );
exit();
}
} else {
// user is not log in ?>
<form method="post">
<p>
<label for="username">User ID</label>
<input type="text" id="userame" name="username" placeholder="User ID">
</p>
<p>
<button type="submit" value="submit" name="submit">Log IN</button>
</p>
</form>
<?php }
} else {
wp_redirect( home_url() );
}
?>

How to set default values for CodeIgniter Form Validation?

I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isnt submitted or its before a form submission?
public function index($uri = NULL)
{
$this->load->helper('form');
$this->load->library('form_validation');
//pull from DB or Session
$data = array(
'Status' => 'users_default_status',
'Order' => 'users_default_order',
'Asc' => 'users_default_asc'
);
$this->form_validation->set_data($data);
$this->form_validation->set_rules('Status', 'Status', 'numeric|trim|required|strtolower');
$this->form_validation->set_rules('Order', 'Order', 'trim|required');
$this->form_validation->set_rules('Asc', 'Asc', 'trim|required|strtolower');
if ($this->form_validation->run() === FALSE) // validation failed
{
// validation failed but maintain submitted values in form/feedback
}else{
// validation successful, do whatever
}
}
So that if there was a form submission it uses the POST values, and if not it uses defaults (but still validated). I would like the defaults to work on a variable by variable basis, so some can be defaults some can be user submitted.
I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isn't submitted or it's before a form submission?
Simply check if the value exists and use it as the default, otherwise it's blank (or a different default).
In the Controller, decide if you're going to load a blank form, if not, send the data for the fields....
$data['fieldname'] = "whatever"; // from the database
$this->load->view('yourpage', $data);
Then in your View, check for the existence of this data for each field. If the data was sent, use it. Otherwise, set a blank value.
<?php $value = isset($fieldname) ? $fieldname : ''; ?>
<input name="fieldname" value="<?php echo set_value('fieldname', $value); ?>" type="text" />
If you do not send the data from the Controller, the field will be blank (you could also set a default)
If you send the data from the Controller, the field will be filled out with this data from your Controller (database).
If you submit the form and validation fails, set_value() function will reload the field with the data from the most recent post array.
These are just some thoughts...
The validation rules act upon the posted data. So if you are using set_value('order',$default_order), when the form is submitted it will either take the new user entered value or the one you provided.
If the user empties a prefilled or default input, you can't have it set as "required" in the rules. What you would do is use a callback function to handle that case to check if it's empty and provide a default value and return TRUE.

Codeigniter custom url string

I am new to codeigniter and i am working on making a doctors site and need to allow users to search for doctors using simple url like http://www.mywebsite.com/newyork .so this url doesn't have any class as there can be many states and cant have class for each state. Should i change 404 override in routes script? Or there is a better way to achieve it
$route['(:any)']='search/check_state';
if i use above routing then other page like /login doesnt work.Please help
Make database that contains all states and do it this way
Inside search/check_state
// Get state from URL
$state = $this->uri->segment(1, "");
// Make sure state is not null and its found in database
if($state <> "" && $this->validateState($state)){
// Valid state, continue
}else{
// Give error message / redirect to 404 page
}
Add new function to controller
function validateState($state){
// If database contains $state then return true else return false
}
UPDATE
You can also do it with POST form.
Make form into page where user gives input details
echo form_open(base_url().'path_to_post_validation');
// make form here that sends "state" into page that handles validation
echo form_close();
Handle POST validation
// Make sure user has send POST request
if($this->input->post()){
// Set form validation rules
$this->form_validation->set_rules('state', 'state', 'required|trim|xss_clean');
// Run form validation
if ($this->form_validation->run() == TRUE){
// Store state into variable
$state = $this->input->post('state');
// Check database that it contains $state and then continue or give error message
}
}
got it try
$route['search/check_state/:any'] ='search/check_state';

Change form value before Codeignighter Form Validation

I have form data posted by client, I want to manipulate one of the forms value before I run it through $this->form_validation->run().
Is this possible
i.e something like;
//Get user form inputs
$input = $this->input->post();
//generate slug - my custom code
$input['slug'] = sf_generate_slug($input['slug']);
if ($this->form_validation->run()) {
...
You can reassign any post value before $this->form_validation->run() like
$_POST['slug'] = sf_generate_slug($_POST['slug']);
While if you use your above method it will validate because it didn't overrides the $_POST values
Hope it makes sense

Codeigniter - checkbox form validation

I have a form validation rule in place for a form that has a number of checkboxes:
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
If none of my checkboxes are checked upon submission, my code never gets past the validation->run as the variable does not exist:
if ($this->form_validation->run()):
If i surround my validation rule with a check for the var, the validation never passes as there are no other form validation rules:
if(isset($_POST['groupcheck'])):
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
endif;
How can I manage a checkbox validation rule where the var may not exist, and it will be the only form variable?
Regards, Ben.
Don't use isset() in CodeIgniter as CodeIgniter provide better class to check if the POST Variable you are checking is exist or not for example try to use this code instead of your code:
if($this->input->post('groupcheck')):
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
endif;
For Guidline using on how to use POST and GET variables in CodeIgniter check the User Guide here: http://codeigniter.com/user_guide/libraries/input.html
I had the same issue.
If your checkbox is unchecked then it will never get posted. Remove the set_rules for your checkboxes and after your other form validation rules, try something like:
if ($this->form_validation->run() == TRUE){ // form validation passes
$my_checkbox_ticked = ($this->input->post('my_checkbox')) ? yes : no;
You may compare validation_errors() after $this->form_validation->run() if is FALSE then nothing was validate, so you can do something or show a warning
if ($this->form_validation->run() == FALSE) {
if (validation_errors()) {
echo validation_errors();
} else {
echo 'empty';
}
}
You also need to set button submit
$this->form_validation->set_rules('terminos_form', 'TERM', 'required');
$this->form_validation->set_rules('terminosbox', 'TERM BOX', 'callback__acept_term');
Callback
function _acept_term($str){
if ($str === '1'){
return TRUE;
}
$this->form_validation->set_message('_acept_term', 'Agree to the terms');
return FALSE;
}
HTML
<input type="checkbox" name="terminosbox" value="1"/>
<button type="submit" name="terminos_form" value="1">NEXT</buttom>

Categories