How to check CSRF token is valid or not after custom form submit in codeigniter - codeigniter

I am working on CodeIgniter custom form, In this form, I have used CSRF token after form submit I want to check in controller after form submit if CSRF token is valid or not, can anyone please help me for this issue?
PHP Form code
<form role="form" data-parsley-validate="" novalidate="" class="mb-lg" action="?c=
<?php echo isset($controller) ? $controller : "welcome"; ?>&m=login" method="post">
<div class="form-group has-feedback">
<input name="email" id="exampleInputEmail1" type="email" placeholder="Enter email" autocomplete="off" required class="form-control">
<span class="fa fa-envelope form-control-feedback text-muted"></span>
</div>
<div class="form-group has-feedback">
<input name="password" id="exampleInputPassword1" type="password" placeholder="Password" required class="form-control">
<span class="fa fa-lock form-control-feedback text-muted"></span>
</div>
<div class="clearfix">
<div class="pull-right">
Forgot your password?
</div>
</div>
<?php
$csrf = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
);
?>
<input type="hidden" name="<?php echo $csrf['name'];?>" value="<?php echo $csrf['hash'];?>" />
<button type="submit" class="btn btn-block btn-primary mt-lg">Login</button>
</form>

CodeIgniter does this for you automatically. If it is not valid it will do a show_error with show_error('The action you have requested is not allowed.', 403);
Relevant functions can be found in the /system/core/security class, functions: csrf_verify() and csrf_show_error() (if invalid).
If you have understood by now, if you have csrf enabled in the config and you do not have the appropriate csrf hidden field or use form_open (which adds the field for you) then when you post the request it will fail with the above message. The same goes for AJAX requests - to automate this for ajax requests you can add this to the top of you page wherever there is an ajax request:
<script type="text/javascript">
token["<?php echo $this->security->get_csrf_token_name(); ?>"] = "<?php echo $this->security->get_csrf_hash(); ?>";
jQuery.ajaxSetup({data: token, type: "POST"});
</script>

Related

How to put route url in the echo in laravel form inside a controller?

This is the code inside the controller of my laravel:
echo '
<form action="'.$link.'" method="POST">
';
csrf_token();
echo '
<div class="form-group">
<label for="reason">Total Worked Hours::</label>
<input type="text" class="form-control" disabled="disabled" id="hours" value="'.$totalhours.'"style="color:red;font-weight:bold;"">
</div>
<div class="form-group">
<label for="reason">Enter Your Reason:</label>
<input type="text" class="form-control" id="text">
</div>
<button type="submit" class="btn btn-default">Submit Reason</button>
</form>
';
and the error is 419 page expired what is the proper code for this.
change the line
csrf_token();
by
echo csrf_field();
Or, depending on your ajax, remove it completly.

Is it possible to call confirmation dialog from controller in codeigniterr?

I am using codeigniter of version 3. When I submit that form, i have to save the data of that form and a confirmation dialog with yes no option has to appear. If user clicks yes i have to redirect to a page and if use clicks to no i have to redirect to another page .How can i do that?
My View code:
<form id="saveRenewFirm" action="<?php echo base_url() ?>firm/saveFirmInfo" method="post" role="form">
<div class="row">
<div class="col-25">
<label> Name of the firm:</label>
</div>
<div class="col-75">
<input type="text" id="firm_name" name="firm_name" value="<?php echo $firmDetail->firm_name; ?>" <?php echo $status;?> style="width:50%;" />
</div>
</div></p>
<div class="row">
<div class="col-25">
<label>Category :</label>
</div>
<div class="col-75">
<input type="text" name="category" id="category" value="<?php echo $firmDetail->category; ?>" <?php echo $status;?> />
</div>
</div>
<div class="row">
<div class="col-25">
<label>Phone no :</label>
</div>
<div class="col-75">
<input type="text" name="phone_no" id="phone_no" value="<?php echo $firmDetail->phone; ?>" <?php echo $status;?> />
</div>
</div>
<div class="row">
<div class="col-25">
<label>Address :</label></div><div class="col-75"><input type="text" name="address" style="width:400px;" id="address" value="<?php echo $firmDetail->address; ?>" <?php echo $status;?> />
</div>
</div>
<button value="submit" name="action" type="submit" class="button" >Submit</button>
<?php echo form_hidden('renew_id',$firmDetail->renew_id);?>
</form>
My controller:
public function saveFirmInfo() {
$this->setValidation();
if($this->form_validation->run() == FALSE){
$this->index();
} else {
$data = array(
'firm_name' => $this->input->post('firm_name'),
'category' => $this->input->post(category),
'phone_no' => $this->input->post('phone_no'),
'address' => $this->input->post('address'));
$new_id = $this->renewed_firm_model->insert($data);
if($new_id>0){
$this->session->set_flashdata('success', 'Firm Detail submitted. Do you want to continue to payment?');
}else {
$this->session->set_flashdata('error', 'Error during processing, please try again...');
}
redirect('member/profile','refresh');
}
I want to bring a confirmation dialog instead of flash message to continue for payment . If user clicks yes then i have to redirect to payment page and if user clicks no another page has to be opened.
You can either do this 2 ways.
The first way, and the easiest given your current code would be to redirect to a page after the user submits the form that has a question and 2 options (yes or no).
The second way would be to submit the form via ajax and launch a modal on success function. This would be more intensive, and require substantial changes to your current save function.

The POST method is not supported for this route. Supported methods: GET, HEAD.",…

I am having issues while using laravel resourceApi controller along with vue js i am creating and application where i am using vue and laravel i am posting a value to store method of my controller but it is saying the method is not allowded or 405 exception in the response. i need some help i am new to laravel and vue.
Here is my code
**UserController :**
public function store(Request $request)
{
return ['message' => 'i have your data'];
}
**Route:**
Route::apiResources(['user' => 'API\UserController']);
**Vue Code:**
<form #submit.prevent="createUser">
<div class="modal-body">
<div class="form-group">
<input
v-model="form.name"
placeholder="Enter name"
type="text"
name="username"
class="form-control"
:class="{ 'is-invalid': form.errors.has('name') }"
>
<has-error :form="form" field="name"></has-error>
</div>
<div class="form-group">
<input
v-model="form.email"
placeholder="Enter email"
type="email"
name="username"
class="form-control"
:class="{ 'is-invalid': form.errors.has('email') }"
>
<has-error :form="form" field="email"></has-error>
</div>
<div class="form-group">
<textarea
v-model="form.bio"
placeholder="Enter bio"
type="email"
name="username"
class="form-control"
:class="{ 'is-invalid': form.errors.has('bio') }"
/>
<has-error :form="form" field="bio"></has-error>
</div>
<div class="form-group">
<select
v-model="form.type"
placeholder="Enter bio"
name="type"
class="form-control"
:class="{ 'is-invalid': form.errors.has('type') }"
>
<option value>---Select User Role---</option>
<option value="admin">Admin</option>
<option value="user">Standard User</option>
<option value="author">Author</option>
</select>
<has-error :form="form" field="bio"></has-error>
</div>
<div class="form-group">
<input
v-model="form.password"
placeholder="Enter email"
type="password"
name="password"
class="form-control"
:class="{ 'is-invalid': form.errors.has('password') }"
>
<has-error :form="form" field="password"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Create</button>
</div>
</form>
**Vue method :**
createUser() {
this.form.post("api/user");
}
error:
I have tried running your code in my program and all the code you mentioned above seems fine. Since you have not provided the code of createUser method so I think you might have done mistake while calling the api.
Please try the below code once in your axios post route.
methods:{
createUser(){
axios.post('/api/user/store', {
//keep your field here//
}).then(res => {
console.log(res)
}
}
}
Maybe there's an error in your post route in axios. It would be helpful if you show your createUser() method. But I'm guessing you have to do something as such to have your code run.
createUser()
{
axios.post('/api/user/store',{
//your fields and all
})
}
API Resource Routes doesn't Support the function for create and Edit i mean POST or PUT method. apiResource method automatically exclude these two routes(Create and Edit).If you want to store or update something, you may specify another route with its corresponding function or use resource routes rather then API resource route like as,
Route::resource(['user' => 'API\UserController']);
please go through the documentation https://laravel.com/docs/5.8/controllers#restful-partial-resource-routes
axios has a default path so if the get request is "/user" the path will be "http://localhost/client" but if you are making a call from another path "http://localhost/invoice" and the get request is "user" so axios will take the current path as base path "http://localhost/invoice/invoice/user" for this reason you must use "/user".
you can check the documentation: https://github.com/axios/axios#request-method-aliases
createUser(){
axios.post('/api/user',{
/* parameter */
})
}

using route resource form did not post to store function

I have a form which upon successful validation should show the desired result. But on button press the browser displays The page has expired due to inactivity. Please refresh and try again.
view page
<form class="form-horizontal" method="POST" action="{{action('BookController#store')}}">
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" required="required" runat="server" id="txtBookName" class="form-control" autocomplete="off" autofocus="autofocus" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
Route code
//web.php
Route::resource('book','BookController');
controller code
class BookController extends Controller
{
public function index()
{
//
}
public function create()
{
return view('pages.book');
}
public function store(Request $request)
{
$validatedInput = $request -> validate([
'txtBookName' => 'required|string|min:3|max:100'
]);
return $validatedInput;
}
}
Form url
http://127.0.0.1:8000/book/create
on submit button press, the page is redirected to
http://127.0.0.1:8000/book and it displays The page has expired due to inactivity. Please refresh and try again.
You can either post a CSRF token in your form by calling:
{{ csrf_field() }}
Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php:
protected $except = [
'your/route'
];
Implement like this to avoid Expired message.
<form action="{{ action('ContactController#store') }}" method="POST">
#csrf <!-- this is the magic line, works on laravel 8 -->
<!--input components-->
<!--input components-->
<!--input components-->
</form>
you should use {{ csrf_field() }} in your form.
Please do this after the form class, because the resource take the #method('PUT')
<form class="form-horizontal" method="POST" action="{{action('BookController#store')}}">
{{csrf_field()}}
#method('PUT')
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" required="required" runat="server" id="txtBookName" class="form-control" autocomplete="off" autofocus="autofocus" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>

Posting data from form Codeigniter

I need to post data from a form that creates fields from looping through some ids, so the fields have the same id and names but different data which i need to pass to my controller an eventually save
My Form View
<form class="form" id="addForm">
<div class="panel-body">
<?php foreach ($lab_result->result() as $results){?>
<div class="form-group">
<div class="col-md-5">
<input type="hidden" id="request_details_id" name="request_details_id" class="form-control" value="<?php echo $results->id; ?>"/>
<label class="col-sm-12 control-label"><span class="text-warning"><strong>Requested Service : </strong></span> <span class="text-success"><?php echo $results->service_name; ?> - <?php echo $results->service_description; ?></span></label>
<label class="col-sm-12 control-label"><span class="text-warning"><strong>Service Costs : </strong></span> <span class="text-success">Ksh. <?php echo $results->service_price; ?></span></label>
</div>
<div class="col-sm-7">
<textarea class="form-control" rows="2" id="results" name="results" placeholder="Input Lab Results, if none type N/A"></textarea>
</div>
</div>
<?php }?>
</div><!-- panel-body -->
<div class="panel-footer">
<button type="submit" class="btn btn-primary">Send Results</button>
</div>
</form>
Ajax to post data
$.ajax({
url: '<?php echo base_url(); ?>laboratory/addLabResult',
type: 'post',
data: $('#addForm :input'),
dataType: 'html',
success: function(html) {
$('#addForm')[0].reset();
bootbox.alert(html, function()
{
window.location.reload();
});
}
});
If i print_r in my controller, I only see the post from the last row
You need to use input name in array format to upload all values
<input type="hidden" id="request_details_id" name="request_details_id[]" class="form-control" value="<?php echo $results->id; ?>"/>
and
<textarea class="form-control" rows="2" id="results" name="results[]" placeholder="Input Lab Results, if none type N/A"></textarea>

Resources