Archive for May 2013

Control structure in Php: declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
statement


The directive section allows the behavior of the declare block to be set. Currently only one directive is recognized: the ticks directive.
The statement part of the declare block will be executed -- how it is executed and what side effects occur during execution may depend on the directive set in the directive block.
The declare construct can also be used in the global scope, affecting all code following it.

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
// entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>


Ticks

A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.
The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Example: Profile a section of PHP code

<?php
// A function that records the time when it is called
function profile($dump = FALSE)
{
static $profile;

// Return the times stored in profile, then erase it
if ($dump) {
$temp = $profile;
unset($profile);
return $temp;
}

$profile[] = microtime();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
for ($x = 1; $x < 50; ++$x) {
echo similar_text(md5($x), md5($x*$x)), "<br />;";
}
}

// Display the data stored in the profiler
print_r(profile(TRUE));
?>


The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed. This information can then be used to find the slow areas within particular segments of code. This process can be performed using other methods: using ticks is more convenient and easier to implement.
Ticks are well suited for debugging, implementing simple multitasking, background I/O and many other tasks.

Add last class to the wordpress menu items (nested list)

Some times you have to add "last" class for support old browsers and css. Add this snippet to your theme's function.php file and its done.


/**
 * Add classes to the menu items
 * http://php-everyday.blogspot.com
 */
function add_last_item_class($menuHTML) {
  $last_items_ids  = array();

  // Get all custom menus
  $menus = wp_get_nav_menus();

  // For each menu find last items
  foreach ( $menus as $menu_maybe ) {

    // Get items of specific menu
    if ( $menu_items = wp_get_nav_menu_items($menu_maybe->term_id) ) {

      $items = array();
      foreach ( $menu_items as $menu_item ) {
        $items[$menu_item->menu_item_parent][] .= $menu_item->ID;
      }

      // Find IDs of last items
      foreach ( $items as $item ) {
        $last_items_ids[] .= end($item);
      }
   }
}

  foreach( $last_items_ids as $last_item_id ) {
    $items_add_class[] .= ' menu-item-'.$last_item_id;
    $replacement[]     .= ' menu-item-'.$last_item_id . ' last';
  }

  $menuHTML = str_replace($items_add_class, $replacement, $menuHTML);
  return $menuHTML;

}
add_filter('wp_nav_menu','add_last_item_class');

Control structures in Php: include()

The include() statement includes and evaluates the specified file.
The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in included file doesn't cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.
Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in the current working directory.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Example: Basic include() example

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>


If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Example: Including within functions

<?php

function foo()
{
global $color;

include 'vars.php';

echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so *
* $fruit is NOT available outside of this *
* scope. $color is because we declared it *
* as global. */

foo(); // A green apple
echo "A $color $fruit"; // A green

?>


When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.
If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper, instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Warning:

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

Example: include() through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'file.txt'; // Works.
include 'file.php'; // Works.

?>


Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.
Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.
Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Example: Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
echo 'OK';
}
?>


Note: In PHP 3, the return may not appear inside a block unless it's a function block, in which case the return() applies to that function and not the whole file.

Example: include() and the return() statement

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>


$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.
If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.
Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:

Example: Using output buffering to include a PHP file into a string

<?php
$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}

?>


In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Note: Because this is a language construct and not a function, it cannot be called using variable functions

htacess configuration

IfModule mod_php5.c
php_value display_errors on
php_value error_reporting 6135
php_flag magic_quotes_gpc On

php_value post_max_size 50M
php_value upload_max_filesize 20M
php_value memory_limit 50M
IfModule

Options -Indexes
DirectoryIndex index.php

IfModule mod_rewrite.c
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule index.html$ index.php

RewriteRule ^en/langsession.html langsession.php?lang=en [L]
RewriteRule ^it/langsession.html langsession.php?lang=it [L]

# rewite rule for top search result

RewriteRule luxury-hotels.html$ index.php?dir=view&page=search_result&type=1
RewriteRule boutique-hotels.html$ index.php?dir=view&page=search_result&type=2
RewriteRule hotel-spa.html$ index.php?dir=view&page=search_result&type=3
RewriteRule hotel-golf.html$ index.php?dir=view&page=search_result&type=4
RewriteRule design-hotel.html$ index.php?dir=view&page=search_result&type=5

# End of top rewite rule

RewriteRule location-(.*).html$ index.php?dir=view&page=search_result&mode=top&locationid=$1
RewriteRule region-(.*).html$ index.php?dir=view&page=search_result&mode=top&stateid=$1

## rule for the result and hotel details page
RewriteRule hotels-(.*)\.html$ index.php?dir=view&page=hotels&city=$1
RewriteRule details-(.*)-(.*)\.html$ index.php?dir=view&page=hotel-details&hid=$2

#End of rule

RewriteRule result.html$ index.php?dir=view&page=search_result
RewriteRule hotels.html$ index.php?dir=view&page=search_result
RewriteRule site-map.html$ index.php?dir=view&page=site_map

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)\.html$ index.php?dir=view&page=display&url=$1

IfModule

OWASP, the Open Web Application Security Project

OWASP, the Open Web Application Security Project, is famous for its Top Ten list of security vulnerabilities. David ported the list to PHP (PHP and the OWASP Top Ten), and now OWASP has released its own PHP-specific list, the PHP Top 5:
The PHP Top 5 is based upon attack frequency in 2005 as reported to Bugtraq. This information is a valuable insight into the most devastating attacks against the world's most popular web application framework.In 2005, OWASP collaborated with SANS to research and write a completely new PHP section to their successful Top 20 2005. The OWASP PHP Top 5 is the full unabridged text, updated to reflect recent XSS attacks and SQL injection vectors.

SQL- distinct

select distinct city, college_name from students

> so the combination of city and college should be distinct we can not have it like

select city, distinct college_name from students

but we can have it with an aggregate e.g. for each city give me the count of distinct colleges :) eh!

select city, count(distinct college_name) from students

Force propel to use utf-8 connection

If you having problems with utf-8 you should check runtime-conf.xml file for settings. You should add set names decleration.

<connection>
<dsn>mysql:host=localhost;dbname=cms</dsn>
<user>root</user>
<password>1234</password>
<settings>
<setting id="charset">utf8</setting>
</settings>
<options>
<option id="MYSQL_ATTR_INIT_COMMAND">SET NAMES utf8 COLLATE utf8_unicode_ci</option>
</options>
</connection>

End regenerate php configration file
propel-gen convert-conf

Control structures in Php: include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
For more examples on using require_once() and include_once(), look at the » PEAR code included in the latest PHP source code distributions.
Return values are the same as with include(). If the file was already included, this function returns TRUE

Note: include_once() was added in PHP 4.0.1

Note: Be aware, that the behaviour of include_once() and require_once() may not be what you expect on a non case sensitive operating system (such as Windows).

Example: include_once() is case insensitive on Windows

<?php
include_once "a.php"; // this will include a.php
include_once "A.php"; // this will include a.php again on Windows! (PHP 4 only)
?>


This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.

Warning:

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

What is the PHP in History !


PHP is a general-purpose server-side scripting language orginally designed for Web development Program. To create dynamic webpages. It is one of the first developed server side scripting languages. PHP is using on more than 20 million websites and 1 million web servers. PHP was originally created by Rasmus Lerdorf in 1995. While PHP originally stood for "Personal Home Page", it is now said to stand for "PHP: Hypertext Preprocessor", a recursive acronym.


History:-
PHP development begain in 1994 when the persons Danish / Greenlandic / Canadian programmer Rasmus Lerdorf initially created a set of Perl scripts he called "Personal Home Page Tools" to maintain his personal homepage. The scripts performed tasks such as displaying his résumé and recording his web-page traffic. Lerdorf initially announced the release of PHP on the comp.infosystems.www.authoring.cgi Usenet discussion group on June 8, 1995.
Zeev Suraski and Andi Gutmans, two Israeli developers at the Technion IIT, re-wrote the parser in 1997 and formed the base of PHP 3, changing the language's name to the recursive initialism PHP: Hypertext Preprocessor.

Afterwards, public testing of PHP 3 begain, and the official launch came in June 1998. Suraski and Gutmans then started a new rewrite of PHP's core, producing the Zend Engine in 1999. They also founded Zend Technologies in Ramat Gan, Israel.
In 2008 PHP 5 became the only stable version under development. Late static binding had been missing from PHP and was added in version 5.3.
PHP is free software released under the PHP License, which insists that


Syntax:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PHP Test</title>
</head>
<body>
<?php
echo 'Hello World';
/* echo("Hello World"); works as well,
although echo is not a function, but a
language construct. In some cases, such
as when multiple parameters are passed
to echo, parameters cannot be enclosed
in parentheses. */

?>
</body>
</html>


Source:PHP


Mysql Benchmarking tool

I did a study on the benchmarking tools available for mysql. I found mysqlslap to be the ideal tool for this. You can install mysqlslap by using the following command

$home> sudo apt-get install mysqlslap.


Once install you can use mysqlslap --help to get the argument list and synopsis for how to use it.
you can use number of iteration and concurrency limit for benchmarking performance of mysql.

for example:

mysqlslap -uroot -p -q Desktop/emp.sql -i15000


in this case the sql query written in the file emp.sql will run for 15000 times.

One important note is that mysqlslap only work if all of your tables,views,proc used in the query are under mysqlslap database.