How to access DB config in CodeIgniter? - codeigniter

In my application, I need to know what values are assigned to the DB config items such as database, username, etc. How do I access those information?

I don't have enough rep to comment on Matt Browne's correct answer but just adding a bit incase anyone forgets...
load the db driver like so first:
$this->load->database();
then you can easily access what you need:
$this->db->hostname
$this->db->username
$this->db->password
$this->db->database

Pretty much all the config values are accessible via $this->db (take a look at system/database/DB_driver.php).
That's what worked for me...none of the other suggestions here did.
As an example
$config = [
'host' => $this->db->hostname,
'port' => '3306',
'username' => $this->db->username,
'password' => $this->db->password,
'database' => $this->db->database
];

In case you have multiple database connection groups defined in config/database.php, for eg :
$db['dbname']['hostname'] = "localhost";
$db['dbname']['username'] = "root";
$db['dbname']['password'] = "root";
$db['dbname']['database'] = "web_dbname";
$db['dbname_readonly']['hostname'] = "localhost";
$db['dbname_readonly']['username'] = "root";
$db['dbname_readonly']['password'] = "root";
$db['dbname_readonly']['database'] = "web_dbname_readonly";
If you want to use the connection params of any particular db in a controller or model:
$db = $this->load->database('dbname');
If you want to use in a helper or library :
$ci = &get_instance();
$db = $ci->load->database('dbname');
The connection params will be available as $db->hostname, $db->username etc.

I stumbled across this, looking for a way to find all of the DB settings. Was not able to find a solution on-line, but found some useful code in system/database/DB.php
Here's my approach, get the contents of the entire database config:
if ( ! file_exists($f = APPPATH.'config/'.ENVIRONMENT.'/database.php')
&& ! file_exists($f = APPPATH.'config/database.php'))
{
show_error('The configuration file database.php does not exist.');
}
include($f);
// Use a NEW variable.
// Because $db is a reserved name!!
$db_settings = $db;
foreach($db_settings as $key => $value) {
// .. do something with .. $this->database->load($key);
// .. do something with .. $value['database'];
// .. do something with .. $value['password'];
}

You should be able to get at your configuration setting like this :
$this->config['env']

You can retrieve it with this:
http://codeigniter.com/user_guide/libraries/config.html
$this->config->item('item name');

Related

security on insert batch? codeigniter

can anyone know how to preventing user input, on codeigniter if i use insert_batch? sorry bad english
code like this
$data[] = array(
'id_invoice' => $this->input->post('id_invoice'),
'id_product' => $key['id_product'],
'id_fabrics' => $key['id_fabric'],
'id_option' => $id_option,
'name' => $key['name'],
'number' => $key['number'],
'id_size' => $key['size'],
'comment' => $key['comment']);
and use insert batch like this
$this->orders->insert_order_mix($data);
So Simple You can remove abuse tags and data from user input
//Change This
$this->orders->insert_order_mix($data);
// to
$data = $this->security->xss_clean($data); // You have to clean Data with XSS Filtering
$this->orders->insert_order_mix($data);
This method Clean your all abuse data with [removed] keyword
if user can input any script then XSS filtering remove as per below
$name = '<script>Your Name</script>';
echo $name; // Output : <script>Your Name</script>
// But you use XSS then output is change as per below
$name = '<script>Your Name</script>';
$name = $this->security->xss_clean($name);
echo $name; // Output : [removed]Your Name[removed]
Or You can use very simple with edit your config file
// Change global_xss_filtering value FALSE to TRUE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = TRUE;
I think you are confused with the concept of Batch Insert. Please READ THIS to get a good understanding of Batch Insert. Now for your issue, it's very good to be concerned about security these days as said
Always filter input and escape output, Never trust data.
You can Use Codeigniter Security Class to secure your data.
E.g
$data=$this->security->xss_clean($this->input->post());
OR
$postData=$this->input->post();
$data=$this->security->xss_clean($postData);
Furthermore you can avoid Cross Site Request Forgery by using CSRF token in your Forms
Thanks for your answer, i am not sure about your answer because i am using ajax to get data, and data is on array format, and this is my code to process on controller
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
} else {
$input = $this->input->post('ar_dat');
$option = $this->input->post('list_option');
if ($option == null){
$id_option = '';
} else {
$id_option = implode(',',$option);
}
foreach ($input as $key) {
$data[] = array(
'id_invoice' => $this->input->post('id_invoice'),
'id_product' => $this->input->post('id_product'),
'id_fabrics' => $this->input->post('id_fabric'),
'id_option' => $id_option,
'name' => $key['name'],
'number' => $key['number'],
'id_size' => $key['size'],
'comment' => $key['comment']);
}
$this->orders->insert_order_uniform($data);
}

How to change value of a request parameter in laravel

I need to change value of my request parameter like this:
$request->name = "My Value!";
I use this code but does not work:
$request->offsetSet('img', $img);
Try to:
$requestData = $request->all();
$requestData['img'] = $img;
Another way to do it:
$request->merge(['img' => $img]);
Thanks to #JoelHinz for this.
If you want to add or overwrite nested data:
$data['some']['thing'] = 'value';
$request->merge($data);
If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request
Use merge():
$request->merge([
'user_id' => $modified_user_id_here,
]);
Simple! No need to transfer the entire $request->all() to another variable.
Read more about Laravel's merge() here:
https://laravel.com/docs/collections#method-merge
If you need to customize the request
$data = $request->all();
you can pass the name of the field and the value
$data['product_ref_code'] = 1650;
and finally pass the new request
$last = Product::create($data);
If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel
$request->replace(['property to update' => $newValue]);
Use add
$request->request->add(['img' => $img]);
If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().
namespace App\Http\Requests\Admin\Category;
class CategoryRequest extends AbstractRequest
{
protected function prepareForValidation()
{
if ( ! $this->get('url')) {
$this->merge([
'url' => $this->get('name'),
]);
}
$this->merge([
'url' => \Str::slug($this->get('url')),
'active' => (int)$this->get('active'),
]);
}
}
I hope this information will be useful to somebody.
It work for me
$request = new Request();
$request->headers->set('content-type', 'application/json');
$request->initialize(['yourParam' => 2]);
check output
$queryParams = $request->query();
dd($queryParams['yourParam']); // 2
Great answers here but I needed to replace a value in a JSON request. After a little digging into the code, I came up with the following code. Let me know if I'm doing something dumb.
$json = $request->json()->all();
$json['field'] = 'new value';
$request->json()->replace($json);
Try that :
$request["name"] = "My New Value";
$request["img"] = $img;
It's worked in Laravel 8.
Also, make sure to update the model class.
Item
{
fillable=[
'img',
... // other attributes
];
}
in case of updating an item of object you can write the lines bellow
$Obj = $request->data;
$Obj['item'] = value;

How to delete session in cakephp 3.0?

all code is in one controller
My code goes like this.
public function login()
{
$session = $this->request->session();
$session_event_id = $session->read('Events.event_id');
$session_division_id = $session->read('Events.division_id');
if(!$session_event_id || !$session_division_id) {
$event_table = TableRegistry::get('Events');
$event = $event_table->find('all', ['fields' => ['id'], 'order' => 'id desc'])->first();
$session->write('Events.event_id', $event->id);
$session_event_id = $session->read('Events.event_id');
$division_table = TableRegistry::get('Divisions');
$division = $division_table->find('all',['fields' => ['id'], 'conditions' => ['event_id' => $event->id]])->first();
$session->write('Events.division_id', $division->id);
$session_division_id = $session->read('Events.division_id');
}
}
By above code i am able to write and read session values but while logout i want to delete those session data
public function logout()
{
$session = $this->request->session();
$this->$session->delete();
return $this->redirect($this->Auth->logout());
}
Warning (4096): Object of class Cake\Network\Session could not be
converted to string [APP/Controller/UsersController.php, line 56]
Notice (8): Object of class Cake\Network\Session to string conversion
[APP/Controller/UsersController.php, line 56]
Error: Call to a member function delete() on a non-object File
/var/www/html/MEX/src/Controller/UsersController.php
You're looking for $this->request->session()->destroy();
http://book.cakephp.org/3.0/en/development/sessions.html#destroying-the-session
Just a tip - there's not much of a point for storing a variable $session for a function that small, where the reuse of $session isn't necessary. The only case I'd store $this->request->session(); in a variable is when I'm accessing the session for multiple read and writes all in the same function.
(As far as the error is concerned, #Eagle is correct in that you're referencing '$this' twice by the use of that stored variable.)
Thank You for your supports and help finally i found solution of my problem by myself
$session = $this->request->session();
$session->delete('Events.event_id');
$session->delete('Events.division_id');
by doing so, i am able to clear session data. Thank you

CodeIgniter: unset all userdata, but not destroy the session

Is there a way to unset ALL userdata in a session without having to use session destroy? I'm trying to log my user out and need to unset all userdata one at a time. It's becoming tedious to keep track of all possible userdata set in session. I just want to unset everything that might have been set in userdata.
This is very simple!
$this->session->unset_userdata('some_name');
or
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
I hope this helps!
Edit: It looks like you actually don't keep track of anything in your session (kind of strange?). You could call this function I wrote up:
function unset_only() {
$user_data = $this->session->all_userdata();
foreach ($user_data as $key => $value) {
if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
$this->session->unset_userdata($key);
}
}
}
Of course, that assumes you use the default CI session setup though.
Copied from codeigniter forum:
All it does is kills the users cookie, but the userdata will
remain within the session class until the end of the current request.
The session will be reinitialised on the next request, and there will
be no userdata available. Basically, all it does is severs the link
between the user and the server session, but the data still remains
until the end of the request.
If it’s that much of an issue, you can do this:
$this->session->userdata = array();
I manage it please try it .
$this->load->library('session');
// write parameter your session data
$this->session->unset_userdata('sessiondata');
// if you want to session unset group then try it
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
You can try this one.
In the latest version above code is not working.
$unset_array_items = array('token_id', 'last_id');
$this->session->unset_userdata($unset_array_items);

code igniter :: send url as param?

I am creating an ajax function to edit some settings.
these must be handled via the url
(i.e)
the url would be http://example.com/setting1/setting2/setting3
This works fine but.
One of the settings is a url.
How could I pass this in this way?
this might work
$url = 'http://stackoverflow.com/questions/4245416/code-igniter-send-url-as-param';
$encoded = base64_encode($url);
//aHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy80MjQ1NDE2L2NvZGUtaWduaXRlci1zZW5kLXVybC1hcy1wYXJhbQ==
// Make your URL
$my_url = "site.com/controller/method/params/params/" . $encoded;
// redirect or whatever
$encoded_url = $this->uri->segment(4); // (or wherever the URL is)
$url = base64_decode($encoded_url);
// http://stackoverflow.com/questions/4245416/code-igniter-send-url-as-param
Look for the URI Class: http://codeigniter.com/user_guide/libraries/uri.html
From index.php/user/search/name/joe/location/UK/gender/male
You can get:
[array]
(
'name' => 'joe'
'location' => 'UK'
'gender' => 'male'
)
Using:
$array = $this->uri->uri_to_assoc(3);
You can also find useful $this->uri->segment_array() .

Resources