Multilevel Login in php&mysqli with codeigniter - javascript

i have 3 user with different access page, i have try create login form standart with no limit access. now i'm confussed where i must place new code multiple login.
( i use php&mysqli database with codeigniter framework )
Please help me,
thk u before
database image
code image
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('m_rental');
}
public function index(){
$this->load->view('login');
}
function login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->form_validation->set_rules('username','Username','trim|required');
$this->form_validation->set_rules('password','Password','trim|required');
if($this->form_validation->run() != false){
$where = array(
'admin_username' => $username,
'admin_password' => $password,
);
$data = $this->m_rental->edit_data($where,'admin');
$d = $this->m_rental->edit_data($where,'admin')->row();
$cek = $data->num_rows();
if($cek > 0){
$session = array(
'id'=> $d->admin_id,
'nama'=> $d->admin_nama,
'status' => 'login'
);
$this->session->set_userdata($session);
redirect(base_url().'admin');
}else{
redirect(base_url().'welcome?pesan=gagal');
}
}else{
$this->load->view('login');
}
}
}

Try to add level to your session and read it later on dashboard page:
$session = array(
'id'=> $d->admin_id,
'nama'=> $d->admin_nama,
'status' => 'login',
'level' => $d->level
);
And on dashboard page
if($this->session->userdata["level"] === "superadmin")
{
// Code if level = superadmin
}

Related

POST http://127.0.0.1:8000/broadcasting/auth 403 (Forbidden) ,How i can resolve this error

app.js :
import './bootstrap';
Echo.private('App.Models.Company.' + companyId)
.notification((notification) => {
console.log(notification);
});
channel.php :
Broadcast::channel('App.Models.Company.{id}', function ($company, $id) {
return (int) $company->id === (int) $id;
});
blade page :
<script>
let companyId = '{{ Auth::id() }}';
</script>
#vite(['resources/js/app.js'])
This problem has been solved, because I am using guards in my system, it does not recognize any guards other than the default guard
I defined the guard in the channel route such as :
Broadcast::channel('App.Models.Company.{id}', function ($company, $id) {
return (int) $company->id === (int) $id;
},['guards'=>['company']]);

return back laravel function not working on server

I have problem with my laravel project, when validator false return back function run well on localhost, but on the server it return to root url , somebody may help me figure it out?
My controller like this:
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('employees.form_edit', ['user' => User::find($id)]);
else {
$rules = [
'name' => 'required',
'full_name' => 'required',
'id_number' => 'required',
'date_of_birth' => 'required',
'avatar' => 'mimes:jpeg,jpg,png,gif|max:2048'
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
;
}
$user = User::find($id);
$user->name = $request->name;
$user->position = $request->position;
$user->full_name = $request->full_name;
$user->id_number = $request->id_number;
$user->date_of_birth = $request->date_of_birth;
$user->status = $request->status;
$img_current = 'upload/avatar/' .$request->input('img_current');
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$user->image = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
echo "no file";
}
$user->save();
return redirect('listEmployees');
}
}
My route:
Route::group(['prefix' => 'listEmployees'], function () {
Route::match(['get', 'post'], 'update/{id}', 'EmployeesController#update');
});
Try this code I have
CONTROLLER
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('employees.form_edit', ['user' => User::find($id)]);
else {
$_data = $request->validate([
'name' => ['required'].
'full_name' => ['required'],
'id_number' => ['required'],
'date_of_birth' => ['required'],
'avatar' => ['mimes:jpeg,jpg,png,gif', 'max:2048'],
'position' => ['nullable'],
'status' => ['nullable']
])
$img_current = 'upload/avatar/' .$request->input('img_current');
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$data['image'] = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
echo "no file";
}
$user = User::find($id);
$user->update($_data);
return redirect('listEmployees');
}
}
VIEW
#if ($errors->any())
<div class="alert alert-warning">
#foreach ($errors->all() as $error)
{{$error}} <br>
#endforeach
</div>
#endif
Before you go further with this problem you need to clean up your code a little bit.
First of all you dont need to check the request->method if you have already made the route "Route::update" (laravel takes care of it).
Second: use laravel form-request and make your controller much more cleaner and readable(php artisan make:request ModelNameRequest)
Third: you dont need to redirect user to manually if you want to redirect to back(), again laravel takes care of it, it will redirect back() if the validator fails with and array of $errors.
any ways this is the code that may work:
public function update(Request $request, $id)
{
$rules = [
'name' => 'required',
'full_name' => 'required',
'id_number' => 'required',
'date_of_birth' => 'required',
'avatar' => 'mimes:jpeg,jpg,png,gif|max:2048'
];
// if the validation failes, laravel redirects back with a collection of $errors
$this->validate($request->all(), $rules);
// you probably want to use User::create($request->only('input1', 'input2', ...);
$user = User::find($id);
$user->name = $request->name;
$user->position = $request->position;
$user->full_name = $request->full_name;
$user->id_number = $request->id_number;
$user->date_of_birth = $request->date_of_birth;
$user->status = $request->status;
$img_current = 'upload/avatar/' .$request->input('img_current');
// use a good package for storing your files like Mediable to make it easy.
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$user->image = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
//TODO: you should not echo some thing here, you should use session()->flash()
session()->flash('message', 'You did not select any file.');
}
$user->save();
return redirect('listEmployees');
}
i solve this problem by change redirect function to
return redirect()->action(
'EmployeesController#update', ['id' => $id]
)
thank all guy

Woocommerce API connection to place order button

I am trying to connect to an api using the code below, so when the customer clicks on the "place order" button on the Woocommerce checkout page, I am getting a "please try again" error:
var amount = <?php global $woocommerce; print WC()->cart->total; ?>;
var merchantOrderId = '<?php echo print time(); ?>';
var apiKey = 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t';
renderMMoneyPaymentButton(amount, merchantOrderId, apiKey);
I am trying to pass this information to the api via this function but I am not getting a successful connection.
public function process_payment( $order_id ) {
global $woocommerce;
// we need it to get any order detailes
$order = new WC_Order($order_id);
/*
* Array with parameters for API interaction
*/
$args = array(
'amount' => '<?php global $woocommerce; print WC()->cart->total; ?>',
'merchant_order_id' => '<?php print time(); ?>',
'api_Key' => 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t',
'currency' => 'BBD',
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', $args );
if( !is_wp_error( $response ) ) {
$body = json_decode( $response['body'], true );
// it could be different depending on your payment processor
if ( $body ['$response'] == 'APPROVED') {
// we received the payment
$order->payment_complete();
$order->reduce_order_stock();
// some notes to customer (replace true with false to make it private)
$order->add_order_note( 'Thanks for your payment!!!!', true );
// Empty cart
$woocommerce->cart->empty_cart();
// Redirect to the thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} else {
wc_add_notice( 'Please try again.', 'error' );
return;
}
} else {
wc_add_notice( 'Connection error.', 'error' );
return;
}
}
let me know what i am doing wrong much appreciated also this is the other script as well
function renderMMoneyPaymentButton(amount, merchantOrderId, apiKey) {
let paymentParams = {
amount: amount,
api_key: apiKey,
currency: 'BBD',
merchant_order_id: merchantOrderId,
onCancel: function () { console.log('Modal closed'); },
onError: function(error) { console.log('Error', error); },
onPaid: function (invoice) { console.log('Payment complete', invoice); }
};
// "mMoney" window global provided by sourcing mmoney-payment.js script.
// Attach the button to the empty element.
mMoney.payment.button.render(paymentParams, '#mmoney-payment-button');
}
1) In your first snippet code you are using javascript and you need to get the order Id and then the order total… You can only get the Order ID after the order is placed…
There is an answer example here.
2) Your 2nd public function involves only PHP… There are some errors and mistakes in this code. Try the following revisited code instead:
public function process_payment( $order_id ) {
// Get The WC_Order Object instance
$order = wc_get_order( $order_id );
/*
* Array with parameters for API interaction
*/
$args = array(
'amount' => $order->get_total(),
'merchant_order_id' => $order_id,
'api_Key' => 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t',
'currency' => $order->get_currency(),
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', $args );
if( !is_wp_error( $response ) ) {
$body = json_decode( $response['body'], true );
// it could be different depending on your payment processor
if ( $body ['$response'] == 'APPROVED') {
// we received the payment
$order->payment_complete();
$order->reduce_order_stock();
// some notes to customer (replace true with false to make it private)
$order->add_order_note( 'Thanks for your payment!!!!', true );
// Empty cart
$woocommerce->cart->empty_cart();
// Redirect to the thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} else {
wc_add_notice( 'Please try again.', 'error' );
return;
}
} else {
wc_add_notice( 'Connection error.', 'error' );
return;
}
}
It should better work.

How to send mail depending on radio button value in codeigniter?

I have one selection form in my application..in that i have four fields one is selection,comments,results,and two radio buttons with selected and selected..
So what I want to do is when person clicked on the selected radio button I need to send selected mail..if person selected not selected radio button need to send mail not selected mail..
My Controller code :
public function requirement()
{
$this->load->model('RequirementModel');
$data['user'] = $this->RequirementModel->getusers();
$this->load->view('Requirements/requirements', $data);
$insert = array(
'role_name' => $this->input->post('role_name'),
'vacancies' => $this->input->post('vacancies'),
'experience' => $this->input->post('experience'),
'jd' => $this->input->post('jd'),
'hiring_contact_name' => $this->input->post('hiring_contact_name'),
'hiring_contact_number' => $this->input->post('hiring_contact_number'),
'user_id' => implode(',', $this->input->post('user_id')),
);
$this->RequirementModel->add_requirement($insert);
$all_users = $this->input->post('user_id');
foreach ($all_users as $key) {
$get_email = $this->RequirementModel->get_user_email_by_id($key);
$role_name = $this->input->post('role_name');
$vacancies = $this->input->post('vacancies');
$experience = $this->input->post('experience');
$jd = $this->input->post('jd');
$hiring_contact_name = $this->input->post('hiring_contact_name');
$hiring_contact_number = $this->input->post('hiring_contact_number');
$config = array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://md-in-42.webhostbox.net',
'smtp_port' => 465,
'smtp_user' => 'test3#clozloop.com',
'smtp_pass' => 'test3',
);
$this->load->library('email', $config);
$this->email->set_mailtype("html");
$this->email->from('test3#clozloop.com', 'bharathi');
$this->email->to($get_email);
$this->email->subject('this is our requirements pls go through it');
$link = 'Click on this link - Click Here';
$this->email->message($link);
// $this->email->message("Dear,\n\nRole Name:$role_name, Vacancies:$vacancies,experience:$experience,jd:$jd,hiring_contact_number:$hiring_contact_number,hiring_contact_name:$hiring_contact_name.\n\nThanks, \nGlobaalign.");
//$this->email->send();
//print_r($get_email);
if ($this->email->send()) {
echo "email sent";
} else {
echo "email failed";
}
}
please help me how to do this..
Thank you
Here is the solution:
if($data['selection_process']==1)
{
//send selected mail
}
else
{
//send not selected mail
}

Send and image from PHP to Javascript (JSON)

I'm trying to make a "meal" in my DB, so in my website i made a form with a name, and a picture. This is the code of the form :
<?php
$new_meal_title = htmlentities($_POST["new_meal_title"]);
$new_meal_img = htmlentities($_POST["new_meal_img"]);
$data = array(
'new_meal_title' => $new_meal_title,
'new_meal_img' => base64_encode($new_meal_img)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents(constant("API_URL")."/meal", false, $context);
if($result === FALSE){
var_dump($result);
}
$json = json_decode($result);
if($json->success == "true"){
header('Location: ../../');
return;
}
else{
echo $json->message;
}
header('Location: ../../');
?>
The form is sending data to my Node API. My Question is, how to save into a folder the image path through form in Javascript after it has been received in JSON.
Thanks for your help, i just had to change this line :
$new_meal_img = htmlentities($_POST["new_meal_img"]);
By
$new_meal_img = $_FILES['new_meal_img']["tmp_name"];
And
'new_meal_img' => base64_encode($new_meal_img)
By
'new_meal_img' => base64_encode(file_get_contents($new_meal_img))

Categories

Resources