Monday, August 26, 2013

How to replace a space with an underscore in PHP?

Use str_replace function of php to replace a space with an underscore. I am posting this for those of you who have struggled with this, in hopes that it just might save a couple of hours.
It is such a simple solution.
$string = "this is example";
$final = str_replace(" ","_",$string);
//output : this_is_example
Alternative solution can be to use regular expression.

How to set global constants containing arrays using Codeigniter?

You can use Codeigniter's constants file to store global arrays which can be used in multiple controllers or any where within your codeigniter's project scope.
Problem: Apparently, constants can't hold arrays.
Solution: You can serialize your array and then put it into the constant.
For example,
# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);
You can store it as a JSON string in a constant. And application point of view, JSON can be useful in other cases.
define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));    
$fruits = json_decode (FRUITS);    
var_dump($fruits);
It may exists other efficient ways to store global arrays in Codeigniter. Suggestions will be appreciated. :)
Ref: http://stackoverflow.com/questions/1290318/php-constants-containing-arrays

Thursday, August 22, 2013

How to compare two arrays and generate new array with common elements from both arrays in PHP?

There exists the php inbuilt function called array_intersect that computes the intersection of arrays.
Syntax:
  
 array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
//array 1: An array with master values to check.
//array 2: An array to compare values against.
//Returns an array containing all of the values in array1 whose values exist in all of the parameters.
 
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
Example of array_intersect()
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>
The above example will output:
Array
(
    [a] => green
    [0] => red
)
In this way, you can generate array which has common elements from both arrays. :)
Source: http://php.net/manual/en/function.array-intersect.php

Wednesday, August 21, 2013

PHP CURL functions for POST and GET request using Codeigniter

Install the curl library from https://github.com/philsturgeon/codeigniter-curl
CodeIgniter-cURL is a CodeIgniter library which makes it easy to do simple cURL requests and makes more complicated cURL requests easier too.
  //load the Curl library
  $this->load->library('Curl');        

  //Request using POST Method
   $url = 'http://postexample.com/json.php';       
   echo $this->curl->simple_post($url, false, array(CURLOPT_USERAGENT => true));

   //Request using GET Method
   $get_url = http://getexample.com/json.php;  
   echo $this->curl->simple_get($get_url, false, array(CURLOPT_USERAGENT => true)); 
It is very important to set CURLOPT_USERAGENT, otherwise many servers may refuse your request if you don't pass user agent.
   //PHP version, you can put anyvalue for CURLOPT_USERAGENT, but it shouldn't be empty or blank.
    curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); 
I tried without setting CURLOPT_USERAGENT in GOOGLE CHROME, it didn't worked. I spent more than 4 hours to find a solution, why it is not returning the result. Finally, I found this post http://www.silverphp.com/php-curl-function-for-post-and-get-request.html and try with my luck. And it worked. :)

Tuesday, August 20, 2013

How to set P3P headers in Codeigniter?

What is P3P header?
The Platform for Privacy Preferences Project (P3P) is a protocol allowing websites to declare their intended use of information they collect about web browser users. Designed to give users more control of their personal information when browsing, P3P was developed by the World Wide Web Consortium (W3C) and officially recommended on April 16, 2002.

If you didn't set P3P header, it may not work properly in IE browsers.

Real world problem and solution example
Problem: My codeigniter application is trying to set cookies from inside an iFrame, and this is not working very well with IE8.
Solution: Add P3P headers

IE's "high" privacy setting blocks all cookies from websites that do not have a compact privacy policy, but cookies accompanied by P3P non-policies like those below are not blocked.

In order to set the P3P header in Codeigniter, place following code within the index.php page, like so:
<?php

header('P3P:CP="We do not have a P3P policy!"');

// ... rest of the index.php file 
The only place I have found this worked in codeigniter :)

Note: It didn't worked using Codeigniter output class ( $this->output->set_header )

Monday, August 19, 2013

Run a cronjob to schedule tasks on Linux using crontab and url

If you’ve got a website that’s heavy on your web server, you might want to run some processes like generating thumbnails or enriching data in the background. This way it can not interfere with the user interface. Linux has a great program for this called cron. It allows tasks to be automatically run in the background at regular intervals. You could also use it to automatically create backups, synchronize files, schedule updates, and much more. Welcome to the wonderful world of crontab.

Crontab
Cron is a daemon that executes scheduled commands. Crontab is the program used to install, deinstall or list the tables used to drive the cron daemon. The crontab (cron stands for time (Greek); tab stands for table) command, found in Unix and Unix-like operating systems, is used to schedule commands to be executed periodically. To see what crontab are currently running on your system, you can open a terminal and run:
crontab -l
To edit the list of cronjobs you can run:
crontab -e
This will open a the default editor to let us manipulate the crontab. If you save and exit the editor, all your cronjobs are saved into crontab. Cronjobs are written in the following format:
* * * * * /bin/execute/this/script.sh
Scheduling explained
As you can see there are 5 stars. The stars represent different date parts in the following order:
1. minute (from 0 to 59)
2. hour (from 0 to 23)
3. day of month (from 1 to 31)
4. month (from 1 to 12)
5. day of week (from 0 to 6) (0=Sunday)
Special words
Instead of the first five fields, you can also put in a keyword as follows:
@reboot     Run once, at startup
@yearly     Run once  a year     "0 0 1 1 *"
@annually   (same as  @yearly)
@monthly    Run once  a month    "0 0 1 * *"
@weekly     Run once  a week     "0 0 * * 0"
@daily      Run once  a day      "0 0 * * *"
@midnight   (same as  @daily)
@hourly     Run once  an hour    "0 * * * *"
Pratical examples on how to run CRON command using URL address
    
//CRON command to run URL address every hour
@hourly wget -q -O /dev/null "http://yoursite.com/tasks.php"

//CRON command to run URL address every midnight 
0 0 * * * wget -q -O /dev/null "http://yoursite.com/tasks.php"
You can use following crontab command also to run a task
* * * * * wget -O - http://yoursite.com/tasks.php >/dev/null 2>&1
Using -O - means that the output of the web request will be sent to STDOUT (standard output). By adding >/dev/null we instruct standard output to be redirect to a black hole. by adding 2>&1 we instruct STDERR (errors) to also be sent to STDOUT, and thus all output will be sent to a blackhole. (so it will load the website, but never write a file anywhere).

Ref: http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/ and http://stackoverflow.com/questions/13259530/using-cron-jobs-to-visit-url

Thursday, August 15, 2013

How to empty or truncate mysql table using codeigniter active record?

If you want to empty or truncate a mysql table using Codeigniter active record, use the following code.
To empty
$this->db->empty_table();
This will generate a delete SQL string and runs the query.
// DELETE FROM mytable
To truncate
$this->db->from('mytable'); 
$this->db->truncate(); 
// or 
$this->db->truncate('mytable');
This will generate a truncate SQL string and runs the query.
// TRUNCATE mytable 
Source: http://www.learnhow2do.com/computer/internet/2013/04/13/learn-how-to-empty-or-truncate-table-using-codeigniter-active-record/

Wednesday, August 14, 2013

How to get time and Date from datetime stamp in php and mysql?

You can use the strtotime php function to separate date and time from datetime string. It can come in handy when you need to separate date and time from datetime format in the mysql database.
   $datetime = '2013-08-14 11:45:45';
   echo date("Y-m-d",strtotime($datetime)); // output 2013-08-14
   echo  date("H:i:s",strtotime($datetime)); // output 11:45:45
Small and simple solution. :)

Tuesday, August 13, 2013

Creating a cronjob with Codeigniter

You need cronjob to achieve many things. For example, if you need to reset/update the database every 30min or one hour, you need cronjob.

First create a controller in the folder application/controller/. I create a controller like this application/controller/crontodo.php
class Crontodo extends CI_Controller{

 function __construct()
 {
  parent::__construct();
  //load the model
  $this->load->model('cronjob_model','',TRUE);
 }

 function index()
 {
  $this->cronjob_model->my_cronjob();
 }
}
The next one is to create the model as application/models/cronjob_model.php
class Cronjob_model extends CI_Model
{
  function __construct()
  {
  // Call the Model constructor
  parent::__construct();    
  }

         function my_cronjob(){

          // here you should add what you wanna do with cronjob such as drop, create, add, delete. update etc

          }
}
And you can set up a cron job through a crontab.You need to add a URL, for example http://www.example.com/index.php/crontodo

Thursday, August 8, 2013

Contact form using jquery validation, codeigniter and bootstrap

I have used Jquery validation plugin for validation, bootstrap for styling HTML and Codeigniter to send the email.
I have posted the complete source code and screen dump of final outcome. Feel free to use it. :)

Bootstrap Contact form 

Form built with Twitter Bootstrap
<style type="text/css">
label.valid {
width: 24px;
height: 24px;
background: url(../img/valid.png) center center no-repeat;
display: inline-block;
text-indent: -9999px;
}
label.error {
font-weight: bold;
padding: 2px 8px;
margin-top: 2px;
}
</style>
<div class="container-fluid">
<div class="row-fluid">
<div class="span9 offset3">
<form action="" id="contact-form" class="form-horizontal" method="post">
<fieldset>
    <div class="control-group">
        <label class="control-label" for="name">Your Name</label>
        <div class="controls">
            <input type="text" class="input-xlarge" name="name" id="name">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="email">Email Address</label>
<div class="controls">
            <input type="text" class="input-xlarge" name="email" id="email">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="subject">Subject</label>
        <div class="controls">
            <input type="text" class="input-xlarge" name="subject" id="subject">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="message">Your Message</label>
        <div class="controls">
            <textarea class="input-xlarge" name="message" id="message" rows="3"></textarea>
        </div>
    </div>
    <div class="control-group">
        <div class="controls">
            <button type="submit" class="btn">Send Email</button>
        </div>
    </div>
</fieldset>
</form>
<!-- output the results (Success or failure message from controller) -->
<div id="results"></div>
</div>
</div>
</div>

Required jQuery/Javascript
$(document).ready(function() {
 $('#contact-form').validate({
  rules: {
   name: {
    minlength: 2,
    required: true
   },
   email: {
    required: true,
    email: true
   },
   subject: {
    minlength: 2,
    required: true
   },
   message: {
    minlength: 2,
    required: true
   }
  },
  highlight: function(element) {
   $(element).closest('.control-group').removeClass('success').addClass('error');
  },
  success: function(element) {
   element.text('OK!').addClass('valid').closest('.control-group').removeClass('error').addClass('success');
  }, 
  
  submitHandler: function( form ) {
       
        $.ajax({
            url : 'contact/process',
            data : $('#contact-form').serialize(),
            type: "POST",
            success : function(data){
             $("#contact-form").hide('slow');
             $('#results').html(data);
            }
        })
        return false;
     }
  
 });  
}); // end document.ready

Codeigniter Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Contact extends CI_Controller {

 function process()
 { 
  $this->load->library('email');
              //grab the post data
$this->email->from($this->input->post('email'), $this->input->post('name'));
  $this->email->to('sombody@gmail.com'); 
  $this->email->subject($this->input->post('subject'));
  $this->email->message($this->input->post('message')); 
  
  if($this->email->send())
  {
     echo "We have successfully received your email. We will Contact you ASAP.";
  }
  else
  {
   echo "Some problem occurred.";
  }   
 }
}

/* End of file contact.php */
/* Location: ./application/controllers/contact.php */

Monday, August 5, 2013

Removing the index.php file from url in codeigniter

By default, the index.php file will be included in your URLs:
example.com/index.php/news/article/my_article
You can easily remove this file by using a .htaccess file with some simple rules.
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ index.php?/$1 [L]
This htaccess rule is little different than rule you can find in Codeigniter's own website. When I used the codeigniters htaccess rule, it didn't worked. After searching the solution I found above solution. It worked. :)