| 0 comments ]

How to select a specified number of values starting with each alphabets in mysql.

Suppose you have a table named 'names', which has fields id and name, and you need to select two or three names from each alphabet and display it in a page. For example you have to select 3 names from the table, which contains the names starting with all the alphabets from a-z. ie, You will need to display 26 * 3 = 72 names.

Here is the answer,

SELECT 
 letter, 
 name 
FROM (
 SELECT 
  LEFT( name, 1 ) AS letter, 
  name, 
  @num := IF( @prev = LEFT( name, 1 ),@num +1, 1 ) AS row_num, 
  @prev := LEFT( name, 1 ) AS previous
 FROM 
  names,(
   SELECT 
    @num  :=0, 
    @prev := ''
  )  PHPQA
 ORDER BY name
 ) QAPHP
WHERE row_num <=3


You can find its live example on following page.
 http://sqlfiddle.com/#!2/abfd8/3
http://sqlfiddle.com/#!2/4887b/1

| 0 comments ]

Mysql query for searching a value, add weightage on the number of occurances and sort based on the weightage

Consider a table named 'data' which has columns named 'Name', and 'Content', We need to search these columns, if 'Name' colomn has a match it should have a weightage of '.08' and if 'Content' has a match it should have a weightage of '0.2' ,

Suppose 'Name' has one match and 'Content' has 3 match, then it should have a total weightage of (.08*1)+(.02*3) = .14

For that we can use the following query to get the result.


SELECT *
FROM (
SELECT * , (
(
length( `Content` ) - length( replace( LOWER(`Content`) , "SEARCHKEY", "" ) ) ) / length("SEARCHKEY" ) * .08
) + (
(
length( `Content` ) - length( replace( LOWER(`Content`) ,"SEARCHKEY", "" ) ) ) / length("SEARCHKEY" ) * .02
) AS weight
FROM data
)a
WHERE weight > 0
ORDER BY weight DESC
LIMIT 0,10

| 0 comments ]

Creating a custom VtigerCRM Module

Step 1.
Download the module creation script from the VtigerCRM or copy it from below

name = 'Phpqa';
$module->save();

// Initialize all the tables required
$module->initTables();
// Initialize Webservice
$module->initWebservice();

// Add the module to the Menu (entry point from UI). Will display under Tools menu
$menu = Vtiger_Menu::getInstance('Tools');
$menu->addModule($module);

// Add the basic module block
$block1 = new Vtiger_Block();
$block1->label = 'LBL_PHPQA_INFORMATION';
$module->addBlock($block1);

// Add custom block (required to support Custom Fields)
$block2 = new Vtiger_Block();
$block2->label = 'LBL_CUSTOM_INFORMATION';
$module->addBlock($block2);

/** Create required fields and add to the block */
$field1 = new Vtiger_Field();
$field1->name = 'Sales';
$field1->label = 'Sales';
$field1->table = $module->basetable;
$field1->typeofdata = 'V~O';
$block1->addField($field1); /** Creates the field and adds to block */

// Set at-least one field to identifier of module record
$module->setEntityIdentifier($field1);

$field2 = new Vtiger_Field();
$field2->name = 'Name';
$field2->label = 'Name';
$field2->typeofdata = 'V~O';// Varchar~Optional
$block1->addField($field2); /** table and column are automatically set */

$field3 = new Vtiger_Field();
$field3->name = 'InvoiceType';
$field3->label= 'Invoice Type';
$field3->typeofdata = 'V~O'; // Date~Mandatory
$block1->addField($field3);  /** table, column, label, set to default values */

$field4 = new Vtiger_Field();
$field4->name = 'InvoiceID';
$field4->label= 'Invoice ID';
$field4->typeofdata = 'V~O';
$block1->addField($field4);

/** END */

// Create default custom filter (mandatory)
$filter1 = new Vtiger_Filter();
$filter1->name = 'All';
$filter1->isdefault = true;
$module->addFilter($filter1);

// Add fields to the filter created
$filter1->addField($field1)->addField($field2, 1)->addField($field5, 2);

// Create one more filter
$filter2 = new Vtiger_Filter();
$filter2->name = 'All2';
$module->addFilter($filter2);

// Add fields to the filter
$filter2->addField($field1);
$filter2->addField($field2, 1);

// Add rule to the filter field
$filter2->addRule($field1, 'CONTAINS', 'Test');

/** Associate other modules to this module */
//$module->setRelatedList(Vtiger_Module::getInstance('Accounts'), 'Accounts', Array('ADD','SELECT'));

/** Set sharing access of this module */
$module->setDefaultSharing('Private'); 

/** Enable and Disable available tools */
$module->enableTools(Array('Import', 'Export'));
$module->disableTools('Merge');

?>

Step 2
Save it in your vigercrm root folder. and run the script .
Step 3
Copy the desired version of sample vtigercrm module from the vtlib/ModuleDir and paste it into the /modules directory
Step 4
Rename the folder name into the desired name you have given in the module creation script. (Phpqa)
Step 5
Rename the ModuleFile.php, ModuleFileAjax.php, ModuleFile.js to your module name. Here the ModuleFile indicates your module name. So names are like Phpqa.php, PhpqaAjax.php and PhpqaFile.js
Step 6
Open the Phpqa.php and rename the class name into Phpqa. Change the all modulename occurance into your custom module name
Change the following
 
var $table_name = 'vtiger_phpqa';
var $table_index= 'phpqaid';

var $customFieldTable = Array('vtiger_phpqacf', 'phpqaid');

var $tab_name = Array('vtiger_crmentity', 'vtiger_phpqa', 'vtiger_phpqacf');

var $tab_name_index = Array(
 'vtiger_crmentity' => 'crmid',
 'vtiger_phpqa'   => 'phpqaid',
 'vtiger_phpqacf' => 'phpqaid');


Also the change the other listed variables in the page as per our need.
Step 7
Change the Language file variable based on the module name. Its located in /language folder of the module .
 

'Phpqa' => 'Phpqa',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'LBL_PHPQABLOCK_INFORMATION' => 'Phpqa Block Information'

 
 

Step 8
You can see your module is listed in the vtigercrm admin console. Settings > Module Manager page under the custom module. Here we can disable/enable and export your module for future use. if you click on the export buttom, a Zip file will be downloaded as an installtion file. and we are reuse it in other vtiger applications.

| 0 comments ]

Can we compare equality of two floats in php ?

The answer is NO. Its not encouraged in php programming. The reason is, its related to system confugurations. We can not trust these values, it may vary in different systems. Consider this example


if( 0.111 + 0.222 == 0.333 ){
 echo 'a and b are same';
}
else {
 echo 'a and b are not same';
} 


Here the value 0.333 is A literal but a float(calculated sum) using to compare it. So it may result some variations in the result. some times it will show the 'true' part, sometime it will show the 'false' part.
You can see its more explantions on php.net
here are the links

http://php.net/manual/en/language.operators.comparison.php 
http://in.php.net/float 

 To overcome this, we can use the precition checking


  function floatCheck($x,$y,$precision=0.0000001) 
    { 
        return ($x+$precision >= $y) && ($x-$precision <= $y); 
    }

floatCheck(1.0002541,1.0002540,$precision=0.0000002);

| 0 comments ]

How to add or remove WWW on URLs using htaccess. Adding www to your site url using .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^yoursite.in$ 
RewriteRule (.*) http\:\/\/www\.yoursite\.in\/$1 [R=301]

Removing www from your site url using .htaccess

RewriteCond %{HTTP_HOST} ^yoursite\.in$ [OR]
RewriteCond %{HTTP_HOST} ^www\.yoursite\.in$ [NC]
RewriteRule ^/?$ "http\:\/\/yoursite\.in\/" [R=301,L]

| 0 comments ]

Compressing HTML, CSS, Javascript using Apache There are two methods to available in apache to handle compression of webpage contents. They are mod_gzip and mod_deflate . Usually deflate comes pre-installed on servers. We can install both in our apache server. before we install, lets check is it availble in your server,

In order to check whether these apache directives are installed or not, we can create a test php file with calling function the phpinfo() function. From that we can see "Loaded Modules" setting in the "apache2handler" header.

From that we can see whether its installed or not. in the case of deflate, we can see "mod_deflate" under that section.

Install mod_deflate in your server

a2enmod deflate

the restart your apache with the following command

/etc/init.d/apache2 restart

We can enable this feature using .httacess file in the root directory

## Apache2 deflate support if available
##
## Important note: mod_headers is required for correct functioning across proxies.
##

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.[0678] no-gzip
BrowserMatch \bMSIE !no-gzip

 
Header append Vary User-Agent env=!dont-vary
 
 
# The following is to disable compression for actions. The reason being is that these
# may offer direct downloads which (since the initial request comes in as text/html and headers
# get changed in the script) get double compressed and become unusable when downloaded by IE.
SetEnvIfNoCase Request_URI action\/* no-gzip dont-vary
SetEnvIfNoCase Request_URI actions\/* no-gzip dont-vary
 


This is a simple version for the usage of mod_deflate.c in .httacces


 AddOutputFilterByType DEFLATE application/x-javascript text/css text/html text/xml


The another option is mod_gzip, it is usually 4 -6 times faster than deflate. But its needs too much server load compared to deflate. So its advised to use mod_gzip on low-traffic sites and in large traffic sites, its better to use deflate. The settings for mod_zip is following. its can be given in a .htaccess file.

# Turn on mod_gzip if available

    mod_gzip_on yes
    mod_gzip_dechunk yes
    mod_gzip_keep_workfiles No
    mod_gzip_minimum_file_size 1000
    mod_gzip_maximum_file_size 1000000
    mod_gzip_maximum_inmem_size 1000000
    mod_gzip_item_include mime ^text/.* 
    mod_gzip_item_include mime ^application/javascript$
    mod_gzip_item_include mime ^application/x-javascript$
    # Exclude old browsers and images since IE has trouble with this
    mod_gzip_item_exclude reqheader "User-Agent: .*Mozilla/4\..*\["
    mod_gzip_item_exclude mime ^image/.*


| 0 comments ]

Mysql optimization by configuring the query cache
In Ubuntu (debian) the query cache settings can be changed in the following file /etc/mysql/my.cnf
 Use the following command to edit the file
 nano /etc/mysql/my.cnf or vi /etc/mysql/my.cnf 

In this file you can find following settings.
#  Query Cache Configuration
#   
query_cache_limit       = 1M
query_cache_size        = 16M
#

Query Cache options SQL_CACHE
SELECT SQL_CACHE id, name FROM students;

SQL_NO_CACHE
 SELECT SQL_NO_CACHE id, name FROM students; 

We can check whether cache enabled in mysql database
 mysql> SHOW VARIABLES LIKE 'have_query_cache'; 

We can set Query_cache by queries
mysql>SET GLOBAL query_cache_size = 41984; 

If "query_cache_size " has value '0', then query cache is disabled, in the mysql environment. Also need to take care about the setting the query_cache_size with huge value. that will affect the system. For more information about the query caching you can visit http://dev.mysql.com/doc/refman/5.1/en/query-cache.html

| 0 comments ]

Lets have a look on How to use the Stored Procedures in Mysql. We can use these stored procedures in PHP. The following example shows how to use mysql stored functions in PHP scripts. Defining a stored function

DELIMITER $$

DROP PROCEDURE IF EXISTS `tester`.`GetAllProducts`$$
CREATE PROCEDURE `tester`.GetAllProducts(IN t INT,IN age INT)
 BEGIN
 UPDATE students SET age = age WHERE id = t;
 INSERT INTO students (name,age,sex) VALUES ('Jayan',35,'M');
 END $$
DELIMITER ;

Calling a stored function from PHP

$res = mysql_query('call GetAllProducts(2,30)');

if ($res === FALSE) {
    die(mysql_error());
} else {
    echo "@";
    print_r($res);
}

| 0 comments ]

Let us have a look on How to use the Stored Functions in Mysql. Here I am trying to show you how to use mysql stored functions in PHP scrips. Hope you all know, what is Mysql Stored Functions. Its like normal mysql functions, its written by the user. It will return results as a normal mysql functions. It can be called in normal sql statements. Defining a stored function

DELIMITER $$

DROP FUNCTION IF EXISTS `tester`.`sf_test`$$
CREATE FUNCTION `tester`.`sf_test` ()
RETURNS INT
READS SQL DATA
BEGIN
    DECLARE tot_count INT;
    select count(*) INTO tot_count from students;
    RETURN tot_count;
END$$

DELIMITER ;

Calling a stored function from PHP

$res = mysql_query('select sf_test()');

if ($res === FALSE) {
    die(mysql_error());
} else {
    echo "@";
    print_r($res);
}

| 1 comments ]

How to find out the CREATE TABLE statement of a selected table.

The 'SHOW CREATE TABLE' command will show the CREATE TABLE statement of a selected table. It will be very helpful for the database backup actions.

SHOW CREATE TABLE `tablename`

It will return two colomns one is its table name and other is the 'CREATE TABLE' statement. 

CREATE TABLE `tablename` (
 `id` int(10) NOT NULL,
 `title` varchar(256) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Hope this will helpful for someone ! 

| 0 comments ]

How to find out the Mysql storage engine type of a table.

The following queries will show the engine type of a table

SHOW
TABLE STATUS
WHERE
name= 'tablename';

The Following query will also help you to find out the storage engine.

Each Mysql table's informations are stored in the 'INFORMATION_SCHEMA' table. 

The following query will show the storage engine's of the given databse table.

SELECT 
TABLE_NAME,ENGINE 
FROM information_schema.TABLES
WHERE 
TABLE_SCHEMA = 'dbname'

To show particular table's mysql engine type.

SELECT TABLE_NAME,
ENGINE FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'dbname'
AND TABLE_NAME = 'tablename'

Hope this will helpful for you all.

| 0 comments ]

Its a callback function for codeigniter Form validation class. It will check, whether the input date is a valid date, and it will also check whether the user is above a particular age limit. Here its 13 years.

You can use this function in codeigniter as given below

load form validation class for codeigniter into your controller functions

$this->load->library('form_validation');

Set the rules for date of birth field

$config = array(
                  array(
                     'field'   => 'dob',
                     'label'   => 'date of birth',
                     'rules'   => 'trim|required|callback_dob_valid'
                  ),
                 );

if you need you can add additional rules
Set the Rule for your form

$this->form_validation->set_rules($config);

then run the form against these rules

if ($this->form_validation->run() == FALSE)
{
     // reload the view
}
else
{
      // success action
}

/**
 * Date of birth
 * Checking for a valid date for date of birth and age verification
 *
 * @author http://phpqa.in
 * @since
 * @copyright GPL 
 */
function dob_valid($str)
{
if($str)
{
//match the format of the date dd-mm-yyyy
 // for yyyy-mm-dd  use "/^([0-9]{4})-([0-9]{2})-([0-9]{4})$/
 if (preg_match ("/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/", $str, $parts))
 {
   //check weather the date is valid of not   
 
   $day        = $parts[1];
   $month = $parts[2];
   $year        = $parts[3];
  
   /*
   // for yyyy-mm-dd 
   $day        = $parts[3];
   $month = $parts[2];
   $year        = $parts[1];
   */
  
   // checking 4 valid date
  
   if(!checkdate($month,$day,$year))
   {
$this->form_validation->set_message('dob_valid', '%s is not a valid date, use dd-mm-yyyy format');
return false;
}
else
{
//check for future date
$dob = $year.'-'.$month.'-'.$day;
if($dob < date("Y-m-d"))
{
// age verification using DOB
$dob_time = mktime(0, 0, 0, $month,$day,$year);
$age_req = strtotime('+13 years', $dob_time);
if(time() < $age_req)
{
   $this->form_validation->set_message('dob_valid', 'You must be atleast 13 years old');
   return false;
}
else
{
  return true;
}
return true;
}
else
{
$this->form_validation->set_message('dob_valid', '%s should be a past date');
return false;
}
}
 }
 else
 {
  $this->form_validation->set_message('dob_valid', '%s is not a valid date, use dd-mm-yyyy format');
  return false;
 }
}
return false;

By removing the "$this->form_validation->set_message()" function from the above function we can use the above function in any php scripts
  

| 0 comments ]


function to validate the a given credit card based on the card type and based on luhns algorithm



/**
* function to validate a given credit card based on the card type and based                    on luhns algorithm
*
* @param $c_number credit card number
* @param $c_type credit card type
* @return boolean. true or false.
*
*/


function validateCreditCard($c_number,$c_type='')
{
$cc_num = $number;
if($c_type == "American") 
    {
$denum = "American Express";
elseif($c_type == "Dinners") 
{
$denum = "Diner's Club";
elseif($c_type == "Discover") 
{
$denum = "Discover";
elseif($c_type == "Master") 
{
$denum = "Master Card";
elseif($c_type == "Visa") 
{
$denum = "Visa";
else
{
}
// checking card types and its length based on card type
if($type == "American") 
{
$pattern = "/^([34|37]{2})([0-9]{13})$/"; //American Express
if (preg_match($pattern,$cc_num)) 
{
$verified = true;
} else 
{
$verified = false;
}
elseif($type == "Dinners") 
{
$pattern = "/^([30|36|38]{2})([0-9]{12})$/"; //Diner's Club
if (preg_match($pattern,$cc_num)) 
{
$verified = true;
} else {
$verified = false;
}
elseif($type == "Discover") 
{
$pattern = "/^([6011]{4})([0-9]{12})$/"; //Discover Card
if (preg_match($pattern,$cc_num)) 
{
$verified = true;
} else {
$verified = false;
}
elseif($type == "Master") 
{
$pattern = "/^([51|52|53|54|55]{2})([0-9]{14})$/"; //Mastercard
if (preg_match($pattern,$cc_num)) 
{
$verified = true;
} else 
{
$verified = false;
}
elseif($type == "Visa") 
{
$pattern = "/^([4]{1})([0-9]{12,15})$/"; //Visa
if (preg_match($pattern,$cc_num)) 
{
$verified = true;
else 
{
$verified = false;
}
}
if($verified == false) 
{
return false;
else 
// checking the card number with luhns algorithm
$stack = 0;
$number = str_split(strrev($number), 1);
if(array_sum($number) == 0)
{
return false;
}
foreach ($number as $key => $value)
{
if ($key % 2 != 0)
{
$value = array_sum(str_split($value * 2, 1));
}
$stack += $value;
}
if($stack%10 == 0)
{
return true;
}
return false;
}
}

Sample code to use the function.

if(validateCreditCard("340000000000009","American"))
{
echo "Yeah Its a valid credit card number";
}
else
{
echo "Oops, Its not a valid credit card number";
}




| 1 comments ]

When, I was developing a shipping software based on Fedex ans UPS APIs, I got an issue with packagaging. It was, the packing the products in an optimised way. there are few methods to solve this issues in mathematics. Here's a program which can be used to solve the packaging problem.



   // setting up Max value for each contatiner

    DEFINE('MAX_VALUE',40);

   //   different set of array values for testing

    //$input = array(18,13,33,7,26,39,16,5);
    //$input = array(15,28,19,21,4,36,12,15);

    $input = array(1,2,3,4,5,30,6,7,8,9,10,1,2,3,4,5,30,6,7,8,9,10);

    //$input = array(15,15,15,15,15,10,10,25);

    $expected_containers = ceil(array_sum($input)/MAX_VALUE);
    $no_of_items = count($input);
    rsort($input);

    for($i = 0; $i < $no_of_items; $i++)
   {
        if(isset($input[$i]))
       {
            $remainder = MAX_VALUE - $input[$i];
            for($j = $i + 1; $j <= $no_of_items; $j++)
           {
                if(isset($input[$j]) && $input[$j] <= $remainder)
                {
                    if(!isset($container[$i]))
                   {
                        $container[$i] = array($input[$i],$input[$j]);
                    }
                     else
                    {
                        array_push($container[$i],$input[$j]);
                    }
                    $remainder = $remainder - $input[$j];
                    unset($input[$j]);
                }
                if(!isset($container[$i]))
                {
                    $container[$i] = array($input[$i]);
                }
            }
        }
    }

    echo "Expected containers ".$expected_containers."
";
    echo "Actual containers ".count($container)."
";
    echo '

';

    print_r($container);

    foreach($container as $val)
   {
 $productsum = array_sum($val);
 echo  "
".$productsum;
   } 

   echo '
';
?>




seems helpful someone, who is developing a shipping software.

@credits Praveesh

| 0 comments ]

Handling the multiple checkboxes with jquery for Check All, Uncheck All
and get values from selected values. V2 For new versions of Jquery.


include jquery

<script language="JavaScript" src="youserveraddres/js/jquery.js"></script>


your html

<input name="phpqa[]" type="checkbox" value="1">1
<input name="phpqa[]" type="checkbox" value="2">2
<input name="phpqa[]" type="checkbox" value="3">3
<input name="phpqa[]" type="checkbox" value="4">4
<input name="phpqa[]" type="checkbox" value="5">5
<input name="phpqa[]" type="checkbox" value="6">6
<input name="phpqa[]" type="checkbox" value="7">7
<input name="phpqa[]" type="checkbox" value="8">8

<a href="javascript:void();" onclick="markAll()">Check All</a>
<a href="javascript:void();" onclick="unMarkAll()">Uncheck All</a>
<a href="javascript:void();" onclick="getSelectedVals()">Get Checked Values</a>


// function for mark all / check all

function markAll(){
$("input[name='phpqa[]']").each(function() {
this.checked = true;
});
}


// function for uncheck all

function unMarkAll(){
$("input[name='phpqa[]']").each(function() {
this.checked = false;
});
}


//fetching selected values / checked values

function getSelectedVals(){
$("input[name='phpqa[]']").each(function() {
if ($(this).attr('checked'))
{
alert($(this).val());
}
});
}

| 0 comments ]

How to set up .htpasswd in a site ?

Step 1 : create file .htpasswd and put out side our root folder but inside www for safety.

Step 2 : open the file .htpasswd and add like username:password -> then save and close. So now file contains

   username:password

Step 3 : Add the following in .htaccess file

AuthName "Restricted Area"
AuthType Basic
AuthUserFile D:/wamp/www/.htpasswd # full path to .htpasswd file
AuthGroupFile /dev/null
require valid-user


----------

Now open you site http://mysite.com
It will ask username and password to display.

Use this functionality in all admin side. It will block all hackers.

Posted by : Shijith Nambiar

| 1 comments ]

Redirecting a domain into an another directory of same level

Consider there is a domain called mydomain.com, which curretly pointed to a directory named 'folder1' in the home directory(public_html). Now, I just want to redirect this domain to an another directory, which is in the same home folder(public_html named 'folder2'

In this case we could use the following htaccess code, just remember that you have included the 'RewriteEngine On' statement at the beginning of the htaccess file

RewriteCond %{HTTP_HOST} ^mydomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$
RewriteCond %{REQUEST_URI} !^/folder2/
RewriteRule (.*) /folder2/$1

Now the when type mydomain.com/folder2 it will redirect the folder named 'folder2' in which the directory level the folder 'folder1' is. Not to the subfolder of folder1.

Another case of usage of htaccess redirect.

For setting an HTML splash page for your domain.


if you want to redirect all the traffic to the domain mydomain.com/ to a new folder named /anothersub, but you want to keep the other existing subfolders of mydomain.com/ working as they act

RewriteCond %{HTTP_HOST} ^mydomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) /anothersub/index.html

In this case the traffic to mydomain.com will go to mydomain.com/anothersub/index.html instead of mydomain.com/index.html.
but the traffic to mydomain.com/subfolder1 , mydomain.com/subfolder2, blah blah .. will go to corresponding pages as usual.

| 0 comments ]

Adding cron tasks in Linux using SSH

in most hosting platforms we have the control panel console to add cron tabs. But in the case of our local linux machine, or server's which does not have control panel, we could use the following

adding the commands in the crontab

Login in the console as super user

Use the following command " sudo crontab -e " to open the crontab file.
Some times you will get a message to select the editor to open the file. select the desired editor. the crontab file will open and it contains the syntax for the crontab command. its looks like " # m h dom mon dow command "

m -> minute
h -> hour
dom -> date of month
mon -> Month
dow -> day of week

for setting cron for every minute use the following code

* * * * * yourcommand

for each five minutes

*/5 * * * * yourcommand

For hourly cron

0 * * * * yourcommand

For daily cron

0 0 * * * yourcommand

for yearly

0 0 1 1 * yourcommand


we could also run the cron in particular minute ,hour etc.

15,45 * * * yourcommand

the cron will run each 15 and 45 min of every hour

0 12,24 * * yourcommand

the cron will run each 12 and 24 every hour


where the value of * holds value "Every".


After setting the cronjob save the cron tab file.


For testing these cronsettings please follow following steps..

create the php script and save as mycron.php

root","root");
mysql_select_db("crontest");
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO `test`(`timer`) VALUES ('$date')");
?>

create corresponding database and table

CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) NOT NULL auto_increment,
`timer` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM



open crontab file add following command


*/5 * * * * php /pathto/mycron.php

and save the file and check back the mysql table for inserted values.

I hope this post will help you know details about adding cron job without the control panel or plesk console in your server or in the local machine

| 0 comments ]

Running php script on command line & installing php5-cli library in phpserver

To run php in command line, you need to not only PHP, but also the PHP5-cli library in your php server. The PHP5-cli stands for command-line interpreter for the PHP5 scripting language. It is very useful when we need test our scripts from the shell. In some cases we need to install this library for running cronjobs on the server.


how to install php5-cli. in linux machines.


first login as super user : " su username "

after login just use the following command "sudo apt-get install php5-cli "

the php5-cli installation has completed

just restart your apache server. For that we can use the following command

How to restart a apache server on linux

sudo /etc/init.d/apache2 restart

After the restart of your server, the php5-cli has been installed on your server. and just try to run a simple php script on your server.

| 0 comments ]

/*******************************/
# function to get the byte format #
# @phpqa.blogspot.com #
/*******************************/

function getByteFormat($number,$caption="small"){

$unit = "";
switch($number){

case($number >= 1099511627776):

$number = round($number / 1099511627776, 1);
$unit = $caption == "small" ? "TB" : "Terabyte";
break;

case($number >= 1073741824):

$number = round($number / 1073741824, 1);
$unit = $caption == "small" ? "GB" : "Gigabyte";
break;

case($number >= 1048576):

$number = round($number / 1048576, 1);
$unit = $caption == "small" ? "MB" : "Megabyte";
break;

case($num >= 1024):

$number = round($number / 1024, 1);
$unit = $caption == "small" ? "KB" : "Kilobyte";
break;

default:
$unit = $caption == "small" ? "B" : "Byte";
$number = $number;
break;

}

return number_format($number, 2).' '.$unit;

}

# How to use #

echo getByteFormat(10995116277,"big");
echo getByteFormat(109951162799,"small");
echo getByteFormat(10995116261099);

?>

please try this function and lemme give your feedback as comments