April 21, 2013

Proper Form Input Sanitation

Undermine2k’s Questions:

I have form fields i’m gathering from my form using

 var dataString = $("form").serialize();

I am then sending this over to my controller as dataType “html”

The var_dump for my dataString looks like this (so far, but it will contain email address, select options, etc)

array(3) {
  ["username"]=>
  string(5) "mikey"
  ["firstname"]=>
  string(4) "tes%"
  ["lastname"]=>
  string(6) "tester" }

my question is as follows: What is the proper method of form sanitation i should be using before I send data to my model? I know I need to strip special characters and the like, is there some prepackaged class I should be using?

Do I need to break my data up like

  $username =  trim(Array[0]) ; 

Enable XSS Filtering on application/config/config.php

$config['global_xss_filtering'] = TRUE;
March 19, 2013

php difference between 1 and '1'

Question by Blaze Tama

I have struggle with this problem for hours. I have this method my model (codeigniter) :

public function get_umat($kelas1 = 0, $kelas2 = 0) {
    $this->db->select('*');
    $this->db->from('msumat');
    $this->db->join('mskelas', 'msumat.kelas_id = mskelas.kelas_id');

    if($kelas1 != 0)
    {
        echo $kelas1;
        var_dump($kelas1);
        $this->db->where('mskelas.kelas_id', $kelas1);
    }
    else if($kelas2 !=0)
    {
        echo '2';
        $this->db->where('mskelas.kelas_id', $kelas2);
    }
    else if($kelas1 != 0 && $kelas2 !=0)
    {
        echo '3';
        $this->db->where('mskelas.kelas_id BETWEEN $kelas1 AND $kelas2');
    }

    return $this->db->get();
}

EDIT :
The one that not working is in this line of code (taken from above) :

$this->db->where('mskelas.kelas_id', $kelas1);

Its not working when i called this method in my controller, like this :

$this->backend_m->get_umat($_POST['ddl_kelas1'], $_POST['ddl_kelas1']);

I get ‘1’(String) when i vardump the ($_POST['ddl_kelas1']

Then i try to change the parameter in the controller, but its still not working :

 $this->backend_m->get_umat(1, $_POST['ddl_kelas1']);

Desperately, i tried to change the parameter directly in the model, and its working :

public function get_umat($kelas1 = 1, $kelas2 = 0)

Whats going on here?i think it has something to do with the difference of 1 (int) and ‘1’ (String). Thanks 😀

Answer by Starx

Cast your variables as integer.

$this->backend_m->get_umat((int)$_POST['ddl_kelas1'], (int)$_POST['ddl_kelas1']);
February 28, 2013

Code Igniter : base_url() at CSS file doesn't work

Question by Esgi Dend HigherCloud

base_url() doesn’t work at CSS file…

here’s my php :

<link rel="stylesheet" type="text/css" href="<?=base_url()?>css/style.css"/>
<body>
</body>

here’s my css/style.css :

body {
  background:#356aa0 url(<?=base_url()?>img/background.png) repeat-x;
  color:#fff;
}

the text color change to white, but the image doesn’t show up…
if i use url(../img/background.png), it show up…
but when i open url localhost/project/index.php/control/function/var1/var2, it doesn’t show up…

It’s Solved, Thanks every one… :]

i make php file at view folder like this :

<?php header("content-type: text/css"); ?>

body {
    background:url(<?=base_url()?>img/background.png);
}

and i load the php file i just make with function at controller, and then i link it :

<link type="text/css" rel="stylesheet" href="<?=base_url()?>control/style.php"/>

It’s work, Thanks guys…

Answer by Starx

CSS file does not get parse as PHP file. If you really want to do something like that, rename your file as styles.php

OPEN the page and add

header("content-type: text/css");

This tells the page to be treated as a text based CSS file. Then you can simple echo your remaining CSS like

echo "
body {
....
....
";

To fix the base_url() not being accessible from styles.php set a session variable to keep that. You can keep this on your index.php of codeignitor.

$_SESSION['base_url'] = base_url();

Now, use this inside styles.php.

background: url("<?php echo $_SESSION['base_url']; ?>"/../../some.jpg");
November 9, 2012

Extending the Session Library in Codeigniter 3

Question by luv2Code

I’ve been using CI for a while now and recently upgraded to CI 3. I noticed the Session library has now been moved to a folder.
I used to have my own MY_Session.php file in the application/libraries folder that extended the default CI library.

I also use the autoload.php file to autoload my session library.
This no longer works, as I get Unable to load the requested class: Session.

If I remove MY_Session.php file, then the pages load, but then I’ll be missing my extended functionality.

Does anyone know how exactly to extend the session library in CI 3?

Answer by Starx

You can do this similar to extending other core components.

class MY_Session extends CI_Session {

    function __construct() 
    {
        parent::__construct();
        echo "In extended the session";
    }
}  

Make sure you load the session library as well. Like

$autoload['libraries'] = array('database','session');

Also, Unable to load the requested class: Session are generally triggered for the two reasons.

  • CI can’t fine the session
  • You haven’t autoloaded the library

Also, make sure you have a encryption key on your config.php

$config['encryption_key'] = 'xxxxxxxxxxxxxxxxxxxxxxx';
November 1, 2012

Using numeric indices to pass data from controller to view

Question by raheel shan

I have a simple question. Let me explain
We use this to pass data from controller to view

function index(){

    $data['title'] = 'This is title';
    $data['message'] = 'This is message';
    $this->load->view('test',$data);
}

Here we are using Associative Array to pass data
And now this function again and use indexed array instead of Associative Array

function index(){

    $data[] = 'This is title';
    $data[] = 'This is message';
    $this->load->view('test',$data);
}   

And now in View this does not work.

echo $data[0];
echo '<br>';
echo $data[1];

i only want to know if why this does not work. And in the user guide i never read that associative array is necessary.

Answer by Starx

The view data are converted into variables when parsed. A similar result of what extract() function of PHP gives. For example:

$data['title'] = 'This is the title';

will be accessible directly as $title not $data['title']. In fact, if you look at the sources, you will find it does uses extract() and similar conversion happens on your case to, but since variable $0 and $1 are invalid so they are not available.

Stick to string indexing. If that is not an option, then you might want to prefix something before the texts like:

$data['d0'] = 'This is the title';

Read the manual here its quoted. However, you can pass an array instead of a string and giving the exact result of what you want.

$data['data'] = array('This is the title', 'This is the description');

Now, this you will be access using $data[0] and $data[1].

October 27, 2012

How to solve a session expiration issue

Question by user1295167

I am doing a site which has a problem with session expire issue. The form contain almost 50 input fields , I have done it in ajax. I have given the user checkings in page reload the problem is that session and cookies are setting is done when page reloads,

How can I check whether user logined or not without lossing data? Is there any ajax functions
to retain session?

Answer by Starx

One way of solving this would be to increase the session timeout.

ini_set('session.gc_maxlifetime', '3600'); //Assign the time in seconds
September 18, 2012

Failed to reload content via Ajax

Question by Dr.Kameleon

OK, so basically this is my issue :

  • I’ve got a dynamic page with a table in it
  • When the user clicks to delete an entry, the entry is deleted from the db and the table is reloaded (via a controller) using Ajax
  • However, even when the content is re-fetched, it keeps showing the PREVIOUS version of my contents (as if the page was somehow cached?). If I reload the whole page, it shows up alright…

What could be going on?

Answer by Bardo

Are you using Chrome?

I’ve found similar behaviours when using ajax calls on Chrome.

If you are using jQuery to do the ajax call you can use the attribute cache: false for the method ajax to avoid this behaviour.

Answer by Starx

Its actually a caching related problem. So, to ensure this, just emulate fresh URI like

$.post("yourupdatepage.php?r="+(Math.random() * (1000 - 1) + 1), 
  ...
);
August 26, 2012

Singleton and class instantiation in php

Question by Bojan Savic

There is a class like this in codeigniter framework ( I edited it to be more clear, full function is here http://pastebin.com/K33amh7r):

function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
    {
        static $_classes = array();

        // Does the class exist?  If so, we're done...
        if (isset($_classes[$class]))
        {
            return $_classes[$class];
        }


        is_loaded($class);

        $_classes[$class] = new $name();
        return $_classes[$class];

    }

So, first time when class is loaded ( passed to this function), it will be saved to this static variable. Next time when the same class is loaded, this function checks if class exists already ( if it’s already assigned to static, cached, I’m not sure how in memory is this stored) and if it exists, it’s loaded ( NOT *instantiated* again )

As far as I can see, the only purpose is to save time or memory and not instantiate the same class twice.

My question here is: Does really instantiating a class can take up memory or consume loading time so it has to be cached like this?

Answer by ctrahey

CodeIgniter is is geared for rapid prototyping, and is really not a good example of enterprise patterns in almost any cases. This behavior is related to their design choice of the relationship the “controller” has to almost all other objects; namely that there is exactly one of almost anything (only one instance of controller, only one instance of each library, etc). This design choice is more for rapid development (justified by the developer “not having to keep track of as much” or some such…).

Basically, there is memory saved by not instantiating an object (as much memory as it takes to store the object’s instance variables) and if the object’s constructor tries to do a fair bit of work, you can save time, too.

However, the appropriateness of the single-instance imperative is clearly not universal; sometimes you really do want a new instance. When you can justify this, choose a better framework.

Answer by Starx

Its rather a simple concept, utilizing singleton-pattern it makes sure that one class is instantiated only once during an application’s execution cycle.

This sort of concept apply for libraries more. Lets see a basic example:

class Authenticate {
     public function login($username, $password) {
        ....
     }

     public function logout() {

     }
}

Now, through a execution of a page, there is hardly any case that the object of the above class, needs to be created more than once. The main thing to understand is Utilization of resources

And YES, instantiating same class over and over again will without a doubt add up in the memory, although it might be negligible like in the example I have shown, but it does affect.

May 13, 2012

Make counter in sql query

Question by Viktors Golubevs

I am using codeigniter and have working query which take user 3 images. I want to make a count an give every image a number 1,2,3,4,5,6,7 … and want that query output

-number (count),
-id,
-image,
-date

my sql query :

function bar_images_first($user_id)
{   
    $sql = "SELECT id, image, UNIX_TIMESTAMP(date) as date FROM images WHERE user_id = 3 LIMIT 3";
    $query = $this->db->query($sql, $user_id);
    return $query->result_array();
}

Is it possible to do counter in query?

Answer by Starx

It is possible by setting a SQL parameter as

SET @cnt := 0;
SELECT
    @cnt := @cnt + 1,
    id,
    image,
    UNIX_TIMESTAMP(date) as date 
FROM images WHERE user_id = 3 LIMIT 3";

But such multiple statements cannot be executed from the PHP’s mysql_query() method. But, mysqli function like mysqli_multi_query() does allow to execute multiple queries too, so if possible use mysqli method rather than the AR methods.

However, you can run multiple sets of query one by one.

$query = array(
    "SET @cnt := 0;",
    "SELECT
        @cnt := @cnt + 1,
        id,
        image,
        UNIX_TIMESTAMP(date) as date 
    FROM images WHERE user_id = 3 LIMIT 3"
);

foreach($query as $qry) {
     $result= $this->db->query($qry);
     //.........
}
April 30, 2012

How do I pass a javascript variable to php and reload a frame

Question by bisslad

Ok this may sound a little weird but what i have is a frameset generated by php with codeigniter framework.

In one frame i am displaying rows of database query results with links attached to the row index of each record.

What I want to happen, is that you click one of the links and it brings up a more detailed summary of the record in the right hand frame.

While I am aware of the fact that php is server side etc. i was trying to make the link reload the right hand frame with the value of the index from the left hand side, then within the controller i can query the database using the index and push back the same summary page with the full record.

Answer by Starx

You need to send an AJAX request to the server with the variable. You can google on How to send ajax request to server.

However, Here is a simple example of this, using jQuery

$.post("/next/page", {
   'variable1' : 'value1'
}, function(data) {
   //on success handler
});
...

Please fill the form - I will response as fast as I can!