Sie sind auf Seite 1von 23

Code Igniter : un framework alliant simplicit et efficacit

Code Igniter est un framework PHP compatible PHP 4 qui propose des fonctionnalits intressantes pour la cration dapplication Web. Pour couper court toute discution, il nest pas aussi puissant que Symfony ou le Zend Framwork, mais il offre dautres atout comme la simplicit, la rapidit, lefficacit et la documentation.

Installation
Linstallation est trs simple voir simpliste, il suffit de tlcharger la dernier version et de lextraire dans le rpertoire qui contiendra votre application Web. Il faut ensuite configurer le fichier application/config/config.php pour y mettre lURL de base. Pour configurer la ou les bases de donnes utilises dans le site il faut modifier le fichier application/config/database.php. Ces trois opration permettent davoir un site fonctionnel en quelques secondes. Bien sur, il existe dautres options de configuration qui permettrons aux plus aguerris davoir une application aux plus proches de leurs dsirs.

Caractristiques

Framework pour application Web


Ce framework fournit les briques essentiels pour le dveloppement dapplication Web, sans pour autant tre une usine gaz. On peut dire sans trop se tromper que les bibliothques de Code Igniter couvrent 80% des besoins des dveloppeur.

Un framework libre
Comme souvent dans le monde PHP, le framework est libre. Sa licence est du style Apache / BSD.

Compatible PHP 4
Bien que PHP 5 soit de plus en plus utilis, il reste de nombreux serveur utilisant PHP 4, et dont la place ne cesse daugmenter avec la migration des applications vers PHP 5. Il peut tre intressant dutiliser cette compatibilit pour utiliser nouveau ces ressources laisse libre.

Un framework Rapide
De part sa nature un peu minimaliste, les performances sont au rendez-vous.

Une architecture MVC


CodeIgniter se base sur une architecture MVC qui permet de bien sparer la logique mtier de la prsentation. Avec ce motif de conception, il est parfaitement possible de faire travailler des intgrateurs et des dveloppeurs en parallle sur les mmes projets.

Les clean URLs


CodeIgniter se base sur une approche orientes segments pour la gestion des URLs. Ce mode de fonctionnement est devenu un standard pour tous les frameworks. Le schma mise en oeuvre sinspire de schma de route de Ruby On Rails.

Les librairies
CodeIgniter est fournit avec un certains nombres de librairies, qui couvre les plus grand besoins des dveloppeur Web. On trouve par exemple des classes pour la gestions dun panier, lupload de fichier, la manipulation dimage, linternationalisation, la gestion des formulaires, la base de donnes, la gestion du cache, les tests unitaires . Ce framework est extensible souhait. Il est ainsi parfaitement possible dintgrer des libraries tierces ou crer ses propres helpers. On trouve par exemple sur le site Doctrine un tutoriel pour remplacer la couche de base de donnes par un ORM telle que Doctrine.

Pas besoin de langage de template


Je ne vais pas encore relancer le dbat, mais les langages de templates napportent pas grand chose. CodeIgniter permet de faire sans et cest tant mieux. Si vous tes intgristes et que vous voulez absolument en utiliser un, CodeIgniter fournit un micro-langage de template.

Documentation
Pour terminer, ce rapide tour dhorizon, CodeIgniter dispose dune documentation plutt complte. Dommage que la forme ne soit la hauteur fond, la navigation dans la documentation est pltot pnible mais elle est complte. CodeIgniter est framework PHP plutt bien ralis. Son principal atout rside dans sa simplicit, il est accessible aux nophites comme aux dveloppeur plus chevronns. Il pourra convaincre un programmeur lancienne de lapport des frameworks PHP.

Le framework CodeIgniter est disponible en version 2.0.0


CodeIgniter est un framework open-source crit en PHP conu pour rendre le dveloppement d'applications web plus ais. C'est le 28 janvier qu'a t annonce la sortie de la dernire release, la 2.0.0.

Prsentation du framework
Le framework CodeIgniter est fond sur une architecture MVC. Cette mthode de conception est prsente dans de nombreux autres frameworks PHP tels que symfony ou encore Cake PHP. Inspir de Ruby on Rails, CodeIgniter est principalement connu pour ses performances, sa simplicit d'installation et d'utilisation ainsi que son absence de convention rigoureuse que d'autres imposent. Ainsi, une simple dcompression suffit pour installer le framework, et aucune ligne de commande n'est ncessaire. Un autre point fort que l'on peut citer est sa documentation trs claire avec une quantit d'exemples trs pratiques. Enfin, un systme de bibliothques et de helpers rendent ce framework complet et flexible. En effet, via un systme d'hritage robuste, le framework peut tre modifi volont, et ce, sans l'altrer irrmdiablement.

L'arborescence native des fichiers

En route pour une nouvelle version majeure

Qu'on n'en doute pas, cette version arrive avec des ajouts de fonctionnalits dont certaines taient trs demandes par la communaut. Cependant, cette version symbolise surtout labandon de PHP 4 au profit de la version 5 du langage au logo lphant qui apporte une meilleure stabilit. Alors que la majorit des frameworks utilise dj PHP 5 depuis fort longtemps, bon nombre de dveloppeurs rechignaient utiliser un framework qui utilisait encore une vieille version de ce langage web. Dsormais, seules les versions de PHP suprieures ou gales 5.1.6 seront compatibles avec CodeIgniter 2.0.0.

Plusieurs fonctionnalits sont dsormais passes la trappe. C'est le cas par exemple du scaffolding qui permettait de manipuler trs rapidement la base de donnes sans passer par un

outil comme phpMyAdmin. Rappelons que le scaffolding tait dprci depuis la version 1.6.0 du framework, essentiellement cause des dveloppeurs qui oubliaient de le dsactiver en production. Autre fonctionnalit supprime : les plugins deviendront maintenant des helpers. Les plugins et les helpers sont en quelque sorte des fichiers o l'on dclare diverses fonctions. La diffrence entre ces deux composants se situait surtout au niveau de la quantit de fonctions. Dans cette nouvelle version, il n'y aura plus aucune diffrence.

L'arborescence a elle aussi t compltement revue. prsent, il y a une sparation trs nette entre le code natif de CodeIgniter et celui crit par le dveloppeur. En effet, ces deux parties seront dsormais spares dans deux dossiers ds la racine du site web et sont respectivement nommes system et application. De plus, les dossiers log et cache ont t dplacs dans le dossier application. On notera aussi l'apparition des dossiers core et third_party.

Une autre nouveaut qui a fait son apparition est la possibilit d'inclure automatiquement dans chaque formulaire un jeton de scurit (galement appel token). Le framework se chargera ensuite de vrifier sa validit lors de l'envoi du formulaire. Rappelons que ce moyen permet de lutter efficacement contre les failles CSRF.

Autre nouveaut trs attendue, la possibilit de diviser son application en modules. Auparavant, le code tait divis en contrleurs que l'on plaait dans un unique dossier. Maintenant, il est beaucoup plus facile de dcouper davantage son application en ayant l'quivalent de plusieurs dossiers applications lintrieur du dossier application natif. Cette technique peut tre trs pratique si votre site possde des parties indpendantes. CodeIgniter marque donc le coup avec cette nouvelle version. De plus, les prochaines moutures devraient elles aussi embarquer de nouveaux composants tout aussi intressants. Ce sera notamment le cas de la bibliothque d'authentification qui est encore en phase de conception, ce qui nous laisse esprer l'arrive d'un outil la fois flexible et simple d'utilisation.

Apprendre utiliser AJAX avec CodeIgniter

AJAX for CodeIgniter


Category:Library -> Community | Category:Library -> AJAX AJAX for CodeIgniter is a CodeIgniter library that provides you with AJAX functionality for your CodeIgniter web applications. It comes with simple to use AJAX helpers that you can directly put in use in your apps.o AJAX fr CodeIgniter includes both Prototype and Scriptaculous helpers. This is compatible with CodeIgniter 1.5.1. Download: File:AJAX-for-CodeIgniter.zip Download: File:AJAX-for-CodeIgniter v2.zip (with fixed bug) Below is a quick and simple how-to-use article. For code references and full class documentation, please read the full user guide that comes with the zip file (follow the above link to download).

Enjoy this release. - siric

How to use AJAX for CodeIgniter?


Place the AJAX library in the following directory (default libraries directory):
www-root/system/libraries/

Place the javascript files in your www root directory. For example:
www-root/javascript/

If you use mod_rewrite, make sure you allow the javascript directory to be accessed. To do this, set up your .htaccess file to look something like this:
RewriteEngine on RewriteCond $1 !^(index\.php|images|stylesheets|javascript) RewriteRule ^(.*)$ /index.php/$1 [L]

Then, simply include whichever javascript files you would like to use in your html file:
<script <script <script <script src="javascript/prototype.js" type="text/javascript"></script> src="javascript/effects.js" type="text/javascript"></script> src="javascript/dragdrop.js" type="text/javascript"></script> src="javascript/controls.js" type="text/javascript"></script>

Finally, load up the AJAX library as you would with any other CodeIgniter library. There are two possible ways to do this. Directly from within your controller:
$this->load->library('ajax');

Or, auto-load the AJAX library from within system/application/config/autoload.php:


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

Then all you need to do to use an AJAX helper is to call $this->ajax. For example:
echo $this->ajax->link_to_remote("Login", array('url' => '/login', 'update' => 'divblock'));

Categories:

Library
o o

AJAX Community

CodeIgniter and Ajax Using JQuery Tutorial

I created this tutorial because I was having a hard time finding good simple CodeIgniter + JQuery tutorial for newbie like me. The one I found, created by MR Forbes, is hard to understand and apparently isnt working. Another one, pr0digys, is using Mootools for the AJAX framework. So I decided to create my own CodeIgniter and JQuery tutorial based on pr0digys tutorial. Im assuming you already know how to code using CodeIgniter. If youre new to CodeIgniter, you need to find others tutorial first. The videos given in CodeIgniters site is a good start. This tutorial is about creating simple CodeIgniter + database + ajax system. User will be shown a form to post a message. Then after he/she press the submit button, the system will save the message using ajax and then show the message. You could see the result first if you want.

Database
The first thing we need to do is creating a table to save the message. For this tutorial, We will use this:
1 CREATE TABLE IF NOT EXISTS `messages` ( 2 `id` tinyint(4) NOT NULL AUTO_INCREMENT, 3 `message` VARCHAR(256) NOT NULL, 4 PRIMARY KEY (`id`) 5)

Controller
Then, we need to create a controller. My controller is named message. You could name your controller any name you like. After that, create 2 functions/methods, view and add. view is used to get the default view and list of messages from the database. The codes are:
1 function view($type = NULL) 2 { 3 // get data from database 4 $data['messages'] = $this->Message_model->get(); 5 6 if ($type == "ajax") // load inline view for call from ajax 7 $this->load->view('messages_list', $data); 8 else // load the default view 9 $this->load->view('default', $data); 10 }

We fetch messages from the database using Message_model->get() function. Then the data is passed to the view. Here, we have 2 views called. One for the default view, where we called the page using message/view, and the other is for calling from ajax. add is a proccess used to insert the message to the database. The codes are:
1 function add() 2{ 3 // if HTTP POST is sent, add the data to database 4 if($_POST && $_POST['message'] != NULL) {

5 6 7 8 9}

$message['message'] = $this->input->xss_clean($_POST['message']); $this->Message_model->add($message); } else redirect('message/view');

This function is accessed when we press the submit button from the form. This function will save the message using Message_model->add() function.

Model
The next thing we need to create is the model. I use Message_model for the name. Here we create two functions, add and get. add is a function to insert the data into the database. get is a function to retrieve data from database. I think the codes are pretty self-explainatory, but you could drop me a message if you need some explainations on the codes.
1 2 3 4 1 2 3 4 5 6 7 function add($data) { $this->db->insert('messages', $data); } function get($limit=5, $offset=0) { $this->db->orderby('id', 'DESC'); $this->db->limit($limit, $offset); } return $this->db->get('messages')->result();

View
I use 2 files for view section. default.php and message_list.php. The message_list is used for displaying the messages taken from the database.
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 <!-- default.php --> <div id="form"> <input type="text" id="message" name="message" /> <input type="submit" id="submit" name="submit" value="submit" /> </div> <div id="content"> <?php $this->load->view('messages_list') ?> </div> <!-- message_list.php --> <ol> <?php foreach ($messages as $message): ?> <li><?= $message->message ?></li> <?php endforeach ?> </ol>

Hey, Wheres the JQuery?


Here we go. The last, and maybe the most important part of this tutorial. So, we the our controller, we had the model, and we had the views. I assume you already know how to include a jquery script to your view. The jquery codes are this:

$(document).ready(function() { 1 $('#submit').click(function() { 2 3 var msg = $('#message').val(); 4 5 $.post("<?= site_url('message/add') ?>", {message: msg}, 6 function() { 7 $('#content').load("<?= site_url('message/view/ajax') ?>"); 8 $('#message').val(''); 9 }); 10 }); 11 });

So, when we click the submit button, the javascript will take the value of input textbox then send it to message/add using post method. When the action succeed, the script will call message/view/ajax. Note the ajax keyword. It will call the message_list view instead of the default one. Then the view will replace the content in div#content tag. Well done. You could see the demo I made from the tutorial. You could download the whole files used in this tutorial in tutorial.zip (1.98 KB). Or, if you prefer to get one by one, controller: message (904 bytes) model: message model (583 bytes) view: default (782 bytes) view: message_list (111 bytes) I hope this tutorial helps newbie like me. If you have any question, just drop a comment below Update: Need how to do this using JSON? Check CodeIgniter and Ajax Using jQuery tutorial using JSON

A Quick Code Igniter and JQuery Ajax Tutorial


This tutorial assumes a basic working knowledge of Code Igniter. If you have never used CI before, please refer to the framework documentation In the old days (2 years ago), working the Javascript magic to create a cool AJAX based event took a fairly decent working knowledge of the mechanisms behind the process. With the increasing popularity of Javascript libraries however, this type of functionality became available to the web site hobbyist, and was made much easier for the web site professional. The following step-by-step tutorial will show you how to combine the power of JQuery (a javascript library that weighs in at about 20k) with Code Igniter (a PHP framework based on the MVC design pattern) to quickly and painlessly pass a record ID through the javascript and

over to the server, where it will be passed to a mysql database, used to retrieve some data, and sent back to the page for display. Step 1 We begin by assuming that you have a div with an id of content, which is where you would like your freshly retrieved data to display, once it has been freshly retrieved. For this exercise, you have already taken an action to call your javascript function with a record ID parameter. The first thing you need to do, is make sure JQuery is being loaded, and to create a function for your AJAX request.

Step 2: Next, youll use the JQuery function load, and attach it to your content div:
function get_record_id(record_id) { $('#content').load() }

Step 3: The load function accepts three arguments. The page to be called on the other side of the HTTPRequest, the array to pass through the POST, and a callback function. It looks like this:
function get_record_id(record_id) { $('#content').load(/controller/method,p,function(str){ }); }

Lets go back to that. Code Igniter URLs are created by calling the name of your controller, followed by the function inside the controller class that will handle your request. If your server does not support mod-rewrite, you may also need to append an index.php to the beginning. The str inside the callback function is the results of your AJAX request. There isnt much use for the str when using the .load function, but it does come in handy using the other JQuery AJAX functions $.post and $.get, which I assume are self explanatory. Step 4
var p = {}; //instantiate the array p[record_id] = record_id //assign your record_id variable to it.

Thats all there is to it. Your final javascript function looks like this:
function get_record_id(record_id) { var p = {}; p[record_id] = record_id $('#content').load(/controller/method,p,function(str){ } });

Step 5 On the CI side, you have a controller and method setup something like this:
class Controller { function Controller() { parent::CI; } function method() { }

The important part is the method() function, as it will contain some of the code we need to make things happen. Step 6 The first thing you need to do on the CI side is retrieve the value passed through the request object. This is simple enough, using $_POST[record_id]. You also want to load up your database model so you can get the record out of your database. So, well load the database library, and then load the actual model. Then, we want to send the record ID to the database, get the resulting data, and pass it back out to the request. our function starts to look like its doing something useful pretty quickly.
function method() { $record_id = $_POST[record_id]; //set the record ID $this->load->library(database); //load the database library to connect to your database $this->load->model(records); //inside your system/application/models folder, create a model based on the procedure //outlined in the CI documentation $results = $this->records->get_record($record_id); //get the record from the database }

Step 7 At this point, we need to go into our records.php file in the model folder. Since Code Igniter uses a Model-View-Controller structure, database activity, server-side processing, and clientside display should be as separate from one another as possible. You dont NEED to do this for Code Igniter to do its thing, but its good practice. Inside the records.php file, well create a method called get_record to match the method referenced above. Well use it to get a record by its primary key of ID, put the resulting data into an array, and send it back to the controller, out to the view, and ultimately into the content div we started with.
function get_record($record_id) { $this->db->where(ID,$record_id); //we want the row whose ID matches the value were passing in

$query = $this->db->get(record_table); //get the table and put it into an object named $query $row = $query->row(); //gets the first row of the resulting dataset. In this case, only 1 row will ever be returned $results[record][$row->ID][name] = $row->name; //here, we create a multi-dimensional array holding the returned values //based on the key. return $results; //send the record back to the controller }

The trickiest part of this section is the array. It seems pretty complex from here, but youll see soon enough how it breaks down into something more manageable as we go along. Step 8 Were back to the controller again, and we have one more line to add this time to pass the resulting data into a view to be formatted and printed to the content div. The whole method() function now looks like this:
function method() { $ID = $_POST[record_id]; //set the record ID $this->load->library(database); //load the database library to connect to your database $this->load->model(records); //inside your system/application/models folder, create a model based on //the procedure outlined in the CI documentation $results = $this->records->get_record($record_id); //get the record from the database $this->load->view(AJAX_record,$results); }

Step 9 The AJAX_record.php file should be in your system/application/views folder. Keep in mind, that when you pass an array to a view (in this case the $results array), it will be exploded inside the view. So, the path to your record is now $record, instead of $results[record]. Also inside will be your standard HTML markup, and something like this:
< ?php foreach($record as $id=>$value) { ?> The name associated with this record is: < ?php print $value[name];?> < ?php } ?>

This output is what php is sending to the request object, and is also what gets loaded into the content div. Code Igniter and JQuery make it that easy to dynamically load data using AJAX.

CodeIgniter Tutorial: How to Create Ajax Pagination using CodeIgniter?

CodeIgniter has many built-in classes and plugins. Pagination class of CodeIgniter is very easy and simple to use. Also Ajax Pagination library is availanle in Codeigniter. Here i will describe how to create simple ajax pagination in Codeigniter using some simple steps. First of all download Ajax Pagination from Codeigniter site. And put this library in system/libraries/ folder. Along with library you need to download prototype.js file and put this file any where on root. Here we have a table which we use for getting records and apply pagination on its records.
CREATE TABLE `my_best_friends` ( `f_id` int(11) NOT NULL auto_increment, `f_name` varchar(100) NOT NULL, `f_phone` int(11) NOT NULL, `f_email` int(11) NOT NULL, `f_address` int(11) NOT NULL, PRIMARY KEY (`f_id`) )

Your controller:
class Paging extends Controller { function Paging(){ parent::Controller(); $this->load->helper(array('form','url')); $this->load->helper('text'); $this->load->library('Ajax_pagination'); } function index() { redirect ('paging/my_friends'); } function my_friends() { $pdata['TotalRec'] = $this->FriendsModel->TotalRec(); $pdata['perPage'] = $this->perPage(); $pdata['ajax_function'] = 'get_friends_ajax'; $subdata['paging'] $pdata, TRUE); = $this->parser->parse('paging', = $this->FriendsModel-

$subdata['all_friends'] >my_friends($this->perPage());

$data['body_content'] $subdata, TRUE); }

= $this->parser->parse('friend_list',

$this->load->view('main',$data); function get_friends_ajax() { $pdata['TotalRec'] = $this->FriendsModel->TotalRec(); $pdata['perPage'] = $this->perPage(); $pdata['ajax_function'] = $data['paging'] = TRUE); >perPage()); } $this->load->view('friend_list',$data); 'get_friends_ajax';

$this->parser->parse('paging', $pdata,

$data['all_friends'] = $this->FriendsModel->my_friends($this-

function PerPage() { return 5; } }

Model :
class FriendsModel extends Model { function FriendsModel() { parent::Model(); } function TotalRec() { $sql = "SELECT * FROM my_friends"; $q = $this->db->query($sql); return $q->num_rows(); } function my_friends($perPage) { $offset = $this->getOffset() $query ="SELECT * FROM my_friends Order By f_id Desc LIMIT ".$offset.", ".$perPage; $q = $this->db->query($query); return $q->result(); } function getOffset() { $page = $this->input->post('page'); if(!$page): $offset = 0;

} }

else: $offset = $page; endif; return $offset;

View: paging.php in application/views/ folder


$config['first_link'] $config['div'] $config['base_url'] $config['total_rows'] $config['per_page'] $config['postVar'] = = = = = = 'First'; 'container'; //Div tag id base_url().'paging/'.$ajax_function; $TotalRec; $PerPage; 'page';

$this->ajax_pagination->initialize($config); echo $this->ajax_pagination->create_links();

View: friend_list.php in application/views/ folder


<table border="1" width="200"> <tbody> <tr> <td>Friend Name</td> <td>Friend Phone</td> <td>Friend Address</td> </tr> foreach($all_friends as $row) { <tr> <td>echo $row->f_name</td> <td>echo $row->f_phone</td> <td>echo $row->f_address</td> </tr> }</tbody> </table>

Main home file: main.php in application/views/ folder This file contains your html code and all css and js files. I have just given main container where your data will show. you have to add html and css/js files your self.
<div id="container"> echo @$body_content;</div>

Codeigniter Tutorial: How To check Username/Email availablity using jQuery in Codeigniter?


This post is for CI lover who wants to learn Codeigniter. This script will show you how can we check live availability of username or email using Ajax in Codeigniter. Using this tutorial you can also understand how can we send a jQuery Ajax request to server living in CI.

In your view where you have created form include jQuery library and put the below code there. In header section:
$(document).ready(function() { /// make loader hidden in start 1 $('#Loading').hide(); 2 3 $('#email').blur(function(){ 4 var a = $("#email").val(); 5 var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA6 Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/; 7 // check if email is valid 8 if(filter.test(a)){ 9 // show loader 10 $('#Loading').show(); 11 $.post("<?php echo base_url()? 12 >controller_name/check_email_availablity", { 13 email: $('#email').val() 14 }, function(response){ 15 //#emailInfo is a span which will show you 16 message 17 $('#Loading').hide(); 18 setTimeout("finishAjax('Loading', 19 '"+escape(response)+"')", 400); 20 }); 21 return false; 22 } 23 }); 24 function finishAjax(id, response){ 25 $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); }

In body section in your form:


<div> 1 <label>E-mail</label> 2 <input id="email" name="email" type="text" value="" /> 3 <span id="Loading"><img src="loader.gif" alt="Ajax Indicator" 4 /></span> 5 </div>

In Your controller add this function:


1 function check_email_availablity() 2 { 3 $this->load->model('My_model'); 4 $get_result = $this->My_model->check_email_availablity(); 5 6 if(!$get_result ) 7 echo '<span style="color:#f00">Email already in use. </span>'; 8 else 9 echo '<span style="color:#0c0">Email Available</span>'; 10 }

Suppose you have a model called my_model.php and a table tbl_members or what ever you named. This table should have a field named email of type varchar [200]. Add this function:
function check_email_availablity() 1 { 2 $email = trim($this->input->post('email')); 3 $email = strtolower($email); 4 5 $query = $this->db->query('SELECT * FROM tbl_members where 6 email="'.$email.'"'); 7 8 if($query->num_rows() > 0) 9 return false; 10 else 11 return true; 12 }

Thats it, this function will return a message against email field that whether it is available or not. This is not for only email, you can use it to check any field. Also this is client side check so you also need to use this model function in server side so that email can also be verified when form has been submitted with disabling javascript .

How To: Use Re-Captcha in Codeigniter based website?

Re-captcha is a free web service to add a secured captcha on your website to avoid spams. Spams filled up your inboxes with unnecessary emails or messages which you have no need. Re-captcha is provided by Carnegie Mellon University which are serving over 60 millions captchas in a day. Here are some simple steps to complete this whole process. 1- Just go to re-captcha sign up page and enter your information. You need to add your site url there. And each of your site which you need to be deployed with re-captcha must have its domain name on your account in re-captcha site. 2- You will get public and private kep after entering your domain name and clicking on Create Key button. Save these codes into a notepad.

3- Download re-captcha library (recaptchalib.php) which will be used to interact with recaptcha API. 4- We will use this library as helper in codeigniter. Because this library holds a list of function which interacts re-captcha API. Paste this helper in to your system/application/helpers folder. 5- Now the work has been done at configuration level. Call your helper in controller.
1 $this->load->helper('recaptchalib');

6- In your controller, paste this code. Here the recaptcha_check_answer is used to get what code a user entered.
function recaptcha_validation($string) { $return = recaptcha_check_answer($this->config1 >item('private_recaptcha_key'), 2 3 $_SERVER["REMOTE_ADDR"], 4 5 $this->input->post("recaptcha"), 6 7 $this->input->post("recaptcha")); 8 9 if(!$return->is_valid) 10 { 11 $this->session->set_userdata("Mesg",'Code entered is 12 invalid !'); 13 return FALSE; 14 } 15 else 16 { 17 return TRUE; 18 } 19 } 20 21 function login_user_function() 22 { 23 $this->load->library('validation'); 24 $this->load->helper('recaptcha_helper'); 25 26 $rules['recaptcha'] = 'required|callback_recaptcha_validation'; 27 $this->validation->set_rules($rules); 28 29 $fields['recaptcha'] = 'Code'; 30 $this->validation->set_fields($fields); 31 32 if($this->validation->run() == FALSE) { 33 // code is not correct 34 } 35 else 36 { 37 // Code is verified now submit the form } }

In codeigniter we use config file to hold some global constant types values so i put private recaptcha key (private_recaptcha_key) in config file.

How to Upload files in Codeigniter. A simple way for beginner of CI

Codeigniter has a number of libraries and helpers which you can use for making your code reliable and bugs free. CI provides an extensive library of common usage classes. Upload class in Codeigniter provides us a simple and easy way for uploading files on server. For uploading a file using codeigniter create a simple HTML file which should contains a file input control and submit button with a form. Here is the code:
echo form_open_multipart('upload/do_upload'); <input name="myFile" size="40" type="file" /> <input type="submit" value="Upload" />

REMEMBER : Use form_open_multipart() if you are using any uploading in the form. Your controller will hold a simple function which will set the config array for defining the uploading path, allowed types, max size and height.
function do_upload() { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768'; // You can give video formats if you want to upload any video file. $this->load->library('upload', $config);

if ( ! $this->upload->do_upload()) { $error = array('error' = $this->upload->display_errors()); // uploading failed. $error will holds the errors. } else { $data = array('upload_data' => $this->upload->data()); // uploading successfull, now do your further actions } }

If files that are being uploaded are big in size then you need to increase Max file uploading size in php.ini on your server.

MySQL, PHP, Codeigniter, CSS and JQuery working tips.


Following are some useful tips when a developer needs them while developing. Keeping these points in mind will help us to improve our skills.

Codeigniter
Codeigniter is PHP framework which is light weight and very easy to configure and a lot of help available online. Use separate models for each module so that tracking can be easy.
$this->load->model('Login');

Front and admin should be handled with separate controllers. Use parser library for loading views.
$this->load->library('parser'); $data['content'] = $this->parser->parse('site/header', $data, TRUE);

In config folder routes file will help you to create pretty urls.
$route['admin'] = 'admin/index';

Define all your global constants in config/constant.php or create a separate file for this.
// constant.php define('SITE_NAME', 'zeeshanrasool');

Use flash session for your messages to users.


$this->load->library('session'); // setting data in session $this->session->set_flashdata('item', 'value'); // using data

$this->session->flashdata('item');

Dont call any model function inside views as it is not a valid in MVC. If you want to keep your application folder outside system folder then you need to change path in index.php on main root.
// it is default path define('BASEPATH', $system_folder.'/'); // change it to define('BASEPATH_NEW', '../your_folder/'); // above path will be use like this define('APPPATH', BASEPATH.$application_folder.'/');

Use rollback functions to keep track the functions otherwise revert all of your actions on failed.
$this->db->trans_begin(); if ($this->db->trans_status()===FALSE) { $this->db->trans_rollback(); return True; } else { $this->db->trans_commit(); return False; }

Include all of you css and js files in views separately from controller. Dont include all CSS or JS files on single page i-e index.php

PHP
Use switch conditions instead of if / else in case of using too much conditions. Switch condition is much faster than if / else.
if($a==7) echo 1; else if($a==5) echo 5;

For multiple conditions its best to use switch condition.


switch($a){ case: 1 echo 1; break; case:5 echo 5; break; }

Keep all particular functionality like, code for uploading a file, getting date in specific format etc in separate functions so that you can re-use them instead f writing it again. Use server side validation for required input fields with client side validation.

Single quotes is faster than double quotes for string or query in quotes.
$query = "Select * from table"; $query = 'Select * from table'; // single quoted

Keep error reporting on, so that notices and warnings may be fixed. These small notices may produce some problems on your server online. Comment your code, what you have done. So next time you are any other developer understand your code easily. Use .htaccess to put some securities on your code. Declare all variables properly so that they produce no problem in executions.

MYSQL
Get last 24 hours or 1 day records in mysql.
"select count(*) as cnt from log where date >= DATE_SUB(CURDATE(),INTERVAL 1 DAY)";

Export your table to CSV file.


select * into outfile '/file.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' from zips;

Dont use DISTINCT when you have or could use GROUP BY, LIMIT m,n may not be as fast as it sounds. Dont use ORDER BY RAND() if you have > ~2K records Avoid using IN() when selecting on indexed fields, It will kill the performance of SELECT query. Minimize traffic by fetching only what you need. 1. Paging/chunked data retrieval to limit 2. Dont use SELECT * 3. Be wary of lots of small quick queries if a longer query can be more efficient. Do not duplicate indexes. Avoid wildcards at the start of LIKE queries.

CSS
Keep css Simple. Dont use hacks unless its a known and documented bug. Take care of margins and padding on all elements. Avoid using too much absolute positioning. Validate your code

JQuery
Disable right click.
$(document).ready(function(){ $(document).bind("contextmenu",function(e){

return false; }); });

Re-size font.
$(document).ready(function(){ var originalFontSize = $('html').css('font-size'); $(".resetFont").click(function(){ $('html').css('font-size', originalFontSize); });

Equal height columns.


function equalHeight(group) { tallest = 0; group.each(function() { thisHeight = $(this).height(); if(thisHeight > tallest) { tallest = thisHeight; } }); group.height(tallest); } /* Usage: $(document).ready(function() { equalHeight($(".recent-article")); equalHeight($(".footer-col")); }); */

Remove a word in a text


var el = $('#id'); el.html(el.html().replace(/word/ig, ""));

Preloading images
jQuery.preloadImages = function() { for(var i = 0; i").attr("src", arguments[i]); } }; // Usage $.preloadImages("image1.gif", "/image2.png", "image3.jpg");

Das könnte Ihnen auch gefallen