Flipkart

Monday, November 15, 2010

drupal_set_message() in user_logout

http://drupal.org/node/754560


   $cookieParams = session_get_cookie_params();
    session_start();
    session_set_cookie_params($
cookieParams);
  // Load the anonymous user
  $user = drupal_anonymous_user(session_id());
  drupal_set_message(t('You have successfully logged out of the system. Enter your Username and Passwords below to login again.'));

Thursday, October 28, 2010

drupal_get_form() for returning a node form

// required for Drupal 6
module_load_include('inc', 'node', 'node.pages');
// which nodeform you want
$node_type = 'YOURNODETYPE';
$form_id = $node_type . '_node_form';
// maybe add current users info
global $user;
// create a blank node

$node->uid = $user->uid;
$node->name = (isset($user->name) ? $user->name : '');
$node->type = $node_type;

// Invoke hook_nodapi and hook_node
node_object_prepare($node);
// Or you can also use an exiting node, for example
// $node = node_load(123);
// and the display the form:
$output = drupal_get_form($form_id, $node);

---------------------------------------------------------------------------------------
For User Edit Form:

include_once drupal_get_path('module', 'user') . '/user.pages.inc';
global $user;
 $output = "";
 $account = user_load($user->uid);
 $category = 'account';
//  print_r($userInfo);
 $output = drupal_get_form('user_profile_form', $account, $category);
return $output;

Wednesday, September 22, 2010

Install Adobe Reader (acroread) on Fedora 12 and Fedora 13

http://macintoshbrasil.com/2010/06/10/install-adobe-acrobat-pdf-reader-on-fedora-centos-red-hat-rhel/

Tuesday, September 14, 2010

Enable the New Google Search

1. Go to Google.com.
2. Once it loads, enter this code into your web browser's URL address field:

javascript:void(document.cookie="PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com");

There shouldn't be any http://google.com in front of that. Just that code.

3. Hit enter.
4. Reload or open a new Google.com page and you will have access to the new user interface.

Monday, September 6, 2010

get the Next Auto Increment number in Mysql

$query = mysql_query("SELECT MAX(id) FROM `table`");
$results = mysql_fetch_array($query);
echo $results["Auto_increment"];

Friday, September 3, 2010

Drupal l() With complex link with image Example

$img = '< img src="'.$base_path . $directory . '/images/rssIcon.png" >';
l($img, 'user/3', array('attributes' => array('class' => 'link', 'id' => 'xxx', 'title' => 'Title'), 'html' => 'true'));

Thursday, August 26, 2010

IEs4Linux (Fedora)

Open a terminal. Log in as root to install wine and cabextract:

yum -y install wine*
yum -y install cabextract

Logout and install IEs 4 Linux with your normal user account:

wget http://www.tatanka.com.br/ies4linux/downloads/ies4linux-latest.tar.gz
tar zxvf ies4linux-latest.tar.gz
cd ies4linux-*
./ies4linux

Tuesday, August 24, 2010

Installing rar and unrar programs in Linux or Unix

Under Debian Linux, you can use the same apt-get method as follows to install unrar program:

$ apt-get install unrar


If you are using Fedora core Linux then use yum command as follows:

$ yum install unrar


If you are using FreeBSD, you can use:

$ pkg_add -v -r unrar


If any of above, methods is not working, you can download binary package from official rarlab site and choose the right package for your machine... for example, i chose the latest (by the time i write this post):

$ cd /tmp
$ wget http://www.rarlab.com/rar/rarlinux-3.7.1.tar.gz


then untar the file:

$ tar -zxvf rarlinux-3.7.1.tar.gz


Both rar and unrar commands are located in rar sub-directory. Just go to rar directory:

$ cd rar
$ ./unrar


Now copy rar and unrar to /bin directory:

$ cp rar unrar /bin


Then you can use the same method on creating and extracting rar files in linux in my previous post.

Another thing to add, you can also test the integrity of archive, with this command:

$ unrar t filename.rar


or list the files inside the rar file using this command:

$ unrar l filename.rar

Thursday, August 12, 2010

Export Database Data to .XLS in PHP


$DB_Server = "localhost";        //your MySQL Server
$DB_Username = "username";         //your MySQL User Name
$DB_Password = "password";        //your MySQL Password
$DB_DBName = "databasename";            //your MySQL Database Name

 $DB_TBLName = "users";           //your MySQL Table Name
$ttype = $DB_TBLName;

 $sql = "Select * from $DB_TBLName"; 

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password)
    or die("Couldn't connect to MySQL:
" . mysql_error() . "
" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect)
    or die("Couldn't select database:
" . mysql_error(). "
" . mysql_errno());
//execute query
$result = @mysql_query($sql,$Connect)
    or die("Couldn't execute query:
" . mysql_error(). "
" . mysql_errno());


    while($row = mysql_fetch_row($result))
    {
           $data = $row;

    }


function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';

}

# filename for download $filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($data as $row) {
if(!$flag) { # display field/column names as first row echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\n";
}
exit;

Thursday, August 5, 2010

Codeigniter Layout Library

Create Layout.php in libraries(/application/libraries/Layout.php) folder and copy the below code in the file
< ?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Layout { var $obj; var $layout; function Layout($layout = "layout_main") { $this->obj =& get_instance();
$this->layout = $layout;
}

function setLayout($layout)
{
$this->layout = $layout;
}

function view($view, $data=null, $return=false)
{
$loadedData = array();
$loadedData['content_for_layout'] = $this->obj->load->view($view,$data,true);

if($return)
{
$output = $this->obj->load->view($this->layout, $loadedData, true);
return $output;
}
else
{
$this->obj->load->view($this->layout, $loadedData, false);
}
}
}
? >


Then load your library in your controller

You can use it in two ways. First and obvious is to place the following line in the controller’s constructor function.

$this->load->library('layout', 'layout_main');

The second is by enabling codeIgniter to autoload the library by editing /application/config/autoload.php

$autoload['libraries'] = array('layout');

in your controller you may do this:

$this->layout->view('welcome_message');

Master layout

/application/views/layout_main.php
Your view file must use $content_for_layout. For example:

<html>
<head>
<title><?=$title_for_layout?></title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="/css/main.css" type="text/css" />
</head>
<body>
<div id="pagewidth" >
  <div id="header" ><img src="/images/header.jpg" width="700" height="200"></div>
  <div id="wrapper" class="clearfix" >
    <div id="twocols" class="clearfix">
      <?php echo $content_for_layout?>
    </div>
  </div>
  <div id="footer" > Footer </div>
</div>
</body>
</html>

Monday, August 2, 2010

Add JS and CSS files in *.tpl.php in Drupal6

function yourtheme_preprocess_node(&$variables) {
if ($your_condition) {
drupal_add_css(path_to_theme(). "/filename.css", "theme");
$variables['styles'] = drupal_get_css();

drupal_add_js(file_directory_path() .'/javascript.js', 'inline');
$vars['scripts'] = drupal_get_js();
}
}

Monday, July 26, 2010

Install Google Chrome with YUM on Fedora 13, Red Hat

Add following to /etc/yum.repos.d/google.repo file:
32-bit

[google]
name=Google - i386
baseurl=http://dl.google.com/linux/rpm/stable/i386
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

64-bit

[google64]
name=Google - x86_64
baseurl=http://dl.google.com/linux/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

Note: Both 32-bit and 64-bit repos can be placed in the same file.

## Install Google Chrome Stable version
yum install google-chrome-stable

## OR install Google Chrome Beta version##
yum install google-chrome-beta

## OR install Google Chrome Unstable version##
yum install google-chrome-unstable

Thursday, July 1, 2010

Simpletest: submitFormByName

The SimpleTest PHP unit tester and web test framework.It has support for SSL, forms, frames, proxies and basic authentication. The idea is that common but fiddly PHP tasks, such as logging into a site, can be tested easily.

Unfortunately Simpletest doesnot provide a function for submit a form with its Name.But we can implement this function by 3 small changes in 3 different files.

1)browser.php 
        In this add below code

    function submitFormByName($name) {
        if (! ($form = &$this->_page->getFormByName($name))) {
            return false;
        }
        $success = $this->_load(
                $form->getAction(),
                $form->submit());
        return ($success ? $this->getContent() : $success);
    }


2)Page.php
        Add below function

    function &getFormByName($name) {
        for ($i = 0; $i < count($this->_complete_forms); $i++) {
            if ($this->_complete_forms[$i]->getName() == $name) {
                return $this->_complete_forms[$i];
            }
        }
        $null = null;
        return $null;
    }


3)Form.php

         Here u have to declare variable caleed
                     $this->_name = $tag->getAttribute('name'); 
        in constructor(SimpleForm) then add the function

    function getName() {
        return $this->_name;
    }


 Thats all. Now you can submit a form with its name also.


      

Tuesday, June 22, 2010

Perl: Getting Started

Here is the good link for Perl beginners.

http://www.cgi101.com/book/ch1/text.html

 Perl is a simple, easy to learn language, yet powerful enough to accomplish very difficult and complex tasks. It is widely available, and is probably already installed on your Unix server. You don't need to compile your Perl programs; you simply write your code, save the file, and run it (or have the web server run it). The program itself is a simple text file; the Perl interpreter does all the work. The advantage to this is you can move your program with little or no changes to any machine with a Perl interpreter. The disadvantage is you won't discover any bugs in your program until you run it..............

Thursday, June 17, 2010

Highlight Search Words

String Manipulation

This first method will highlight all the occurances of the string and is case sensitive. It uses str_replace to do the required manipulation but has faults in not being able to tell the difference between PHP and PHPRO. It will highlight the text "PHP" and "PHP"RO which may be the desired result.


<?php

/** 
 * 
 * @highlight words 
 * 
 * @param string $string 
 * 
 * @param array $words 
 * 
 * @return string 
 * 
 */
 
function highlightWords($string$words)
 {
    foreach ( 
$words as $word )
    {
        
$string str_ireplace($word'<span class="highlight_word">'.$word.'</span>'$string);
    }
    
/*** return the highlighted string ***/
    
return $string;
 }

/*** example usage ***/
$string 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
/*** an array of words to highlight ***/
$words = array('php''sql');
/*** highlight the words ***/
$string =  highlightWords($string$words);

?>

<html>
<head> 
<title>PHPRO Highlight Search Words</title> 
<style type="text/css">
.highlight_word{
    background-color: pink;
}
</style> 
</head>
<body>
 <?php echo $string?>
</body>
</html>

Regular Expression

This second method makes us of PHP PCRE to achieve a better result. The seach is case insensitive, which means it will match php and PHP. This method has the added benifit of being able to use word boundries which enables highlighting of the word PHP but not PHPRO. The word boundary prevents partial matching of the search text and of highlighting parts of words. If this is the functionality you require, this is the method to choose.


 <?php

/**
 * @highlight words
 *
 * @param string $text
 *
 * @param array $words
 *
 * @return string
 *
 */
function highlightWords($text$words)
{
        
/*** loop of the array of words ***/
        
foreach ($words as $word)
        {
                
/*** quote the text for regex ***/
                
$word preg_quote($word);
                
/*** highlight the words ***/
                
$text preg_replace("/\b($word)\b/i"'<span class="highlight_word">\1</span>'$text);
        }
        
/*** return the text ***/
        
return $text;
}


/*** example usage ***/
$string 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
/*** an array of words to highlight ***/
$words = array('php''sql');
/*** highlight the words ***/
$string =  highlightWords($string$words);

?>

<html>
<head>
<title>PHPRO Highlight Search Words</title>
<style type="text/css">
.highlight_word{
        background-color: pink;
}
</style>
</head>
<body>
 <?php echo $string?>
</body>
</html>

50+ PHP optimisation tips

  1.  echo is faster than print
  2. Wrap your string in single quotes (‘) instead of double quotes (“) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string. 
  3. Use sprintf instead of variables contained in double quotes, it’s about 10x faster. 
  4. Use echo’s multiple parameters (or stacked) instead of string concatenation. 
  5. Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.
  6. Unset or null your variables to free memory, especially large arrays.
  7. Avoid magic like __get, __set, __autoload. 
  8. Use require() instead of require_once() where possible. 
  9. Use full paths in includes and requires, less time spent on resolving the OS paths. 
  10. require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference. 
  11. Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime(). 
  12. PCRE regex is quicker than EREG, but always see if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead. [Citation]
  13. When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4. 
  14. str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace. 
  15. “else if” statements are faster than select statements aka case/switch.
  16. Error suppression with @ is very slow.
  17. To reduce bandwidth usage turn on mod_deflate in Apache v2  or for Apache v1 try mod_gzip. 
  18. Close your database connections when you’re done with them. 
  19. $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.
  20. Use tags when declaring PHP as all other styles are depreciated, including short tags. 
  21. Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.
  22. PHP scripts are be served at 2-10 times slower by Apache httpd than a static page. Try to use static pages instead of server side scripts.
  23. PHP scripts (unless cached) are compiled on the fly every time you call them. Install a PHP caching product (such as memcached or eAccelerator or Turck MMCache) to typically increase performance by 25-100% by removing compile times. You can even setup eAccelerator on cPanel using EasyApache3
  24. An alternative caching technique when you have pages that don’t change too frequently is to cache the HTML output of your PHP pages. Try Smarty or Cache Lite
  25. Use isset where possible in replace of strlen. (ie: if (strlen($foo) < 5) { echo “Foo is too short”; } vs. if (!isset($foo{5})) { echo “Foo is too short”; } ). 
  26. ++$i is faster than $ i++, so use pre-increment where possible.
  27. Make use of the countless predefined functions of PHP, don’t attempt to build your own as the native ones will be far quicker; if you have very time and resource consuming functions, consider writing them as C extensions or modules. 
  28. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview. 
  29. Document your code. 
  30. Learn the difference between good and bad code. 
  31. Stick to coding standards, it will make it easier for you to understand other people’s code and other people will be able to understand yours. 
  32. Separate code, content and presentation: keep your PHP code separate from your HTML. 
  33. Don’t bother using complex template systems such as Smarty, use the one that’s included in PHP already, see ob_get_contents and extract, and simply pull the data from your database. 
  34. Never trust variables coming from user land (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML.
  35. For security reasons never have anything that could expose information about paths, extensions and configuration, such as display_errors or phpinfo() in your webroot.
  36. Turn off register_globals (it’s disabled by default for a reason!). No script at production level should need this enabled as it is a security risk. Fix any scripts that require it on, and fix any scripts that require it off using unregister_globals(). Do this now, as it’s set to be removed in PHP6. 
  37. Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5 hash.
  38. Use ip2long() and long2ip() to store IP addresses as integers instead of strings.
  39. You can avoid reinventing the wheel by using the PEAR project, giving you existing code of a high standard. 
  40. When using header(‘Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible. 
  41. In OOP, if a method can be a static method, declare it static. Speed improvement is by a factor of 4. 
  42. Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable. 
  43. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. 
  44. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. 
  45. Just declaring a global variable without using it in a function slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists. 
  46. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance. 
  47. Methods in derived classes run faster than ones defined in the base class. 
  48. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
  49. Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory.
  50. Never trust user data, escape your strings that you use in SQL queries using mysql_real_escape_string, instead of mysql_escape_string or addslashes. Also note that if magic_quotes_gpc is enabled you should use stripslashes first.
  51. Avoid the PHP mail() function header injection issue.
  52. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
  53. RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English. Please USE IT!

Avoid doing SQL queries within a loop:


If we writing a sql queries inside the Loop, it results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once. Below is the example to create sql query in loop:

$Data = array();
foreach ($resultSet as $result) {
    $Data[] = '("' . $result['first_name'] . '", "' . $result['last_name'] . '")';
 }
$query = 'INSERT INTO table_name (first_name,last_name) VALUES' . implode(',', $Data);
mysql_query($query);


Here’s a short list of cool features that might have slipped under your radar as well:
  1. Use ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage space by almost a factor of four (15 bytes for char(15) vs. 4 bytes for the integer), make it easier to calculate whether a certain address falls within a range, and speed-up searches and sorts (sometimes by quite a bit).
  2. Partially validate email addresses by checking that the domain name exists with checkdnsrr(). This built-in function checks to ensure that a specified domain name resolves to an IP address. A simple user-defined function that builds on checkdnsrr() to partially valid email addresses can be found in the user comments section in the PHP docs. This is handy for catching those occasional folks who think their email address is ‘joeuser@wwwphp.net’ instead of ‘joeuser@php.net’.
  3. If you’re using PHP 5 with MySQL 4.1 or above, consider ditching the mysql_* functions for the improved mysqli_* functions. One nice feature is that you can use prepared statements, which may speed up queries if you maintain a database-intensive website. Some benchmarks.
  4. Learn to love the ternary operator.
  5. If you get the feeling that you might be reinventing the wheel during a project, check PEAR before you write another line. PEAR is a great resource that many PHP developers are aware of, yet many more are not. It’s an online repository containing over 400 reusable snippets that can be dropped right into your PHP application. Unless your project is trully unique, you ought to be able to find a PEAR package that saves at least a little time. (Also see PECL)
  6. Automatically print a nicely formatted copy of a page’s source code with highlight_file().This function is handy for when you need to ask for some assistance with a script in a messageboard, IRC, etc. Obviously, some care must be taken not to accidently show your source when it contains DB connection information, passwords, etc.
  7. Prevent potentially sensitive error messages from being shown to users with the error_reporting(0) function. Ideally error reporting should be completely disabled on a production server from within php.ini. However if you’re on a shared webhost and you aren’t given your own php.ini, then your best bet is to add error_reporting(0); as the first line in each of your scripts (or use it with require_once().) This will prevent potentially sensitive SQL queries and path names from being displayed if things go awry.
  8. Use gzcompress() and gzuncompress() to transparently compress/decompress large strings before storing them in a database. These built-in functions use the gzip algorithm and can compress plaintext up to 90%. I use these functions almost everytime I read/write to a BLOB field within PHP. The only exception is when I need full text indexing capabilities.
  9. Return multiple values from a function with “by reference” parameters. Like the ternary operator, most PHP developers who come from a more formalized programming background already know this one. However, those who’s background is more HTML than Pascal, probably have wondered at one time “how do I get multiple values back from a function I wrote, even though I can only use one return value?” The answer is that you precede a variable with “&” and use it “by reference” instead of “by value”.
  10. Fully understand “magic quotes” and the dangers of SQL injection. I’m hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it’s absolutely critical to understand. If you’ve never heard the term before, spend the entire rest of the day googling and reading.

Embedding PHP In CSS

Perhaps one of the most frustrating aspects of using PHP with websites, is getting variables into CSS. Having variables stored in an ini file, config file or even a database can make the updating of the look and feel of a site simple, however, CSS files, by default, do not parse PHP. Of course, the web server could be told to parse CSS as PHP in the same way it does for HTML.
AddType application/x-httpd-php .css
With the addition of the above line in httpd.conf or in a .htaccess, the web server will now parse PHP code that is within the CSS files. This is one solution, but a better method may be at hand.
A html file may also include a PHP file, in the same manner as it includes a CSS file. This means the stylesheet can be renamed from style.css to style.php. When included from within the head of the HTML document, the link will look like this.
<link rel="stylesheet" href="style.php" media="screen">
With the link to the style.php file in place, the PHP within the stylesheet is just a normal PHP file.

<?php
/*** set the content type header ***/
header("Content-type: text/css");

/** set the paragraph color ***/
$para_color '#0000ff';

/*** set the heading size ***/
$heading_size '2em';

/*** set the heading color ***/
$heading_color '#c0c0c0';
?>

p{
        color: <?php echo $para_color;  ?>;
        font-weight: bold;
        font-size: 1.2em;
        text-align: left;
}     

h1{
        color: <?php echo $heading_color?>;
        font-size = <?php echo $heading_size?>;
        text-align: centre;
}

The PHP code within the style sheet is embedded just as it would be when using HTML and PHP together in a any php file. Each of the variables are declared at the top of the script, and the values then used where appropriate. Of course, the variables could be stored in a config file or database to make changes to the styles easy from remote locations.
The code above will produce a Cascading Style Sheet as follows:
p{
color: #0000ff;
font-weight: bold;
font-size: 1.2em;
text-align: left;
}

h1{
color: #c0c0c0;
font-size = 2em;
text-align: centre;
}
An addition to CSS is pending that will permit the use of CSS variables, however, this does not exclude the of PHP to get a variable into the CSS file itself. The proposed CSS variables would look like this, and allow the defining of a variable in a @variable at-rule and then be able to use that variable through-out the style sheet.

<html>
<head>
<title>foo</title>
<style type="text/css">
@variables {
  LogoBGColor: #e0e0e0;
}

div.logoContainer {
  background-color: var(LogoBGColor);
  color: red;
}

</style>
</head>

<body>
<h1 class="heading">CSS Variables</h1>
<div class="logoContainer">
This is some Text
</div>
</body>
</html>

Wednesday, June 16, 2010

Run Script From Cron

The cron man page defines cron as a "daemon to execute scheduled commands". This means you can run scripts every hour, or every day, or on the 13 of every month at 5:38am. Here is an example of a cron entry.
00 18 * * * /path/to/command
In a few short minutes you will understand what this command means.

Structure

The structure of a cron entry as seen above is quite simple when broken down. In the above entry there is five sections and a path to a PHP script. Here is how it breaks down
Minute Hour Day Month Day Command
Lets break it down further..
Minute
Minute of the hour, 00 to 59
Hour
Hour of the day in 24-hour format, 00 to 23
Day
Day of the month, 1 to 31
Month
Month of the year, 1 to 12
DayDay of week
3 chars - sun, mon, tue, or numeric (0=sun, 1=mon etc)
Command = The command you want to execute
The time is in twenty four hour time. So you may have guessed already that the 00 is the minutes and the 18 above is 6:00pm. The asterix character * is a wild card and means every. That is, every minute or every day, or every month. This means the script.php script would be executed every day of every month.
00 18 * * * /path/to/script.php

Crontab

The crontab is the command used to interface with cron. Within crontab command can be entered, editted or deleted. To enter into the crontab simply type:
crontab -e
This command will bring you to a vi console where you can create your cron entries. All the same rules that apply to vi apply in the editor. It is important to follow the examples here by using absolute paths to the script that is to be executed. This is because crontab does not have access to the system $PATH, so any system command also need have thier full path also. The path to a system command can be aquired using the which command. The $PATH is not available within cron, however, the $HOME variable is, so that when we need to execute a command or script from our home directory, this is available to us.
#which
mail /bin/mail

Set Crontab Editor

It is hard to imagine, yet there are still people out there who do not use vi(m). On most unix and unix like systems vi(m) is the default editor for crontab. This means when you type "crontab -e" at the command prompt, the crontab file is opened in vi(m). To alter this behaviour, the default editor can be changed or exported with the export command. Shown here is an example of changing the default crontab editor to joe.
export EDITOR=joe

Examples

We saw above how a script could be run at 6:00pm every night. But what is a script needs to be executed every 5 minutes. We could do something like this.
0 ,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/command
This example shows how the time increments are seperated by a space, but we can have multiple values seperated by comma's. Of course, this is a lot to type out, so cron has a little shortcut syntax to achieve the same result.
*/5 * * * * /path/to/command
The previous examples show how to run every day or every whatever. But what if we wish to run a PHP script at 4:00am each Friday just before we go home.
00 16 * * fri /usr/local/bin/php $HOME/script.php
The above cron entry will shows 4:00pm every Friday (fri) and will execute the command /usr/local/bin/php $HOME/script.php. Note the use of the $HOME variable to show that the script.php file to be executed is within the users home directory. The path to the php executable however, must be an absolute path. There is more to cron than these simple demonstrations have shown. It is hoped that this is enough to get you up and scheduling tasks with the cron and the crontab. Just remember the sequence of times - Minute Hour Day Month Day Command

Backup MySQL Database With Cron

Database backup are a frequently performed task, usually a webmaster will begin this process after losing their data and realise that this needs to be done on a regular basis. This is an ideal situation where cron can be used. Database backups should be stored by date. That is, the filename of the SQL dump should be .todays_date.sql so a backup can be made from a given time and/or date. to achieve this, enter the following command in crontab
0 2 * * * /usr/local/bin/mysqldump -db_user -db_password db_name > /home/www/backups/dbname-`date +\%s`.sql

Monday, June 14, 2010

Drupal6 Updates

Here is the Drupal6 features from Changelog.txt

- New, faster and better menu system.
- New watchdog as a hook functionality.
* New hook_watchdog that can be implemented by any module to route log
messages to various destinations.
* Expands the severity levels from 3 (Error, Warning, Notice) to the 8
levels defined in RFC 3164.
* The watchdog module is now called dblog, and is optional, but enabled by
default in the default install profile.
* Extended the database log module so log messages can be filtered.
* Added syslog module: useful for monitoring large Drupal installations.
- Added optional e-mail notifications when users are approved, blocked, or
deleted.
- Drupal works with error reporting set to E_ALL.
- Added scripts/drupal.sh to execute Drupal code from the command line. Useful
to use Drupal as a framework to build command-line tools.
- Made signature support optional and made it possible to theme signatures.
- Made it possible to filter the URL aliases on the URL alias administration
screen.
- Language system improvements:
* Support for right to left languages.
* Language detection based on parts of the URL.
* Browser based language detection.
* Made it possible to specify a node's language.
* Support for translating posts on the site to different languages.
* Language dependent path aliases.
* Automatically import translations when adding a new language.
* JavaScript interface translation.
* Automatically import a module's translation upon enabling that module.
- Moved "PHP input filter" to a standalone module so it can be deleted for
security reasons.
- Usability:
* Improved handling of teasers in posts.
* Added sticky table headers.
* Check for clean URL support automatically with JavaScript.
* Removed default/settings.php. Instead the installer will create it from
default.settings.php.
* Made it possible to configure your own date formats.
* Remember anonymous comment posters.
* Only allow modules and themes to be enabled that have explicitly been
ported to the correct core API version.
* Can now specify the minimum PHP version required for a module within the
.info file.
* Drupal core no longer requires CREATE TEMPORARY TABLES or LOCK TABLES
database rights.
* Dynamically check password strength and confirmation.
* Refactored poll administration.
* Implemented drag-and-drop positioning for blocks, menu items, taxonomy
vocabularies and terms, forums, profile fields, and input format filters.
- Theme system:
* Added .info files to themes and made it easier to specify regions and
features.
* Added theme registry: modules can directly provide .tpl.php files for
their themes without having to create theme_ functions.
* Used the Garland theme for the installation and maintenance pages.
* Added theme preprocess functions for themes that are templates.
* Added support for themeable functions in JavaScript.
- Refactored update.php to a generic batch API to be able to run time-consuming
operations in multiple subsequent HTTP requests.
- Installer:
* Themed the installer with the Garland theme.
* Added form to provide initial site information during installation.
* Added ability to provide extra installation steps programmatically.
* Made it possible to import interface translations at install time.
- Added the HTML corrector filter:
* Fixes faulty and chopped off HTML in postings.
* Tags are now automatically closed at the end of the teaser.
- Performance:
* Made it easier to conditionally load .include files and split up many core
modules.
* Added a JavaScript aggregator.
* Added block-level caching, improving performance for both authenticated
and anonymous users.
* Made Drupal work correctly when running behind a reverse proxy like
Squid or Pound.
- File handling improvements:
* Entries in the files table are now keyed to a user instead of a node.
* Added reusable validation functions to check for uploaded file sizes,
extensions, and image resolution.
* Added ability to create and remove temporary files during a cron job.
- Forum improvements:
* Any node type may now be posted in a forum.
- Taxonomy improvements:
* Descriptions for terms are now shown on taxonomy/term pages as well
as RSS feeds.
* Added versioning support to categories by associating them with node
revisions.
- Added support for OpenID.
- Added support for triggering configurable actions.
- Added the Update status module to automatically check for available updates
and warn sites if they are missing security updates or newer versions.
Sites deploying from CVS should use http://drupal.org/project/cvs_deploy.
Advanced settings provided by http://drupal.org/project/update_advanced.
- Upgraded the core JavaScript library to jQuery version 1.2.3.
- Added a new Schema API, which provides built-in support for core and
contributed modules to work with databases other than MySQL.
- Removed drupal.module. The functionality lives on as the Site network
contributed module (http://drupal.org/project/site_network).
- Removed old system updates. Updates from Drupal versions prior to 5.x will
require upgrading to 5.x before upgrading to 6.x.

- Better performance because of better caching and the ability to split modules in separate files to reduce memory on runtime
- Improved menu and forms API
- Built-in module update tracker

-------------------------------------------------------------------
HOOKS
Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is named foo_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook. Each hook has a defined set of parameters and a specified result type.

To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and call that hook in all enabled modules that implement it.

Friday, June 11, 2010

Magic Methods in PHP

With PHP 5 Object Oriented Programming seems to becoming a reality in PHP but we all know that in PHP a variable can take any form depending on the data passed to it. Also PHP automatically creates variable and assigns values to it even is the variables are not defined. But in Object Oriented Programming all the data members/methods needs to be defined. To solve some of these problems in OOPS environment magic methods have been introduced in PHP5.

NOTE ON MAGIC METHODS:
  • Magic methods are the members functions that is available to all the instance of class
  • Magic methods always starts with “__”. Eg. __construct
  • All magic methods needs to be declared as public
  • To use magic method they should be defined within the class or program scope
Various Magic Methods used in PHP 5 are:
  • __construct()
  • __destruct()
  • __set()
  • __get()
  • __call()
  • __toString()
  • __sleep()
  • __wakeup()
  • __isset()
  • __unset()
  • __autoload()
  • __clone()


__construct()
Constructor are special function in Object Oriented Programming. It gets called automatically whenever object of a class is created. This is useful for performing any pre operation before we start to call the methods of the class. PHP5 uses special keyword “__construct” to define constructor of the class.

< ?
class employee
{
    function __construct()
   {
       echo "Constructor Called";
   } 
}
$a = new employee();
$a = new employee;
? >


__destruct()
Destructor are special function in Object Oriented Programming. It gets called automatically whenever object of a class is destroyed or goes out of scope. This is useful for clean up operation before cleaning the memory. PHP 5 uses special keyword “__destruct” to define destructor of the class.

< ?
class employee
{
    function __destruct()
    {
        echo "Destructor Called";
    }
}
$a = new employee();
? >
 
 So when the page operation is completed destructor function is called automatically.
__set()
This tutorial will guide you through the __set() Magic Method. The __set() Magic method in PHP5 gets called when setting the value to an undeclared or undefined attributes of an class. With this method the programmer can keep track on the variables which are not defined inside the class.

< ?
class magicmethod
{
 function __set($data,$value)
 {
  echo "Error assigning values to undefined attributes";
  echo "attributes Called:".$data;
  echo "Value assigned to attributes:".$value;
 }
 
}
$a = new magicmethod();
$a->setData = 20;
? >
 
Output:

Error assigning values to undefined attributes

attributes Called:setData

Value assigned to attributes:20 

__get()
This tutorial will guide you through the __get() Magic Method. The __get Magic method in PHP5 gets called when accessing the value of an undeclared or undefined attribute of an class. With this method the programmer can keep track on the variables which are not defined inside the class.

< ?
class magicmethod
{
   function __get($data)
   {
       echo "Error accessing undefined attributes";
       echo "attributes Called:".$data;
   }
}
 
$a = new magicmethod();
echo $a->setData;
 
? >
 
Output:

Error accessing undefined attributes

attributes Called:setData 

__call()
This tutorial will guide you through the __call() Magic Method. The __call Magic method in PHP5 get called when accessing an undeclared or undefined methods of an class. With this magic method the programmer can keep track on the undeclared method which are not defined inside the class.

< ?
class magicmethod
{
 
 function __call($data,$argument)
 {
  echo "Error accessing undefined Method";
  echo "Method Called: ".$data;
  echo "Argument passed to the Method: ".$argument;
 }
 
}
 
$a = new magicmethod();
echo $a->setData();  //Calling setData method
 
? >
 
Output:

Error accessing undefined Method

Method Called: setData

Argument passed to the Method: Array (Array of the Argument Passed) 

__toString()
This tutorial will guide you through the __toString() Magic Method. The __toString() Magic method in PHP5 get called while trying to print or echo the class objects. This method can be used print all the methods and attributes defined for the class at runtime for debugging. Also this method can be used to give error message while somebody tries to print the class details.

< ?
class magicmethod
{
 
 function __toString()
 {
  return "Caught You!! Cannot access the Class Object";
 }
 
}
$a = new magicmethod();
echo $a;
? >

Output: Caught You!! Cannot access the Class Object

__sleep()
This tutorial will guide you through the __sleep() Magic Method. The __sleep() magic method in PHP5 gets called while serializing an object in PHP5. Serializing is required to pass complex data across the network or PHP pages. It is also used to store data(files, database, cookies etc). With this magic method call we can define the way how the data object will be stored. The __sleep() method should be used along with __wakeup() magic method. The __wakeup() magic method is called while unserializing the data and restores the serialized object to normal form.

< ?
class magicmethod
{
 function __sleep()
 {
  echo "Performing Clean-Up Operation Before Serializing Data ";
  return array("Serialized Data","1","2","3");
 }
}
$a = new magicmethod();
$serializedata = serialize($a);
echo $serializedata;
? >

Output:
Performing Clean-Up Operation Before Serializing Data
O:11:”magicmethod”:4:{s:15:”Serialized Data”;N;s:1:”1″;N;s:1:”2″;N;s:1:”3″;N;}

__wakeup()
This tutorial will guide you through the __wakeup() Magic Method. The __wakeup() magic method of PHP5 gets called when unserialize operation on object is performed. This method allows us to restore the serialized data to its normal form.

< ?
class magicmethod
{
 private $setName;
 function __sleep()
 {
  echo "Performing Clean-Up Operation Before Serializing Data ";
  $this->setName = "Hello World!!!";
  return array(setName);
 }
 
 function __wakeup()
 {
  echo "Performing Clean-Up Operation Before Unserializing Data ";
  echo $this->setName;
 }
}
$a = new magicmethod();
$serializedata = serialize($a);
$serializedata1 = unserialize($serializedata);
? >
 
 Output:
Performing Clean-Up Operation Before Serializing Data
Performing Clean-Up Operation Before Unserializing Data
Hello World!!!

__isset()
This tutorial will guide you through the __isset() Magic Method. The __isset() magic method in PHP5 is called whenever isset function of PHP is called to check for undeclared data member. With the help of this method we can check for the undeclared variables in the code. We can also set appropriate error message while testing for variable names getting used in the Class.

< ?
class magicmethod
{
 function __isset($variablename)
 {
  echo "Variable '".$variablename."' not Set";
 }
}
$a = new magicmethod();
isset($a->name);
? >

Output: Variable ‘name’ not Set

__unset()
This tutorial will guide you through the __unset() Magic Method. The __unset() magic method of PHP5 is called whenever unset function of PHP is called to clear an undeclared data member. With the help of this method we can check for the undeclared variables in the code. We can also set appropriate error message while testing for variable names getting used in the Class.


< ?
class magicmethod
{
 function __unset($variablename)
 {
  echo "Variable '".$variablename."' not Set and Cannot be UnSet";
 }
}
$a = new magicmethod();
unset($a->name);
? >



Output: Variable ‘name’ not Set and Cannot be UnSet



__autoload()
This methods get automatically called whenever you try to load an object of class which resides in separate file and you have not included those files using include,require and include_once. To use this method it is mandatory to the PHP filename as that of the class name because this methods accepts the class name as the argument. To know more about this method refer

Example – Basic AutoLoad Magic Method Usage

< ?
    function __autoload($classname)
    {
        include $classname.".php"; //Here $classname=magicmethod1
    }
 
    $a = new magicmethod1();
? >

Explanation for the Example:
Here i am trying to create an object of magicmethod1 class, but i have not included the magicmethod1.php so PHP compiler calls the __autoload() method which include that magicmethod1.php file.
Code for magicmethod1.php

< ?
    class magicmethod1
    {
        function __construct()
        {
            echo "MagicMethod1 Class Called";
        }
    }
? >

Output: MagicMethod1 Class Called
 



__clone()
In PHP 5 when you assign one object to another object creates a reference copy and does not create duplicate copy. This would create a big mess as all the object will share the same memory defined for the object. To counter this PHP 5 has introduced clone method which creates an duplicate copy of the object. __clone magic method automatically get called whenever you call clone methods in PHP 5.

< ?
class Animal
{
   public $name ;
   public $legs;
 
   function setName($name)
   {
 $this->name = $name;
   }
 
   function setLegs($legs)
   {
 $this->legs = $legs;
   }
 
   function __clone()
   {
 echo "
Object Cloning in Progress";
   }
}
 
$tiger = new Animal();
$tiger->name = "Tiger";
$tiger->legs = 4;
 
$kangaroo = clone $tiger;
$kangaroo->name = "Kangaroo";
$kangaroo->legs = 2;
 
echo "
".$tiger->name."---".$tiger->legs;
echo "
".$kangaroo->name."---".$kangaroo->legs;
? >
Output:
Object Cloning in Progress
Tiger—4
Kangaroo—2

Tuesday, June 8, 2010

What is .htaccess Files

.htaccess files (or “distributed configuration files”) provide a way to make
configuration changes on a per-directory basis. A file, containing one or more
configuration directives, is placed in a particular document directory, and the
directives apply to that directory, and all subdirectories thereof.


Directives

“Directives” is the terminology that Apache uses for the commands in Apache’s
configuration files. They are normally relatively short commands, typically
key value pairs, that modify Apache’s behavior. An .htaccess file allows
developers to execute a bunch of these directives without requiring access to
Apache’s core server configuration file, often named httpd.conf.
This file,
httpd.conf, is typically referred to as the “global configuration file” and I will
refer to it with that name or its short filename equivalent.
This feature is ideal for many hosting companies deploying a shared hosting
environment. The hosting company will not allow its customers to access the
global configuration file, which ultimately affects all of the customers hosted on
that server. Instead, by enabling .htaccess, they give each of their customers
the power to specify and execute their own Apache directives in their own
directories and subdirectories. Of course it’s also useful to the single
developer, as you will see.
It’s worth mentioning that anything that can be done with a .htaccess file can
be done in the httpd.conf file. However, NOT everything that can be done in
httpd.conf can be done in a .htaccess file. In fact .htaccess files must be
enabled in the httpd.conf file in order to be executed at all. Once enabled,
their power can be limited to certain “contexts” so that they may be allowed
to override some settings but not others. This gives the system administrators
more control over what they let other developers get away with in their
.htaccess files.

for more Information about htaccess Click here

Monday, June 7, 2010

Facebook: CSS Background images won't show up on fbml canvas page

In many of Facebook Applications CSS background images are not showing some time or the background images have shrunk and are tiled 4 times over. And If I copy the image path, and paste it in another tab and do a fetch in the browser, and again go back to my app canvas page and refresh it, the image shows up, but never does it show on the first load.

If anybody having same problem then just upload these images in another domain and give it that path into FBML Application or You can use photobucket.com or imageshack for example.

Im my case i uploaded my images in photobucket and i gave the absolute path in my CSS.

Thursday, June 3, 2010

Output Buffering

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

Advantages of output buffering for Web developers

* Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
* All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
* If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.

Here's a "hello world" of PHP output buffering

<?php
// start output buffering at the top of our script with this simple command
ob_start();
?>

<html>
<body>
<p>Hello world!</p>
</body>
</html>

<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>

It's that simple! Just by doing this our webpages appear less choppy as they render. Now let's take it one step futher.

The next step: compress the output

In the code below, ob_start() is changed to ob_start('ob_gzhandler'). That one simple change compresses our HTML, resulting in a smaller HTML download size for most browsers.

<?php
// start output buffering at the top of our script with this simple command
// we've added "ob_gzhandler" as a parameter of ob_start
ob_start('ob_gzhandler');
?>

<html>
<body>
<p>Hello world!</p>
</body>
</html>

<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>

one more step further: custom post processing

In the code below, ob_start() is changed to ob_start('ob_postprocess'). ob_postprocess() is a function we define below used to make changes to the HTML before it is sent to the browser. Instead of Hello world!, the user will see Aloha world!

<?php
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
ob_start('ob_postprocess');
?>

<html>
<body>
<p>Hello world!</p>
</body>
</html>

<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();

// ob_postprocess is our custom post processing function
function ob_postprocess($buffer)
{
 // do a fun quick change to our HTML before it is sent to the browser
 $buffer = str_replace('Hello', 'Aloha', $buffer);
 // "return $buffer;" will send what is in $buffer to the browser, which includes our changes
 return $buffer;
}
?>

you can set cookies at any time with output buffering on

Since HTML is not sent directly to the browser, we can set cookies anywhere in our scripts without worrying about anything. Just turn it on like we did in step 1 and voilĂ ! No more cookie problems.

Word Jumbling

According to a researcher at Cambridge University, it doesn’t matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole.

Here is the little JavaScript ‘program’ to do word jumbling written by James Padolsey.

The first component is a function which jumbles a string’s characters:

function jumble(word) {

// Rand function will return 2-part array
// [0] -> Index of rand, [1] -> random found value (from args)
var rand = function(){
var myRand = Math.floor(Math.random() * arguments.length);
return [myRand, arguments[myRand]];
},

// Split passed word into array
word = word.split(''),

// Cache word length for easy looping
length = word.length,

// Prepate empty string for jumbled word
jumbled = '',

// Get array full of all available indexes:
// (Reverse while loops are quickest: http://reque.st/1382)
arrIndexes = [];
while (length--) {
arrIndexes.push(length);
}

// Cache word length again:
length = word.length;

// Another loop
while (length--) {
// Get a random number, must be one of
// those found in arrIndexes
var rnd = rand.apply(null,arrIndexes);
// Append random character to jumbled
jumbled += word[rnd[1]];
// Remove character from arrIndexes
// so that it is not selected again:
arrIndexes.splice(rnd[0],1);
}

// Return the jumbled word
return jumbled;

}

The second component get’s the value of the textarea on each keyup event and jumbles all characters between the first and last letter of each word: (It also has a primitive way of handling simple punctuation)


$('textarea').keyup(function(){
var text = $(this).val().split(/\s/g),
converted = '';

$.each(text, function(i,word){
if(!word.length) return;

// Extract punctuation:
var puncPattern = /[,\.;:'!\?]+/,
punc = word.match(puncPattern) ? word.match(puncPattern)[0] : '',
puncIndex = word.search(puncPattern),
word = word.replace(punc,'');

// Compile new word, split to array:
var newWord =
(word.length > 2 ?
word.substr(0,1) + jumble(word.substr(1,word.length-2))
+ word.substr(word.length-1)
: word).split('');

// Insert punctuation back in:
newWord.splice(puncIndex,0,punc);

// Add space after word:
converted += newWord.join('') + '\u0020';

});

// Inserted jumbled test into receiver:
$('#receiver').text(converted);
});


You can see a demo of the above script here.