Showing posts with label CodeIgniter. Show all posts
Showing posts with label CodeIgniter. Show all posts

Sunday, April 20, 2014

confusion related to HMVC design in codeigniter

There are two main different features that HMVC adds to CodeIgniter which often confuses people:
  1. Modular MVC
  2. Hierarchal MVC
Modular MVC is the feature that most people want to use and is essentially just a way to have a cleaner folder structure.
HMVC is the practise of calling controllers from other controllers without the need for a new HTTP request. This is very rarely useful in my opinion, other than for things like calling a custom 404 page or "widgets".
MMVC adds barely anything to performance, calling a controller via HMVC is obviously almost twice as slow.

Either way neither will be noticeable. If your site is starting to crawl under high traffic then this is one of the last things you'll need to worry about.

Wednesday, November 6, 2013

R.I.P Codeigniter



See my tweet https://twitter.com/raviraj4u/status/398343198151430144 It's really sad that
EllisLab stop support for codeigniter. CI is very fantastic framework and need to take advantages of PHP's upcoming releases which are more mature and stable. Well i have stopped working on CI since last an year ( currently i am working on Android native app development) but i loved it very much and proudly says that i was involved with CI at core level. Here are few links which shows my contribution to codeigniter.


Even some developer made plugins using my CI code. http://getsparks.org/packages/login-cookie/versions/HEAD/show

I wish that it should go with safe hand. Bye bye Codeigniter !!

Friday, October 22, 2010

PHP Application Framework Battle ... CodeIgniter vs. Symfony

I'm familiar with many of the PHP frameworks like symfony,zend,cakePHP,codeigniter and last one which i think it will be good enough specially to design rich web and large scale applications, that is YII http://www.yiiframework.com/features/ at last, I would like share a funny framework built in PHP and that's source code you can even tweet :P checkout this one http://twitto.org/  :-)


We have seen on web that there are so many solutions but i notice that people always ask which ones is good ? Does such a framework  exist who do all jobs well ? Usually my first answer is .. your question is a bit like going to the hardware store and having a conversation like:-


You: I'd like to buy some tools. Staff Member: Ok, great. What are you building? You: Don't know yet. But I'm sure I'll need some tools.
Second it's obviously that there are so many metrics of what good can possibly mean like, disk size on server, amount of code generated for the client, difficulty of installing / configuring process on the server, etc... 


There is absolutely no point in solving a problem until you have a problem. Just code vanilla PHP until you decide some particular task is too hard/messy/etc and a framework will actually help you and, this may go against the "must-have-framework" crowd, but honestly I think for trivial tasks you're typically better rolling your own.


So again ball is on your side .. what are your problems and why you need it ? would you like fancy Web 2.0 site ? or scalability is major concern as your site hits ? Most likely in the form of a big complex MVC framework with plenty of layers that abstracts away your database, your HTML, your Javascript and in the end your application itself. If it is a really good framework it will provide a dozen things you'll never need. I am obviously not a fan of such frameworks. I like stuff I can understand in an instant. Both because it lets me be productive right away and because 6 months from now when I come back to fix something, again I will only need an instant to figure out what is going on.


Why MVC ?  I don't want make you confuse but i found that it's up to you how much you would like build your application scalable and modular  like security and all features that's you want to apply..  see my previous one posts .. 


http://ravirajsblog.blogspot.com/2008/12/world-of-object-oriented-programming.html
http://ravirajsblog.blogspot.com/2008/12/principles-of-mvc-design-pattern.html
http://ravirajsblog.blogspot.com/2008/12/3-tier-architecture.html

I like MVC but Just make sure you avoid the temptation of creating a single monolithic controller. A web application by its very nature is a series of small discrete requests. If you send all of your requests through a single controller on a single machine you have just defeated this very important architecture. Discreteness gives you scalability and modularity.
You can break large problems up into a series of very small and modular solutions and you can deploy these across as many servers as you like. You need to tie them together to some extent most likely through some backend datastore, but keep them as separate as possible. This means you want your views and controllers very close to each other and you want to keep your controllers as small as possible.


So design your goals first.


1. Clean and simple design
          * HTML should look like HTML
          * Keep the PHP code in the views extremely simple: function calls, simple loops and variable substitutions should be all you need
   2. Secure
          * Input validation using pecl/filter as a data firewall
          * When possible, avoid layers and other complexities to make code easier to audit
   3. Fast
          * Avoid include_once and require_once
          * Use APC and apc_store/apc_fetch for caching data that rarely changes
          * Stay with procedural style unless something is truly an object
          * Avoid locks at all costs


Now come to title of post .. one to one "CodeIgniter vs Symfony" comparison .. overall, symfony is more sophisticated (ie. harder to use ... it has 7 times more codebase than codeigniter) while codeIgniter seems more geared to low level of programming and environment but yes symfony has complete features of set that makes it much stronger and scalable.


Finally i summarized and here are few my concerns that you should keep in mind while choosing a framework.


1. choose PHP version > 5.3 
In PHP, an object is destroyed when it goes out of scope. This is normally when the script stops executing or when the function it was created within ends. unset($my_variable); we need to be fine allowing the destructor to handle closing the DB in most situations. The garbage collector or GC in PHP will do all the work you need once the variable goes out of scope or there are zero references to it. To be clear, the GC got a major rework in PHP 5.3.


2. Use PHP's PDO for model http://php.net/pdo


3. Use open source for rich UI work like http://developer.yahoo.net/yui/


4. Use PHP's pecl/filter extension for automagically sanitize all user data


5. Use auto include configuration setting in PHP to avoid include one and required once see http://php.net/manual/en/ini.core.php#ini.auto-prepend-file


6. Use PHP's inbuilt APIs for opt code caching http://php.net/apc_fetch


Clean separation of your views, controller logic and backend model logic is easy to do with PHP. Using above ideas, we should be able to build a clean framework aimed specifically at our requirements instead of trying to refactor a much larger and more complex external framework.


Many frameworks may look very appealing at first glance because they seem to reduce web application development to a couple of trivial steps leading to some code generation and often automatic schema detection, but these same shortcuts are likely to be your bottlenecks as well since they achieve this simplicity by sacrificing flexibility and performance. Nothing is going to build your application for you, no matter what it promises. You are going to have to build it yourself. Instead of starting by fixing the mistakes in some foreign framework and refactoring all the things that don't apply to your environment spend your time building a lean and reusable pattern that fits your requirements directly. In the end I think you will find that your homegrown small framework has saved you time and aggravation and you end up with a better product.

Thursday, June 10, 2010

codeigniter's super object


I hope everybody have seen & get_instance variable while working in codeigniter. I searched and trying
to find out how codeigniter builds super object and how it works internally. Hope we will enjoying it.

CI works by building one 'super-object', it runs  whole program as one big object, in order to eliminate scoping issues. When we start CI, a complex chain of events occurs.  If we set CI installation to create a log, we'll see something like this:-

    1 DEBUG - 2006-10-03 08:56:39 --> Config Class Initialized
    2 DEBUG - 2006-10-03 08:56:39 --> No URI present. Default controller  set.
    3 DEBUG - 2006-10-03 08:56:39 --> Router Class Initialized
    4 DEBUG - 2006-10-03 08:56:39 --> Output Class Initialized
    5 DEBUG - 2006-10-03 08:56:39 --> Input Class Initialized
    6 DEBUG - 2006-10-03 08:56:39 --> Global POST and COOKIE data sanitized
    7 DEBUG - 2006-10-03 08:56:39 --> URI Class Initialized
    8 DEBUG - 2006-10-03 08:56:39 --> Language Class Initialized
    9 DEBUG - 2006-10-03 08:56:39 --> Loader Class Initialized
    10 DEBUG - 2006-10-03 08:56:39 --> Controller Class Initialized
    11 DEBUG - 2006-10-03 08:56:39 --> Helpers loaded: security
    12 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: errors
    13 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: boilerplate
    14 DEBUG - 2006-10-03 08:56:40 --> Helpers loaded: url
    15 DEBUG - 2006-10-03 08:56:40 --> Database Driver Class Initialized
    16 DEBUG - 2006-10-03 08:56:40 --> Model Class Initialized

each time a page request is received over the Internet , CI goes through the same procedure.
We can trace the log through the CI files:-

The index.php file receives a page request. The URL may indicate which controller is required, if not, CI has a default controller (line 2). Index.php makes some basic checks and calls the codeigniter.php file.
  
The codeigniter.php file instantiates the Config, Router, Input, URL, (etc.) classes (lines 1, and 3 to 9). These are called the 'base' classes: we rarely interact directly with them, but they underlie almost everything CI does.
  
codeigniter.php tests to see which version of PHP it is running on, and calls Base4 or Base5 (/codeigniter/Base4(or 5).php). These create a 'singleton' object: one which ensures that a class has only one instance. Each has a public &get_instance() function. Note the &:, this is assignment by reference. So if we assign to the &get_instance() method, it assigns to the single running instance of the class. In other words, it points we to the same pigeonhole. So, instead of setting up lots of new objects, we are starting to build up one 'super-object', which contains everything related to the framework.
  
After a security check, codeigniter.php instantiates the controller that was requested, or a default controller (line 10).

The new class is called $CI. The function specified in the URL (or a default) is then called, and life as we know it starts to wake up and happen. Depending on what we wrote in   controller, CI will then initialize any other classes we need, and 'include' functional scripts we asked for. So in the log above, the model class is initialized. (line 16)

    class my_new_class{
var $base;
My_new_class()
{
   $obj =& get_instance();
   // geolocation code here, returning a value through a switch statement
   //this value is assigned to $local_url
   $this->base = $obj->config->item('base_url);
   $this->base .= $local_url;
}
    }

We've looked at the way CI builds up one 'super-object' to make sure that all the methods and variables we need are automatically available without having to manage them and worry about their scope.

CI makes extensive use of assignment by reference, instantiating one class after another and linking them all together so that we can access them through the 'super-class'. Most of the time, we don't need to know what the 'super-class' is doing, provided that we use CI's 'arrow' notation correctly. We've also looked at how we can write   own classes and still have access to the CI framework.

Wednesday, March 17, 2010

Check how much your PHP code meets the standards ?

Generely we easily check for parse errors in a file using the PHP command line interface and the -l (lowercase L) option.
$ php -l /path/to/code/myfile.inc
No syntax errors detected in /path/to/code/myfile.inc

So code is fine and why do I need check code standered ?

Coding standards  make our code easier to read and maintain, especially when multiple people are working on the same application. we want to ensure to follow some set of coding standards,in my previous company , every SVN commits to email all team members so we fulfill the code review process but sometimes still issues are left. we need some more deep level to review code.

PHP_CodeSniffer is a solution. It's quick and easy way to do that. PHP_CodeSniffer is a replacement for the more manual task of checking coding standards in code reviews. With PHP_CodeSniffer, we can reserve code reviews for the checking of code correctness. if we use it in a regular time interval , we ensures some couple of positive things like
1. Team learn the coding standards and make less mistakes in the future.
2. Team can decide if a coding standard doesn't fit a particular piece of code.

Install and How to use:-  it's pear package so easy to install and we can use it as command line.

phpcs -n --report=summary /var/www/html/shiksha/

Another good tool is PHPMD. it scans PHP source code and looks for potential problems such as possible bugs, suboptimal code or overcomplicated expressions. we can get HTML output of Report as well.


Install and How to use:-  it's pear package so easy to install and we can use it as command line.
phpmd ~/shiksha_head/marketing/  html codesize

Third one is PHPCPD. it is a Copy/Paste Detector (CPD) for PHP code. it's funny tool.

fourth and final one is PHP_Depend. it performs static code analysis on a given source base. Static code analysis means that PHP_Depend first takes the source code and parses it into an easily processable internal data structure. This data structure is normally called an AST (Abstract Syntax Tree), that represents the different statements and elements used in the analyzed source base. Then it takes the generated AST and measures several values, the so called software metrics. what are the software metrics ? They are just the sum of some statements or code fragments found in the analyzed source.
it's also provide some graphical charts that tells about percentage of metrics that current code is followed.

Install and How to use:-  it's pear package so easy to install and we can use it as command line.
pdepend --summary-xml=/tmp/summary.xml   --jdepend-chart=/tmp/jdepend.svg    --overview-pyramid=/tmp/pyramid.svg    /home/raviraj/shiksha_head/marketing/

we have seen some good tools that are really helpful for automated quality testing of code. i have run all these tests in my current  project

Happy coding !!!

Thursday, March 11, 2010

Monday, August 24, 2009

What is Thin Server Architecture ?

IT's simple but much more Smarter than other frameworks ...

Putting the View on the Client (Yes, you have one. It's the browser, silly!)
1) Do not use server-side templating to create the web page
2) Use a classical and simple client-server model, where the client runs in the browser.
3) Separate concerns using protocol between client and server and get a much more efficient and less costly development model.

 
 

Thursday, May 28, 2009

UI Bugs & QA Responsibilities

Anybody who has written code for public use will probably have received at least one bad bug report. Reports that say nothing ("It doesn't work!"), reports that make no sense, reports that don't give enough information,reports that give wrong information. well ... as a coder i felt it's a horrible job to work on UI bugs and one reason is bad bug reports. However, not all bug reports are unpleasant and sometimes we received a wonderfully clear, helpful, informative bug reports.

Quality of Bugs:- depends on following points.
1. The development process (how much time between releases)
2. The product planning (how much change per release)
3. The QA Cycle approach
4. % of bugs would have been found within unit test cases or web services testing?
5. % of bugs platform(dependencies like software, os, browsers etc ) specific? how many are UI bugs ?
6. % of bugs as known issues.

Points that should keep in mind:-
1. Be specific. If you can do the same thing two different ways, state which one you used. "I refreshed page" might mean "I clicked refresh button" or "I pressed F5". Say which you did. Sometimes it matters.
2. Be verbose. Give more information rather than less. If you say too much, the programmer can ignore some of it. If you say too little, they have to come back and ask more questions. Be careful of pronouns. Don't use words like "it", or references like "the window", when it's unclear what they mean.
3.Read what you wrote. Read the report back to yourself, and see if you think it's clear. If you have listed a sequence of actions which should produce the failure, try following them yourself, to see if you missed a step.
4. You report a bug because you want the bug fixed. it may be their fault and your problem, and you might be right to be angry with them, but the bug will get fixed faster if you help us by supplying all the information needed.
5. "It doesn't work."case Give the programmer some credit for basic intelligence, :D if the program really didn't work at all, they would probably have noticed. Since they haven't noticed, it must be working for them. Therefore, either you are doing something differently from them, or your environment is different from theirs. They need information, providing this information is the purpose of a bug report. More information is almost always better than less.
6. "Works for me. So what goes wrong?" case Possibly the fault doesn't show up on every computer, your system and theirs may differ in some way. Possibly you have misunderstood what the program is supposed to do, and you are both looking at exactly the same display but you think it's wrong and they know it's right. So also describe what happened. Tell us exactly what you saw. Tell us why you think what you saw is wrong.
7. What happens if bug gets rejected? Rejected bugs fall into two categories:-
7.1. It was rejected because it was not a bug.
7.2. It was rejected because development team do not feel like working on it. :D

Monday, December 22, 2008

Codeigniter 's Flexibility Part-1

I am looking to test Codeigniter 's Flexibility... actually there are few points that cause me to deep dive in codeigniter.

1. Can we keep associated views/controllers/models in the same folder ?
i.e.
/system/application/modules/MODULENAME/controllers/
/system/application/modules/MODULENAME/models/
/system/application/modules/MODULENAME/views/

2. Can we load and render one controller from within another controller ?

3. Can we call more than one controller per request in codeigniter project ?


I have looked on net ... did some googling ;) and working on it and got a very good response. Hope will get success very soon, till then happy coding and enjoy winter weather...

Saturday, December 13, 2008

CodeIgniter Performance

Performance is usually the bane of any development effort. Things that you put together on a development server simply never seem to stand up to the pounding of real traffic. Once again, however, CodeIgniter comes to your aid with a set of profiling and benchmarking tools that allows you to see how your pages (and even sections of code) perform.

Profiling

If you’re curious about performance of any page, you can turn on profiling and get a detailed report of what’s happening. This is a useful thing to do before a site goes live.To turn on profiling, open your Welcome controller in an editor, and make the following change to the constructor:






Now visit the home page and scroll down. You should see a table giving details on how your application performed. You’ll see entries for controller load time, queries run, and other data. It should look something like Figure.
















Compressing Output

One obvious way to speed up your home page is to turn on output compression. Doing so enables Gzip output compression for faster page loads. All you have to do is set $config[‘compress_output’] to TRUE in config.php, and CodeIgniter will test to see if the server its on supports Gzip compression. If so, then the server will use Gzip to speed things up.

There are two important things to keep in mind, however. Since not all browsers support Gzip compression, it will be ignored by those that can’t handle it. Don’t fret about this, though, because it is only the really old browsers that don’t use HTTP/1.1 or understand the Accept-Encoding header. Here’s a partial list of non-GZIP browsers:
❑ Netscape Navigator 3
❑ Netscape Communicator 4 (but only those before 4.06, and with errors after that version)
❑ Mozilla 0.9 (unless the user manually configures the browser to accept)
❑ Internet Explore 3.x and below
❑ Opera 3.5 and below
❑ Lynx 2.5 and below (some use separate Gzip command lines)
You might look at that list and think to yourself, “Isn’t it time for people to upgrade?” You’d be amazed at how long people hang on to their favorite browser. One more thing about compressing: If you have any white space at the end of your scripts, you’ll start serving blank pages. Make sure that you keep the ends of your scripts tidy.

Caching

CodeIgniter ’s caching engine allows you to take dynamically created pages and save them in their fully rendered states on the server, then reuse those fully rendered pages for a specific amount of time. For example, the first time a user hits a query-intensive page, the page is cached for X amount of time, and
all other visitors use the cached page until the cache expires.
Where are pages cached? Good question. They are written to the /system/cache folder that sits above your application. With high-traffic web sites, caching can give you huge boosts in performance in a short amount of time.
To put in caching, all you need to do is set a caching value for any controller function using the following command:





where X is the number of minutes you want the cache to remain active before it is deleted and reset.That’s it — there’s nothing else to load or configure because caching is part of the Output class and is therefore ready to be used in your application.

Turning Off Profiling

It is time to turn off profiling, as you don’t need it anymore. Simply erase the line from your controller,or set the profiler to FALSE.

Benchmarking
The Benchmark class can be used to mark start and end points in your code and to print out how much time (or how many resources) was used by that code. Benchmarking can be used in controllers, views, and models and are a great way to dig deeply into a performance-based problem.
To start off, open up your footer view (/system/application/views/footer.php), and add the following code to the file:










The elapsed_time() function will tell you how much time it took to render a page, from CodeIgniter framework initialization all the way through final output to the browser. The memory_usage() function will tell you how much memory was used.
Once you’ve loaded the view onto your site, visit one of the category pages. Remember, the home page is cached, so it’s better to visit an uncached page. You should see something like Figure.





According to the benchmarking functions, it took 0.07 seconds (give or take) to render the page, and it used 0 memory. (It could also be showing zero because your copy of PHP didn’t have --enable-memory- limit when it was compiled on the server. If that’s the case, and you want to show this kind of data, you will need to recompile PHP with the --enable-memory-limit flag set. In other words, having to reinstall PHP may or may not be worth your time, depending on the kind of visibility you want on profiling.) This kind of information is good, but what if you were trying to diagnose a more specific problem, like how long a specific query was taking? You could, for example, put the following markers down in your function:








Then, in your footer view, you could use elapsed_time() to print out the results:






According to this example, the getCategory() model function is taking a total of 3/1,000-ths of a second to run.

CodeIgniter at a Glance

I’ll be taking a close look at the main features bundled with the CodeIgniter PHP framework. With it, you can quickly build small to moderate object-oriented applications. Now, it’s time to begin harnessing the real power of CodeIgniter. Ignite yourself and start reading now!

Building web applications with PHP is a pretty simple process. As a PHP developer, you can develop practically anything, including database abstraction layers, form validation programs, file upload applications, and so forth. The list goes on and on.

Once you've mastered the foundations of the object-oriented paradigm and learned how to implement certain common design patterns in real-world conditions, you should be armed with a useful toolkit comprised of all sorts of classes and functions that can be used any number of times.

Although you may not be aware of this fact, your toolkit can be considered a general PHP development framework. The end result of your own efforts and skills as programmer.

However, there are certain situations when the capabilities offered by your own framework simply aren’t good enough to fit the requirements of a particular application. In a case like this, you can either upgrade your framework, which will probably require coding additional classes and functions, or you can pick up a third-party software from the numerous packages available on the web today.

If you choose the latter, then you’ll be confronted with another challenge that will keep your mind spinning in circles. Should I pick up a full-featured framework like Zend, or should I work with a more approachable solution, like CakePHP or WACT?

Actually, the answer to that question depends strongly on what type of project you’re going to develop and how much time you want to spend configuring and learning how to use a particular framework. For instance, Zend is great for building enterprise-level PHP applications, but it's likely that you’ll find it pretty overwhelming to work with at first.

On the other hand, CakePHP can be much easier to set up and use, even though they’re not loaded with all the features offered by Zend. However, in the last few months, a small framework has gained popularity with many PHP programmers due to its ultra-fast learning curve and easy configuration.

It's a solid piece of software written by Rick Ellis in PHP 4. It permits users to develop small and middle-scale PHP applications in minutes (literally) with minimal setup. In addition, CodeIgniter is built around the Model-View-Controller pattern, which allows you to easily separate data from application logic and visual presentation.

Downloading CodeIgniter

You can download the latest and greatest version of CodeIgniter by going to
www.codeigniter.com and clicking the Download CodeIgniter button on the home page.

Now that you have CodeIgniter downloaded and unzipped, take a minute to look at the file structure.

As received, the CodeIgniter root directory contains two files and two folders. The two files are index.php (which you want to keep there no matter what) and a license.txt file, containing CodeIgniter ’s license agreement. The two directories are user_guide/ (containing a version of the online
documentation at www.codeigniter.com) and system/.
A quick note before you delve too much further into that all-important system/ folder: Approximately 100 percent of your web projects will require the use of custom CSS, JavaScript, and image files and folders. The best way to handle all of these assets is to create folders for them at the project root, as
siblings to the system/ folder. This is as good a time as any to create your css/, js/, and images/ folders, so do that now. To make those folders accessible to CodeIgniter, you will also need to create a small .htaccess file in the root folder of your web site.

The system/ Folder

application — The application folder contains the application you’re building. Basically, this folder contains your models, views, controllers, and other code (like helpers and class extensions). In other words, this folder is where you’ll do 99 percent of your work.
cache — The cache folder contains all cached pages for your application.
codeigniter — The codeigniter folder is where CodeIgniter ’s core classes live. You have almost no reason to go in here. All of your work will occur in the application folder. Even if your intent is to extend the CodeIgniter core, you would do it with hooks, and hooks live in the application folder.
database — The database folder contains core database drivers and other database utilities. Again, there’s no good reason for you to be in this folder.
fonts — The fonts folder contains font-related information and utilities. Again, there’s no reason to spend any time here.
helpers — The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers). You’ll make frequent use of helpers in your CodeIgniter career and can even extend helpers thanks to improvements introduced in CodeIgniter version 1.6.
language — The language folder contains language files. You can ignore it for now.
libraries — The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder.
logs — The logs folder is the folder CodeIgniter uses to write error and other logs to.
plugins — The plugins folder contains plugins. Plugins and helpers are very similar, in that they both allow developers to quickly address an issue or create content (like forms, links, etc.). However, the main difference between them is that plugins usually consist of one function, while helpers often have many functions bundled inside them.


Initial Configuration

we should know the ins and outs of the files inside the system/application/config/ folder.

❑ config.php
❑ database.php
❑ autoload.php
❑ routes.php

config.php

The config.php file contains a series of configuration options (all of them stored in a PHP array called, appropriately enough, $config) that CodeIgniter uses to keep track of your application’s information and settings. The first configuration option you need to set inside config.php is the base URL of your application.

The second thing you need to do is set a value for your home page by editing the $config[‘index_page’] configuration option. CodeIgniter ships with a value of “index.php” for this option, which means that index.php will appear in all of your URLs. Many CodeIgniter developers prefer to keep this value blank.

CodeIgniter ’s Global XSS Filtering option is set to FALSE by default. The online User Guide suggests that setting this to TRUE adds a lot of performance overhead to the system. However, at this point, it is better to have some global protection put in place. That way you can be assured of some security
precautions while you’re in development.
In the same security vein, notice that sess_encrypt_cookie has been set to TRUE, and that you are to enter a 32-character encryption salt in encryption_key. Doing these two things will encrypt any sessions and provide a salt for any hashing methods you use. Be sure to use a random string of upper-
and lowercase letters and numbers.
One final note before moving on: Make sure that you write down your encryption key and keep it safe somewhere, or, at least, maintain good backups. You’ll need the key to retrieve other information, so if your site is compromised or erased (or if you lose your key any other way), you’ll be glad you have a
record of it.
database.php

To connect to your database, simply enter valid information for your hostname, username, password, database name, and database driver.

autoload.php

The autoload.php file specifies which systems are automatically loaded by CodeIgniter.

The first $autoload option, libraries, is a list of libraries that should be loaded. You’re going to be using the database, session, e-mail, and form validation libraries a lot in this (and many other) CodeIgniter project(s), thus loading them now makes a good deal of sense. You learn more about these libraries later.
The second $autoload option, helper, is a list of helper collections that you will need to get work done. Almost every CodeIgniter project uses the URL, form, and text helpers frequently; it’s not a bad idea to have date and security autoloaded as well, particularly as you’ll need them to help you parse dates and handle security features.
For the time being, keep the third $autoload option, plugin, either blank or filled in with the CAPTCHA plugin, as you may have a need to use CAPTCHA devices in forms for your application for extra security.

routes.php

The routes.php file lets you remap URI requests to specific controller functions.The default_controller route tells CodeIgniter which controller should be loaded if no controller is identified.

CodeIgniter Libraries

CodeIgniter includes the following libraries:
Benchmarking — The Benchmarking library is always active. Use it to determine the time difference between any two marked points in code and to calculate memory usage.
Calendaring — The Calendaring library must be loaded by a controller. Use it to dynamically create calendars for given months and years, with some control over formatting and appearance.
Config — The Config library is initialized automatically by the system. Use it to retrieve configuration information.
Database — The Database library is a very powerful set of methods that must be loaded.
Email — The Email library must be loaded. It includes a very powerful set of tools that simplifies the job of sending e-mails.
Encryption — The Encryption library must be loaded. It provides you with powerful two-way encryption methods.
File Uploading — The File Uploading library must be loaded. Use this library whenever you need to handle file uploads. It includes powerful validation features that can restrict a file by mime type, size (in kilobytes), or even image dimensions.
FTP — The FTP library must be loaded. Use this library to transfer files to a remote server (only standard FTP is supported, by the way).
HTML Table — The HTML Table library must be loaded. Use this very versatile library to autogenerate HTML tables from arrays or database result sets.
Image Manipulation — The Image Manipulation library must be loaded. Use it to resize images, create thumbnails, crop or rotate images, and watermark images. Some functions require further PHP support (such as GD/GD2).
Input and Security — The Input and Security library must be loaded. Use it to pre-process input data (from forms and URLs) and to handle some security functions (such as guarding against XSS attacks).
Language — The Language library must be loaded. Use this library to load different sets of language files for internationalization.
Loader — The Loader library is automatically loaded. You will use this library primarily to load views with your controller, but it is also used to load libraries.
Output — The Output library is automatically loaded. This library has one main function: Send the finalized web page to the requesting browser. It is also used for caching.
Pagination — The Pagination library must be loaded. Use this labor-saving library to paginate database results for performance and usability. You can control how many records to display per page, how many records to pull from the database, and the look and feel of different parts of the pagination.
Session — The Session library must be loaded. Use CodeIgniter ’s Session library to maintain state information about a user. This library does not use PHP’s built-in sessions — instead, it generates its own session data.
Template Parser — The Template Parser library must be loaded. Use this library to create templates that contain parsable pseudo-templates. If you are familiar with Smarty, you’ll find that CodeIgniter ’s templating isn’t as feature-rich but is still very useful.
Trackback — The Trackback library must be loaded. Use this library to send and receive Trackback data.
Unit Testing — The Unit Testing library must be loaded. Use this class to unit test functions in your application. CodeIgniter provides an evaluation function and two result functions in this library.
URI Class — The URI Class library is loaded automatically. You’ll use this library a good deal, especially when you’re parsing URLs, breaking them into segments that can then be passed to a controller or saved as variables.
User Agent — The User Agent library must be loaded. Use this library to identify the browser, mobile device, or robot visiting your site. You can also use it to detect supported languages, character sets, and even referrers.
Validation — The Validation library must be loaded. Use this library to validate form input in your applications.
XML-RPC — The XML-RPC library must be loaded. Use this library to set up XML-RPC clients and servers.
Zip Encoding — The Zip Encoding library must be loaded. Use this library to create Zip archives of both text and binary data.

CodeIgniter Helpers

Helpers, as their name implies, help you with specific tasks. Unlike libraries, helpers are not object-oriented but procedural in nature. Each helper contains one or more functions, each focusing on a specific task, with zero dependence on other functions.Helpers can either be loaded locally or autoloaded in /system/application/config/autoload.php.
CodeIgniter ships with the following built-in helpers:

Array — The Array helper contains functions that help you work with arrays. For example, the random_element() function takes an array as input and returns a random element from it.
Cookie — The Cookie helper contains functions that help you set, read, and delete cookie data.
Date — The Date helper contains functions that help you work with dates. For example, the now() function returns the current time as a UNIX time stamp.
Directory — The Directory helper contains a single function that helps you work with directories. For example, the directory_map function reads a specified directory path and builds an array of it that contains all of its files and subdirectories.
Download — The Download helper contains a single function that helps you download data easily. The force_download() function generates server headers that force data to be downloaded instead of viewed in a browser.
File — The File helper contains functions that help you read, write, and delete files.
Form — The Form helper contains functions that help you build forms. It is probably one of the most used helpers in the CodeIgniter toolbox.
HTML — The HTML helper contains functions that help you create HTML blocks quickly and easily. For example, the ul() function can turn an array of items into a bulleted list.
Inflector — The Inflector helper contains functions that help you to turn words into plural or singular form, to apply camel case, or to turn words separated by spaces into an underscored phrase. For example, the singular() function can turn the string “girls” into “girl.”
Security — The Security helper contains security-related functions like xss_clean(), which filters out any code that may be used in a cross site scripting hack.
Smiley — The Smiley helper contains functions that help you manage emoticons. The functions in this helper might seem superfluous, but become invaluable if you are coding a bulletin board or chat application.
String — The String helper contains functions that help you work with strings, like the random_ string() function, which as its name implies, creates random strings based on type and length arguments.
Text — The Text helper contains functions that help you work with text. For example, the word_ limiter() function can limit a string to a certain number of words, which is useful if you’re trying to limit user input on a form.
Typography — The Typography helper contains a single function that helps you format text in appropriate ways.

URL — The URL helper contains functions that help you work with URLs. This is another helper that sees heavy use. You will use the base_url() and anchor() functions many times in any given project, but other functions, such as safe_mailto() and anchor_popup() are extremely useful as well.
XML — The XML helper contains a single function that helps you work with XML. The xml_ convert() function converts a given string into XML-ready text, converting ampersands and angle brackets (among other things) into entities.

prototype cheatsheet

Securing the PHP Environment by PHPSecInfo

Fact 1
  • PHP is very, very popular
  • Nearly impossible to find a hosting service that doesn’t support PHP in some form
  • About 34% of all domains report using PHP
  • PHP is very easy to learn
  • PHP provides results quickly ,Time between setup and seeing results is very short
Fact 2
PHP powers many busy, high-profile sites
  1. Wikipedia
  2. Facebook
  3. Wordpress.com
  4. Digg
  5. Flickr
  6. Yahoo!
Fact 3 Tells Us
Network Administrator Responsible for

a) Directly responsible for PHP environment security
b) Tendency to lower security of environment to reduce application compatibility complaints

PHP Developer Responsible for


• The PHP Developer Must be aware of the environment and how it impacts app
development
• Will write apps assuming certain features are enabled, despite
security risks

What is PHPSecInfo ?

A security auditing tool accessible to the “Deployer”
1. Compatible
Support PHP4 (63%) and PHP5 (37%)
2. Easy to install
Unzip and Upload
3. Easy to execute (little or no config)
Runs upon upload; single function call
4. Easy to understand
Clear, unambiguous results; color coding
5. Encourage further exploration
Offer extended explanations with links to more info





Test Suite



















1. 17 tests for commonly exploited security
2. vulnerabilities in PHP environment
3. Each test result shows:
  • Current Setting
  • Recommended Setting
  • Result (color-coded)
  • Explanation
  • Link to further info
4. Simple metrics output

More info. Available on -
  • phpsecinfo.com
  • phpsecinfo.googlecode.com
  • phpsec.org
  • cerias.purdue.edu
  • framework.zend.com

Friday, December 12, 2008

Integrating APC (Alternative PHP Cache) Into PHP5 (Fedora 8 & Apache2)

1 Preliminary Note

I have tested this on a Fedora 8 server where Apache2 and PHP5 are already installed and working. I'll use Apache's default document root /var/www/html in this tutorial for demonstration purposes. Of course, you can use any other vhost as well, but you might have to adjust the path to the info.php file that I'm using in this tutorial.

2 Checking PHP5's Current State

First, before we install APC, let's find out about our PHP5 installation. To do this, we create the file info.php in our document root /var/www/html:
  1. vi /var/www/html/info.php
  2. check phpinfo

3 Installing APC

  1. yum install php-pear
  2. yum install php-devel httpd-devel
  3. yum groupinstall 'Development Tools'
  4. yum groupinstall 'Development Libraries'
Now that all dependencies are installed, we can install APC as follows:
  • pecl install apc

Now that APC is installed, we create the configuration file /etc/php.d/apc.ini. We must at least add the line extension=apc.so in there; all other configuration options are optional. You can find a list of all available configuration options on http://de2.php.net/manual/en/ref.apc.php.
  1. vi /etc/php.d/apc.ini
  2. extension=apc.so
    apc.enabled=1
    apc.shm_size=30
That's it. Restart Apache, and you're done:
  • /etc/init.d/httpd restart

some good examples regarding javascript performance

Following are some good examples regarding javascript performance.

http://www.sitepen.com/blog/wp-content/uploads/2008/05/stringfor.png
http://www.sitepen.com/blog/2008/06/09/string-performance-getting-good-performance-from-internet-explorer/
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Iterators_and_Generators
http://blog.monstuff.com/archives/000315.html
http://blogs.msdn.com/ie/archive/2006/08/28/728654.aspx
http://www.rockstarapps.com/samples/performance/

For those whos life goes around DIV's, CSS & Browser’s :)

well .. finally i am going to introduce a blog .. it is totally devoted to CSS,UI and HTML development.
I know both contributors personally. kapil and balbir both are not only expert as HTML Developers but also good friend of mine. both are always ready to help to everyone whenever needed.

Best of luck for their bright Future !!!

http://tekui.blogspot.com

MySQL and SQL Column Truncation Vulnerabilities

While SQL-Injection is one of the most discussed security problems in web applications other possible problems for SQL queries like overlong input are usually ignored although they can lead to all kinds of security problems.
This might be caused by the fact that security problems that are the result of overlong input are often buffer overflows and buffer overflows are something many web application security experts know nothing about and choose to ignore.
There are however several security problems for SQL queries that are caused by overlong input and no one talks about.

max_packet_size

In MySQL there exists a configuration option called max_packet_size which is set to one megabyte by default and controls the maximum size of a packet sent between the SQL client and server. When queries or result rows do not fit into a single packet a error is raised. This means an overlong SQL query is never sent to the server and therefore never executed.
This can lead to security problems when an attacker is able to supply long data elements that are then used in SQL queries. A good example are logging queries that combine information like the HTTP User-Agent, session ids and log messages into a large query that then does not fit into the packet anymore.
Another example from a real world application is a session table cleanup process that first selects all sessions matching certain parameters into a PHP array, then performs a multiple level cleanup and in the end all selected session ids are put into single delete query. It should be obvious that when there are many session identifiers in the table that need deletion the query gets too long. The result of this is that flooding the application with new sessions in a short time will result in no unused session being deleted later anymore.
Therefore web application developers should always ensure that they do not sent overlong data to the server. And it doesn’t matter if they use prepared statements or not.

SQL Column Truncation Vulnerabilities

When user input is not checked for its length SQL Column Truncation Vulnerabilities can arise. “SQL Column Truncation Vulnerability” is the name I use to describe security problems arising from overlong input that is truncated during insertion in the database. By default MySQL will truncate strings longer than the defined maximum column width and only emit a warning. Those warnings are usually not seen by web applications and therefore not handled at all. In MySQL the sql_mode STRICT_ALL_TABLES can be activated to turn these warnings into errors but applications will run most of the time on servers that run in the default mode and even if an application uses the stricter sql_mode it should not produce this error in the first place. Therefore a length check is required.
To understand why the truncation on insert can lead to security problems imagine the following application.
  • The application is a forum where new users can register
  • The administrator’s name is known e.g. ‘admin’
  • MySQL is used in the default mode
  • There is no application restriction on the length of new user names
  • The database column username is limited to 16 characters
A potential attacker might now try to register the name ‘admin ‘, which will fail because the ‘isAlreadyRegistered’ check will result in the SQL query.
SELECT * FROM user WHERE username='admin '
Because MySQL does not compare strings in binary mode by default more relaxed comparison rules are used. One of these relaxations is that trailing space characters are ignored during the comparison. This means the string ‘admin ‘ is still equal to the string ‘admin’ in the database. And therefore the application will refuse to accept the new user.
If the attacker however tries the username ‘admin x’ the application will search for it in the database and will not find it, because it is impossible to find a username with a length of 17 in a database field that has a 16 character limit. The application will accept the new username and insert it into the database. However the username column is to short for the full name and therefore it is truncated and ‘admin ‘ is inserted into the database.
The result of this is that the user table now contains two users that due to trailing spaces both will be returned when the SELECT query above is executed. At this point a potential security problem arises because now it depends on how the username is treated throughout the application. The following pseudocode for example is vulnerable.
$userdata = null; if (isPasswordCorrect($username, $password)) {    $userdata = getUserDataByLogin($username);    ... }
When the previous piece of code uses the SQL query
SELECT username FROM users WHERE username = ? AND passhash = ?
to detect if the user password is correct and then does a lookup of the user data by name a security problem manifests.
SELECT * FROM users WHERE username = ?
Because the attacker created the newly created admin user he knows the correct password to pass this check. And because the real admin user is first in the table it will be returned first when the user data lookup by name is executed later.

Conclusion

Both problems described here are two new things web applications needs to be audited for because both can lead to real security problems. And because no one searches for these kind of vulnerabilities, now that it is public most probably the next weeks will bring several advisories about open source software suffering from these problems.

Original Source: http://www.suspekt.org/2008/08/18/mysql-and-sql-column-truncation-vulnerabilities/