CodeIgniter Setting config item that is in array - codeigniter

So I just started using CodeIgniter... and got stuck in setting config item
I have read that replacing the value of a config item is as easy as this:
$this->config->set_item('item_name', 'item_value');
But what if I want to set a config item that is part of an array of config items... like this one:
$api_config = $this->config->load('api'); //loading the created configuration under config folder
api.php
$facebook['app_id'] = '123213213';
$facebook['api_key'] = '123123WERWERWE123123';
$config['facebook'] = $facebook;
and I want to dynamically replace app_id.

Sure you can do it, but you'll need to manually unwrap/rewrap the config item. For example, given this config file:
$f['a'] = "1";
$f['b'] = "2";
$config['t'] = $f;
And this controller function:
function t()
{
var_dump($this->config->item("t"));
echo "<br>";
$v = $this->config->item("t");
$v['a'] = "3";
$this->config->set_item('t', $v);
var_dump($this->config->item("t"));
}
You will get this output:
array(2) { ["a"]=> string(1) "1" ["b"]=> string(1) "2" }
array(2) { ["a"]=> string(1) "3" ["b"]=> string(1) "2" }
One thing to note: the actual config value in the file hasn't changed: you will need to re-apply your change on each request.

Unfortunately, you can't do that as you have things right now.
A look at the code in question:
// from CI 2, CI 1 has no differences which will effect the current situation
include($file_path);
if ( ! isset($config) OR ! is_array($config))
{
if ($fail_gracefully === TRUE)
{
return FALSE;
}
show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.');
}
if ($use_sections === TRUE)
{
if (isset($this->config[$file]))
{
$this->config[$file] = array_merge($this->config[$file], $config);
}
else
{
$this->config[$file] = $config;
}
}
else
{
$this->config = array_merge($this->config, $config);
}
As you can see, the only value which is picked up from the config file is $config. CI pretty much discards everything else. You should not be able to access that value through config for reading or writing.
Your options are that you can have a facebook config file, you can store the facebook array as a value in the $config variable in the api config file, or you can store the value as some special key like 'facebook_app_id' in the same file. You'll have to decide which option is best for your needs, but I would be inclined to store the value as 'facebook_app_id'.

$this->config->load('api', true);//load config first
//begin set new value
$this->config->set_item('app_Ckey',‘your new value’);
$this->config->set_item('app_id',‘your new value’);
$this->load->library('api');
echo $this->config->item('app_Ckey');

Related

Check if Config item exists

I would like to know if there is a way to check if a config item exists.
I have a case where I refer to some config items in the config/custom.php file, and others in a database table.
The concept is to make use of existing config items that exist in config/custom.php, and when they don't exist, I pull them from my database.
$config = Config::get($configtype . '.' . $configname);
if (!$config){
// if config not found, then get it from the database
$configrecord = Newconfigs::where(['name' => $configname])->get()->first();
if (!$configrecord){
$config = false;
} else{
$config = $configrecord->value;
}
}
return ($config);
As you can see, doing it this way will not cater for config values of NULL of FALSE.
I would like to do something like this in my very first line to check if the config "exists" in the file...
If(Config::exists($configtype . '.' . $configname)){ } else{ //get from database }
Is there such a thing?
After searching found a solution. Here is the solution that can help
if (config()->has('some.key')) {
// Get configuration value from config file
} else {
// Get configuration value from database
}

Terraform - Adding Validation for type = map(object()) in variables.tf

First thanks for this post Adding a default field for type = map(object()) in variavles.tf, this answered the first part of the struggle that I had in getting default values to work with type map(object()). The last part that I am trying to get working is how to do validation of the input values.
terraform {
experiments = [module_variable_optional_attrs]
}
variable "dns_server" {
description = "Add DNS Servers for domain resolution. You can configure a maximum of two servers. Only one can be preferred 'true'."
type = map(object({
preferred = optional(bool)
server = optional(string)
}))
default = {
default = {
preferred = false
server = "198.18.1.1"
}
}
validation {
condition = (
can(regexall("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$", var.dns_server["server"]))
)
error_message = "The DNS Server is not a valid IPv4 Address."
}
}
locals {
dns_server = {
for k, v in var.dns_server : k => {
preferred = coalesce(v.preferred, false)
server = coalesce(v.server, "198.18.1.1")
}
}
}
The defaults value in the variable field I know isn't used but I am using it as a placeholder for the terraform docs output.
I also know what I have above for validation is not correct because if the user used the default server IPv4 that wouldn't be set until the locals definition. I just don't know of a way to do the validation because I my trusty google search hasn't pulled up any similar examples.
The code is located here if you need more details about how it is being used:
https://github.com/scotttyso/terraform-aci-fabric/tree/main/test
If I comment out the validation everything else is working fine. Thanks in advance.
Is this what you are after?
variable "mapobject" {
type = map(object({
cidr_block = string
destination_type = string
}
))
validation {
condition = alltrue([
for o in var.mapobject : contains(["CIDR_BLOCK","NETWORK_SECURITY_GROUP","SERVICE_CIDR_BLOCK"],o.destination_type)]) error_message = "All destination_types must be one of CIDR_BLOCK,NETWORK_SECURITY_GROUP or SERVICE_CIDR_BLOCK!"
}
}
With a variable assignment of
mapobject = {
"r0" = {cidr_block = "10.1.1.0/24",destination_type = "CIDR_BLOCK" }
}
The validation succeeds, where as the following fails (as required)
mapobject = {
"r0" = {cidr_block = "10.1.1.0/24",destination_type = "CIRD_BLOCK" }
}
Error: Invalid value for variable
on main.tf line 86:
86: variable "mapobject" {
All destination_types must be one of CIDR_BLOCK,NETWORK_SECURITY_GROUP or
SERVICE_CIDR_BLOCK!
This was checked by the validation rule at main.tf:93,2-12.
If it is, then kudos goes here: https://discuss.hashicorp.com/t/validate-list-object-variables/18291/2

$_SESSION variables use in queries

I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"

Modify the existing canonical link in header

I am using Joomla 2.5 and I want to change the canonical link in the header.
I do this in category view (components/com_content/category/tmpl/default.php)
$url = JURI::root();
$sch = parse_url($url, PHP_URL_SCHEME);
$server = parse_url($url, PHP_URL_HOST);
$canonical = $this->escape($_SERVER['REQUEST_URI']);
$document->addCustomTag('<link rel="canonical" href="'.$sch.'://'.$server.$canonical.'"/>');
It prints the right canonical, but it also leaves the old canonical link there so that I have 2 canonical links in the header.
How can I change or delete the old canonical link?
I have found the following to work for me with Joomla! 3.2.1. You can directly modify the
$_links
variable in the JHtmlDocument object.
I'm doing a subset of the following in a particular view of my component because the URL that Joomla! is coming up with is not correct.
Hope this helps.
$document = JFactory::getDocument();
foreach($document->_links as $key=> $value)
{
if(is_array($value))
{
if(array_key_exists('relation', $value))
{
if($value['relation'] == 'canonical')
{
// we found the document link that contains the canonical url
// change it!
$canonicalUrl = 'http://www.something.com/index.php/component/my-component-name-here/?view=viewNameHere&parameterNameHere=parameterValueUsedInTheViewRightNow
$document->_links[$canonicalUrl] = $value;
unset($document->_links[$key]);
break;
}
}
}
}
What you probably want to do instead is something like the following:
$doc_data = $document->getHeadData();
$url = JURI::root();
$sch = parse_url($url, PHP_URL_SCHEME);
$server = parse_url($url, PHP_URL_HOST);
$canonical = $this->escape($_SERVER['REQUEST_URI']);
$newtag = '<link rel="canonical" href="'.$sch.'://'.$server.$canonical.'"/>'
$replaced = false;
foreach ($doc_data['custom'] as $key=>$c) {
if (strpos($c, 'rel="canonical"')!==FALSE) {
$doc_data['custom'][$key] = $newtag;
$replaced = true;
}
}
if (!$replaced) {
$doc_data['custom'][] = $newtag;
}
$document->setHeadData($doc_data);
This will grab all of the current head data from the document, including the canonical link that you want to replace. It will search through the custom set (where I'm guessing this will be) and if it finds it, replace it with yours. If it doesn't find it, then it tacks it on at the end. Just in case.
Potential problems with this that I can see right away:
If the tag contained rel='canonical' with single quotes it would not be found, so you may have to adjust that.
The tag may have been placed in a different section of what I've termed $doc_data. You may want to do a var_dump($doc_data}; to confirm the location of the variable in this array.

How can I addslashes() to elements of a multidimensional array? (php)

I have a multidim array from my $_POST but I have to serialize() then save to the database...
Normally, I can serialize but I got some problem with slashes (apostrophe and double quote).
My array seems like this: $array["hu"]["category"]["food"] = "string";
But when the "string" contains "" or '' theres's shit...
I need some short code for add slashes, but thres a lots of wrong solutions out there.
p.s.: I'm a CodeIgniter user.
// update:
function addslashesextended(&$arr_r) {
if (is_array($arr_r)) {
foreach ($arr_r as &$val){
if( is_array($val) ){
addslashesextended($val);
}else{
$val = addslashes($val);
}
}
unset($val);
} else {
$arr_r = addslashes($arr_r);
}
}
Thx!
I think the best solution would be to use the codeigniter input class and active record class . Addslasches/escapes, and most general sanitization will be taken care of for you.
http://codeigniter.com/user_guide/libraries/input.html
http://codeigniter.com/user_guide/database/active_record.html

Resources