Saturday, 25 May 2013

WampServer


WampServer

How to Set up and Get Started
with PHP MySQL Web Development

1.  Introduction

AMP is an acronym for Apache (an HTTP Server), MySQL (a relational database) and PHP (a server-side programming platform). These are industrial-strength, open-source software that collectively can be used to develop, deploy and run web applications. Depending on the operating platform, we have:
  • WAMP: Windows-Apache-MySQL-PHP
  • LAMP: Linux-Apache-MySQL-PHP
  • MAMP: Mac-Apache-MySQL-PHP
You can choose to install the components individually, or use a bundled software package. For example,
I shall assume that you are familiar with Apahe, MySQL and PHP. Otherwise, read "How to setup and get started with Apache HTTP Server", "How to setup and get started with MySQL".

2.  Setting Up WampServer

WampServer (@ http://www.wampserver.com/en/) bundles Apache, MySQL and PHP for Winodws in a single package. It also includes tools such as PhpMyAdmin (a MySQL database administration tool), SQL Buddy (an alternative to PhpMyAdmin), XDebug (a PHP Debugging Tool), WebGrind (a PHP Profiling Tool).

2.1  Installing WampServer

To Install WampServer:
  1. Download: Goto WampServer mother site at http://www.wampserver.com/en ⇒ Select "DOWNLOADS" ⇒ Choose the appropriate package for your platform (e.g., WampServer 2.2e (32 bits)) ⇒ Download the installation file (e.g., wampserver2.2e-php5.4.3-httpd2.2.22-mysql5.5.24-32b.exe).
  2. Install: To install the WAMPServer, simply run the downloaded installation file. Choose your installation directory. I shall assume that WampServer is installed in "d:\WampServer", denoted as <WAMPSERVER_HOME>, in this article.

2.2  Starting WampServer

To start the WampServer, choose "start WampServer" from the "Start" menu; or run "wampmanager.exe" from the WampServer installed directory. An icon will appear on the icon tray. "Green" icon indicates that all the services have started. "Red" indicates that all the services have stopped. You can put the server online (so that user can access the server over the Internet) by selecting the option "Put Online". Alternatively, you could put the server "Offline", such that it is accessible only within the localhost.

2.3  Verifying the Installation

By default, a directory called "www" was created under the WampServer installed directory, which serves as the root directory of the Apache Server. A welcome page called "index.php" was also created in the "www" directory.
To verify the installation:
  1. Start the WampServer. Wait for the icon to appear green (indicates that all services have started). Otherwise, click the icon and select "Start All Services". For testing, put the server "offline" to disable external access (i.e., it can be accessed only in localhost).
  2. Start a browser and issue URL http://localhost. This will in turn request for "index.php". Observe the output and compare with "index.php" source.

2.4  Writing a Hello-world PHP Script

Use a program editor to write a simple PHP script called "hello.php" and save under the "www" directory, as follows:
<html>
<head>
<title>First PHP Page</title>
</head>
<body>
<?php
echo '<h1>Hello, world!</h1>';
?>
</body>
</html>
To run this script, start a browser and issue URL http://localhost/hello.php.
Check the output produced via "view source". Take note that PHP is a server-side technology (instead of client-side technology like JavaScript). The PHP statements <?php ... ?> are processed in the server, and the results returned to the client (browser).

2.5  WampServer Directory Structure

WampServer is organized in the following directory structure:
  • bin: contains binaries for Apache, MySQL, and PHP, in their respectively sub-directory. For each component, you can install multiple versions and select one of them in operation.
  • apps: contains server-side tools such as PhpMyAdmin, SQL Buddy, and WebGrind.
  • tools: contains client-side tool such as xdc (XDebug Client).
  • www: is the apache server's root directory.
  • logs: contains apache access and error logs; and mysql log files.
  • alias: contains the the apache's alias configuration for PhpMyadmin, SQL Buddy and WebGrind.
  • scripts:
  • lang:
  • tmp:

2.6  Apache Configuration

The Apache's configuration file "http.conf" is located at "<WAMPSERVER_HOME>\bin\apache\Apache2.2.xx\conf". Take note of the following configuration directives.
  • The core directives are:
    ServerRoot "<WAMPSERVER_HOME>/bin/apache/apache2.2.xx"
    Listen 80
    ServerName localhost:80
    DocumentRoot "<WAMPSERVER_HOME>/www/"
    The ServerRoot specifies the apache's installed directory. Listen specifies the TCP port number for Apache web server, in this case, default of TCP port 80. The DocumentRoot specifies the root directory of the web server.
  • The directives related to directory authorisation are:
    #
    # Each directory to which Apache has access can be configured with respect
    # to which services and features are allowed and/or disabled in that
    # directory (and its subdirectories). 
    #
    # First, we configure the "default" to be a very restrictive set of 
    # features.  
    #
    <Directory />
        Options FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
    </Directory>
    #
    # This should be changed to whatever you set DocumentRoot to.
    #
    <Directory "<WAMPSERVER_HOME>/www/">
        Options Indexes FollowSymLinks
        AllowOverride all
    #   onlineoffline tag - don't remove
        Order Deny,Allow
        Deny from all
        Allow from 127.0.0.1
    </Directory>
    [TODO] Explanation
  • The directives related to logging are:
    ErrorLog "<WAMPSERVER_HOME>/logs/apache_error.log"
    CustomLog "<WAMPSERVER_HOME>/logs/access.log" common

2.7  PHP Configuration

The PHP's configuration file "php.ini" is located at "<WAMPSERVER_HOME>\bin\apache\Apache2.2.xx\bin".
[TODO] Explanation

2.8  MySQL Configuration

The MySQL's configuration file "my.ini" is located at "<WAMPSERVER_HOME>\bin\mysql\mysql5.5.xx", i.e., the MySQL installed directory. Take note of the following settings:
  • MySQL Server
    [wampmysqld]
    port  = 3306
    socket = /tmp/mysql.sock
    key_buffer = 16M
    max_allowed_packet = 1M
    table_cache = 64
    sort_buffer_size = 512K
    net_buffer_length = 8K
    read_buffer_size = 256K
    read_rnd_buffer_size = 512K
    myisam_sort_buffer_size = 8M
    basedir=<WAMPSERVER_HOME>/bin/mysql/mysql5.5.xx
    log-error=<WAMPSERVER_HOME>/logs/mysql.log
    datadir=<WAMPSERVER_HOME>/bin/mysql/mysql5.5.xx/data
    The port specifies the TCP port number for the MySQL server (defaulted to 3306). The basedir specifies the MySQL installed directory. The datadir specifies the databases directory. The log-error specifies the MySQL error log file.
  • MySQL Server Daemon (mysqld.exe)
    [mysqld]
    port=3306
  • Interactive Client (mysql)
    [client]
    #password = your_password
    port  = 3306

2.9  Customizing MySQL

The default MySQL installation provides a superuser called "root" without a password. It also provides an anonymous user with no password. You need to set a password for root, remove the anonymous user, and create a new user for operational use.
There are many ways to administer MySQL:
  1. PhpMyAdmin
  2. SQL Buddy
  3. MySQL Interactive client ("mysql.exe")
SQL Buddy
To set password for superuser "root":
  1. Login to SQL Buddy via URL http://localhost/sqlbuddy, with user "root" and empty password.
  2. Select "Users".
  3. Check the row of "User" of "root", "Host" of "localhost" and select "Edit".
  4. Enter the new password in "Change password" box.
  5. Repeat the above for root@127.0.0.1 (IP address for localhost) and root@::1 (IPv6 localhost address).
To remove the anonymous user:
  1. Login to SQL Buddy with superuser "root".
  2. Select "Users".
  3. Check the row of anonymous user (empty user name), and select "Delete".
You should not use superuser "root" for normal operations. "root" should be used for creating new user only. You could create a new user for normal operation. To create a new user called "wampuser":
  1. Login to SQL Buddy with user "root".
  2. Select "Users".
  3. In the "ADD NEW USER", enter "localhost" in "host" box, "wampuser" in "name" box, and "xxxx" in "password" box. Select the appropriate authorization option (do not check the "Grant Option"). Click "Submit" button.
PhpMyAdmin
[TODO]
MySQL Interactive Client (mysql)
Read "How to setup MySQL".

3.  Eclipse PDT (PHP Developer Tool)

A good IDE with a graphic debugger is critical for program development.
Eclipse PDT (PHP Developer Tool) is an IDE for PHP program development. The main advantage is it can debug PHP script with XDebug or Zend Debugger. Read "Eclipse PDT (PHP Developer Tool)".

4.  PhpMyAdmin and SQL Buddy

PhpMyAdmin (http://www.phpmyadmin.net) is an open source web-base tool intended to handle the administration of MySQL. SQL Buddy (http://www.sqlbuddy.com) is an alternative to PhpMyAdmin.

4.1  PhpMyAdmin

PhpMyAdmin is bundled in WampServer, installed under <WAMPSERVER_HOME>\apps\phpmyadmin3.x.xx.
The configuration file is "config.inc.php", located at the PhpMyAdmin installed directory. The default configuration requires you to hardcode the MySQL user and password inside the configuration file:
$cfg['Servers'][$i]['auth_type'] = 'config'
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'your_root_password';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
I recommend that you change the configuration to prompt user to login with password by changing the auth_type from "config" to "cookie".
// $cfg['Servers'][$i]['auth_type'] = 'config'
$cfg['Servers'][$i]['auth_type'] = 'cookie';
// $cfg['Servers'][$i]['user'] = 'root';
// $cfg['Servers'][$i]['password'] = 'your_root_password';
// $cfg['Servers'][$i]['AllowNoPassword'] = true;
To launch PhpMyAdmin, start a browser and issue URL http://localhost/phpmyadmin.

4.2  SQL Buddy

SQL Buddy is an alternative to PhpMyAdmin, which is also bundled in WampServer, under directory <WAMPSERVER_HOME>\apps\sqlbuddy1.3.x. SQL Buddy could be easier to use than PhpMyAdmin.
To use SQL Buddy, start a browser, and issue URL http://localhost/sqlbuddy.

5.  Setting up SSL Support for Apache Server

Step 1: Create a Certificate for the Web Server
The first step to set up SSL/TLS is to create a certificate for your web server. To do so, you need OpenSSL, which is an open-source software available at http://www.openssl.org (source distributions only). For windows user, you can download the OpenSSL binary from http://www.slproweb.com/products/Win32OpenSSL.html (you also need "Visual C++ 2008 Redistributables". The download link is given in the same page). Download and install OpenSSL. (WampServcer also bundled a copy of OpenSSL in d:\WampServer\bin\php\php5.3.5\extras\openssl but is hard to use.)
Create a self-signed certificate for the server: Use OpenSSL to create a self-signed certificate for server by issuing the following command from a command shell. First of all, a public-private key pair needs to be generated. The private key is saved in the server in a secure file "server.key". The public key is store in a certificate "server.crt" to be transferred to the user.
> openssl req -new -x509 -days 36500 -sha1 -newkey rsa:1024 -nodes -keyout server.key -out server.crt 
  -subj /C=SG/O=Company/CN=localhost
  • -x509 requests a x509 certificate to be generated.
  • -days 36500 sets the expiration period for the certificate. The default is 30 days. I set to 100 years.
  • -sha1 specifies that SHA1 encryption should be used.
  • rsa:1024 sets the key as 1024 bit RSA.
  • -nodes specifies no passphrase is to be used for the private key file.
  • -keyout and -out specify where to store the private key (server.key) and certificate (server.crt).
  • -subj sets the country code (/C), company name (/O), and the web site address (/CN). If you leave these out, you'll be prompted for them. The CN (Common Name) must be the same as the address of your web site, otherwise the certificate won't match and users will receive a warning when connecting.
  • Refer to http://www.modssl.org/docs/2.2/ssl_reference.html for more information about OpenSSL command syntax.
To view the content of a certificate (which contains the public key of the server), issue the following openssl command:
> openssl x509 -in server.crt -noout -text
Step 2: Configuring Apache HTTP Server
First of all, move the private key file (server.key) and certificate (server.crt) to the Apache's configuration directory (<WAMPSERVER_HOME>/bin/apache/apache2.2.xx/conf).
To configure apache for SSL/TLS support for WampServer, simply uncomment the following lines in apache's configuration "httpd.conf" (under <WAMPSERVER_HOME>/bin/apache/apache2.2.xx/conf):
LoadModule ssl_module modules/mod_ssl.so
Include conf/extra/httpd-ssl.conf
The LoadModule loads the SSL module and the Include directive includes more configuration options for SSL/TLS support.
Tailor "conf/extra/httpd-ssl.conf":
Listen 443
NameVirtualHost *:443
 
<VirtualHost *:443>
DocumentRoot "<WAMPSERVER_HOME>/wwwssl"
ServerName localhost:443
ErrorLog "<WAMPSERVER_HOME>/bin/apache/Apache2.2.17/logs/error.log"
TransferLog "<WAMPSERVER_HOME>/bin/apache/Apache2.2.17/logs/access.log"
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile "<WAMPSERVER_HOME>/bin/apache/Apache2.2.17/conf/server.crt"
SSLCertificateKeyFile "<WAMPSERVER_HOME>/bin/apache/Apache2.2.17/conf/server.key"
 
<Directory "<WAMPSERVER_HOME>/wwwssl">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
#   SSLRequireSSL
</Directory>
 
</VirtualHost>
Verifying SSL/TLS Installation
To verify Apache with SSL, start the Apache Server. Start a browser and issue https://localhost.
Because the server certificate is self-signed and not signed by a trusted CA (Certificate Authority), browse issues a warning.
For firefox: Select "I understand the risk" ⇒ "Add Exception" ⇒ "Confirm Security Exception".
What if...
In case of error in the installation:
  • Check the Apache and SSL log.
  • Try connecting to the Apache server via OpenSSL as follows:
    > openssl s_client -connect localhost:443
    If the connection succeeds then an HTTP command such as "`GET /"' to retrieve a web page.
More on Certificate
You may be able to get a free certificate from CAcert.org.
You can attached a passphrase (i.e., password) to the private key file. However, to start Apache, you need to either hardcode the passphrase in the apache's configuration file (same security exposure as no passphrase) or provide the passphrase during the start-up dialog (can't automate the apache start-up!).
To generate a certificate for signning by CA:
  1. Generate a public-privage key pair and a certificate request:
    > openssl req -new -sha1 -newkey rsa:1024 -nodes  
      -keyout server.key -out www.example.com.csr
      -subj /O=Company/OU=Department/CN=www.example.com
    we didn't use the -x509 switch. The command will therefore generate a public-private key pair and certificate request (in a .csr file), but not a certificate (.crt file).
  2. Send that certificate request file "www.example.com.csr" to the CA (with your payment).
  3. Rename the received certificate to server.crt and verify its contents:
    > openssl verify -CAfile /path/to/trusted_ca.crt -purpose sslserver server.crt
    Check that the certificate corresponds to your private key:
    > openssl x509 -noout -modulus -in server.pem | openssl sha1
    > openssl rsa -noout -modulus -in server.key | openssl sha1
    
  4. Install your private key (server.key) and certificate (server.crt) in your apache configuration.

6.  Profiling PHP program with XDebug and WebGrind

The Xdebug PHP extension helps you debugging your script by providing a lot of valuable debug information and generate trace and profiling information.
Webgrind (http://code.google.com/p/webgrind/) is an Xdebug profiling web frontend in PHP5. It implements a subset of the features of kcachegrind and installs in seconds and works on all platforms.
[TODO]

7.  Debugging Web Pages (HTML, CSS, JavaScript, Cookie) on FireFox with Firebug/FireCookie

[TODO]
REFERENCES & RESOURCES
  1. Robin Nixon, "Learning PHP, MySQL, JavaScript, and CSS", 2nd ed, O'Reilly, 2012.
  2. Timothy Boronczyk, Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz and Michael K. Glass, "Beginning PHP6 Apache MySQL Web Development", Wrox Programmer to Programmer, 2009.
  3. Luke Welling and Laura Thomson, "PHP and MySQL Web Development", 4th edition, Addison-Wesley, 2008.
  4. Dirk Merkel, "Expert PHP 5 Tools", Packt Publishing, 2010.

Tuesday, 21 May 2013

How to send email notifications for comments in Drupal 7 with actions & triggers (or the Rules module)

http://adellefrank.com/blog/how-to-email-notifications-comments-drupal7

How to send email notifications for comments in Drupal 7 with actions & triggers (or the Rules module)

Rules module logo Do you have a Drupal 7 web site? Do you want to get an email when someone comments, so you don't have to check your site all the time? Don't panic! Here's how you do it.
You don't need to install any new modules to do this in Drupal 7. All that's needed is a little configuring and to copy and paste in a short bit of code.
Update: Both the easiest & most powerful way to get these notification emails (in Drupal 6 or 7) is to install and configure the Rules Module. NodeOne has a great set of video tutorials on their site explaining how to use the Rules module. I've also put example code for a Rules-based email notification in the comments to this post for both Drupal 6 and Drupal 7

Step 1: Getting started

Go to the Modules page, and make sure that you enable the Trigger module (at Modules > Trigger) and turn on Clean URLs (at Administer > Configuration > Search and metadata). These are core modules/settings in Drupal 7, so you don't have to install them, just turn them on.
enabled checkbox for Trigger on the Modules pagelocation of Clean URLs in administrative interface

Step 2: Taking action

Your next step will be to create an action, so that drupal can perform it when a comment is saved.
Go to Configuration > System > Actions.
Actions link shown on Configuration page
On the Actions page, choose the dropdown for Create an Advanced Action at the bottom of the page, and click on Send email and then Create.
create an advanced action dropdown with Send email highlighted
On the Configure an advanced action page, fill in the first 3 fields, as in these examples:
  • Label: Send an email notification to site owner upon comment save
  • Recipient: siteowner@adellefrank.com
  • Subject: New Comment at AdelleFrank.com
The trickiest part of this entire endeavor is filling in the Message field, but here's some easy sample code that you could just copy and paste in:
### Node
[comment:node:title] at: [site:url]node/[comment:node:nid]#comment-[comment:cid]

### Comment
[comment:author:name]
[comment:title]
[comment:body]

### Review
[site:url]admin/content/comment/approval

Those bits of code within square brackets are called tokens. Tokens are placeholders, little bits of code that represent commonly-used values. To find more tokens in Drupal 7, you must have two modules enabled. First, turn on the core Help module, which you should have enabled anyway...because it's helpful.  However, I find it bizarre that, even though you're only using tokens included in the Core, you must still install and turn on the Token module, too.
Only then can you point your web browser to the Help > Token page at http://www.yoursite.com/admin/help/token and get a list of all the tokens you can choose among.

Step 3: Triggering your action

At the top of the page, click on the Triggers link to go to the next step. This page can also be found underneath Structure > Triggers.
Triggers link shown at top of Actions page
Be sure to choose the comments tab on the Triggers page.
Comments tab shown at top of Triggers page
You have a number of choices, but since mine is a solo blog, Trigger: After saving a new comment seems most appropriate. Click on the dropdown instructing you to Choose an action and click underneath system on the name of the Action (Send an email notification to site owner upon comment save) you created in Step 2 and then click Assign.
action selected on dropdown for Trigger: After saving a new comment
successfully assigned action to trigger

Step 4: Testing your comments form

Now, as far as you know, your web site is set up to email you when someone saves a comment.  To be absolutely certain that your new action and trigger are working correctly, you need to test it.
Browse to any page, article, or blog post on your site and post a comment.
Check your email at the address you chose in step 2. Does this email give you the information you expected?
Remember to delete your test comment off of your site.

For more information

Drupal

http://www.lullabot.com/blog/articles/hiding-content-drupals-search-system

Drupal 7 - Give permission to manage users but not permissions-use ful links

http://drupal.stackexchange.com/questions/34352/drupal-7-give-permission-to-manage-users-but-not-permissions

http://www.technospiders.com/drupal/creating-new-user-roles

Thursday, 11 April 2013

wordpress plugin

<?
/**
 * Plugin Name: html form generation
 * Plugin Uri:  http://wordpress.org/extend/plugins/fg-joomla-to-wordpress/
 * Description: A plugin to migrate categories, posts, images and medias from Joomla to WordPress
 * Version:     1.10.6
 * Author:     pradeep kumar
 */
?>
<?php
/** Step 2 (from text above). */
add_action( 'admin_menu', 'my_plugin_menu' );

/** Step 1. */
function my_plugin_menu() {
    add_options_page( 'My Plugin Options', 'My Plugin', 'manage_options', 'my-unique-identifier', 'my_plugin_options' );
}

/** Step 3. */
function my_plugin_options() {
    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }
    echo '<div class="wrap">';
    echo '<p>Here is where the form would go if I actually had options.</p>';
    echo '</div>';
}
?>

Thursday, 21 February 2013

Wordpress pagination

<?php
$catname = wp_title('', false);
$wp_query = new WP_Query();
$wp_query->query('category_name='.$catname.'&showposts=5'.'&paged='.$paged);
?>

<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<?php the_title(); ?>
<?php } ?>

<?php endwhile; ?>

<?php next_posts_link('&laquo; Older Entries') ?>
<?php previous_posts_link('Newer Entries &raquo;') ?>

Wordpress thumbnails

http://codex.wordpress.org/Post_Thumbnails

Post Thumbnails

Post Thumbnail is a theme feature introduced with Version 2.9. It was quickly changed to Featured Image with Version 3.0. Post Thumbnail, now Featured Image, is an image that is chosen as the representative image for Posts, Pages or Custom Post Types. The display of this image is up to the theme. This is especially useful for "magazine-style" themes where each post has an image.

Contents

[hide]

Enabling Support for Post Thumbnails

Themes have to declare their support for post images before the interface for assigning these images will appear on the Edit Post and Edit Page screens. They do this by putting the following in their functions.php file:
add_theme_support( 'post-thumbnails' ); 
Note: To enable Post Thumbnails only for specific post types see add_theme_support()

Setting a Post Thumbnail

If your theme was successful in adding support for Post Thumbnails the "Featured Image" metabox will be visible on the on the Edit Post and Edit Page screens. If it isn't, make sure "Featured Image" is enabled in the screen options on the top right.
Featured Image Metabox
Featured image metabox
After clicking the "Set featured image" link follow the same steps as inserting images in Posts and Pages. But instead of the "Insert into Post" button use the "Use as featured image" link next to it, to set the Post Thumbnail.
image insert button
Insert image button

Function Reference

Template Tags
Other Functions

Examples

Default Usage

// check if the post has a Post Thumbnail assigned to it.
if ( has_post_thumbnail() ) {
 the_post_thumbnail();
} 
the_content();
Note: To return the Post Thumbnail for use in your PHP code instead of displaying it, use: get_the_post_thumbnail()

Linking to Post or Larger Image

To link the Post Thumbnail to the Post permalink or a larger image see the examples in the_post_thumbnail()

Thumbnail Sizes

The default image sizes of WordPress are "thumbnail", "medium", "large" and "full" (the image you uploaded). These image sizes can be configured in the WordPress Administration Media panel under Settings > Media. This is how you use these default sizes with the_post_thumbnail():
the_post_thumbnail();                  // without parameter -> Thumbnail

the_post_thumbnail('thumbnail');       // Thumbnail (default 150px x 150px max)
the_post_thumbnail('medium');          // Medium resolution (default 300px x 300px max)
the_post_thumbnail('large');           // Large resolution (default 640px x 640px max)
the_post_thumbnail('full');            // Original image resolution (unmodified)

the_post_thumbnail( array(100,100) );  // Other resolutions

Set the Post Thumbnail Size

To be used in the current Theme's functions.php file.
Set the default Post Thumbnail size by resizing the image proportionally (that is, without distorting it):
set_post_thumbnail_size( 50, 50 ); // 50 pixels wide by 50 pixels tall, resize mode
Set the default Post Thumbnail size by cropping the image (either from the sides, or from the top and bottom):
set_post_thumbnail_size( 50, 50, true ); // 50 pixels wide by 50 pixels tall, crop mode

Add New Post Thumbnail Sizes

Example of a new Post Thumbnail size named "category-thumb".
To be used in the current Theme's functions.php file.
add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height)
Here is an example of how to use this new Post Thumbnail size in theme template files.
<?php the_post_thumbnail( 'category-thumb' ); ?>

Example of functions.php

if ( function_exists( 'add_theme_support' ) ) { 
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 150, 150, true ); // default Post Thumbnail dimensions (cropped)

// additional image sizes
// delete the next line if you do not need additional image sizes
add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height)
}

Styling Post Thumbnails

Post Thumbnails are given a class "wp-post-image". They also get a class depending on the size of the thumbnail being displayed You can style the output with these CSS selectors:
img.wp-post-image
img.attachment-thumbnail
img.attachment-medium
img.attachment-large
img.attachment-full
You can also give Post Thumbnails their own class.
Display the Post Thumbnail with a class "alignleft":
<?php the_post_thumbnail('thumbnail', array('class' => 'alignleft')); ?>

Wednesday, 20 February 2013

Query string in PHP URL's

http://ditio.net/2008/06/12/php-query-string/

Query string plays important role in building web applications, especially if you want to make nice urls without question mark and many key, value pairs, actually it is not so easy to design application with nice urls however it is always worth doing so, because it not only looks very proffessional, such URLs are search engine friendly, which means that they will get indexed faster but also it happens that search engines have problems with indexing pages with more then 3 key=value pairs in query string.
However, one place where using nice URLs is not necessary are all kinds of admin panels, there are usually only few admins and more over admin panel never gets indexed so it doesn’t make any sense to make those URLs search engine friendly.
Query string can be accessed thru global array $_SERVER, more specific $_SERVER['QUERY_STRING'] is the actual variable where query string is written, this variable contains all data that is inputed after question mark in the URL. For example if we have URL which looks like this:
http://someurl.com/page.php?a=1&b=2&c=3
Then echo $_SERVER['QUERY_STRING'] will display: a=1&b=2&c=3, such data is no use to us, we need to parse it, or get it thru global array $_GET, in our case we could write:
echo $_GET['a'];
echo $_GET['b'];
echo $_GET['c'];
which would output:
1
2
3
Two things i have to mention here:
- i do not recommend displaying variables passed by user withut checking if they contain potentially dangerous code.
- make sure you have register_globals set to off in your ini file. If you do not have access to ini file, you can change this setting in your .htaccess file (if you have htaccess files working on your server). To do this just add following line php_flag register_globals off.
Using $_GET array to access variables from query string is pretty simple, however we would want to transform our URL to make it look like this:
http://someurl.com/1/2/3
This is very search engine friendly approach, however like always there are no roses without thorns. First problem is that $_SERVER['QUERY_STRING'] variable is empty now, so $_GET array is empty as well.
But first thing first, we can’t just input this URL in web browser address bar, hit enter and wait for a page to load. Probably it would end with 404 Error. To avoid this we need to create .htaccess file in the same directory as page.php file. Then open .htaccess file and write in it:
RewriteEngine on
RewriteRule .* page.php
Now all requests to directory which contains file page.php will be redirected to page.php file. Pretty simple and we can now use URL without question mark or any other unwanted signs i provided earlier (e.g. http://someurl.com/1/2/3).
So as i said earlier now our $_GET array is empty, but fortunately we can still check what the URL looks like by writing this code:
echo $_SERVER['REQUEST_URI'];
// output /1/2/3
Well, maybe URL looks pretty search engine friendly however id does not provide a lot of info as it did earlier. Unfortunately solution to this problem is beyond the scope of this article and i will give you only few guidlines: first you need to parse URL wit explode() to get array, then it will be good to assign some keys to each of the variable, but you always need to remember who is who, do not change order of parameters in the URL.
I covered only two types passing arguments to application with query string, there are other solutions as well, but i think that this two are the most common used and are actually the best when it comes to PHP.

Monday, 18 February 2013

leaf year programme for php and jquery

<html>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
    //alert('readyfunciton');
    //Month value changed
    $("#MM").change(function(){
        var selectVal = $('#MM :selected').val();
        //alert(selectVal);
        if(selectVal == '2'){
            $("#DD option[value='29']").attr('hidden','hidden');   
            $("#DD option[value='30']").attr('hidden','hidden');
            $("#DD option[value='31']").attr('hidden','hidden');
        }else if(selectVal == '4' || selectVal == '6' ||selectVal == '9'|| selectVal == '11'){
            $("#DD option[value='29']").removeAttr("hidden");   
            $("#DD option[value='30']").removeAttr("hidden");
            $("#DD option[value='31']").attr('hidden','hidden');           
        }else{
            $("#DD option[value='29']").removeAttr("hidden");   
            $("#DD option[value='30']").removeAttr("hidden");
            $("#DD option[value='31']").removeAttr("hidden");
        }               
    });
    $("#YYYY").change(function(){
        var yearVal = $('#YYYY :selected').val();       
        var monthVal = $('#MM :selected').val();
        if( ((yearVal%4 == 0 && yearVal%100  !== 0) && monthVal == 2)|| yearVal%400 == 0)){
            $("#DD option[value='29']").removeAttr("hidden");                   
            $("#DD option[value='30']").attr('hidden','hidden');
            $("#DD option[value='31']").attr('hidden','hidden');
                       
        }   
    });
  
});
</script>
<body>
<select name="MM" id="MM">
<option>MM</option>
<?php
$MM = array('1' => 'JAN',
            '2' => 'FEB',
            '3' => 'MAR',
            '4' => 'APR',
            '5' => 'MAY',
            '6' => 'JUN',
            '7' => 'JUL',
            '8' => 'AUG',
            '9' => 'SEP',
            '10' => 'OCT',
            '11' => 'NOV',
            '12' => 'DEC');
foreach ($MM as $key => $value){
    echo '<option value ="'.$key.'">'.$value.'</option>';
}
?>
</select>
<select name="DD" id="DD">
<option>DD</option>
<?php
for ($i = 1; $i <= 31; $i++) {
    echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
<select name="YYYY" id="YYYY">
<option>YYYY</option>
<?php
for ($i = 1960; $i < 2020; $i++) {
    echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
</body>
</html>

Thursday, 20 December 2012

Difference between compiler and interpreter


A Compiler and Interpreter both carry out the same purpose – convert a high level language (like C, Java) instructions into the binary form which is understandable by computer hardware. They are the software used to execute the high level programs and codes to perform various tasks. Specific compilers/interpreters are designed for different high level languages. However both compiler and interpreter have the same objective but they differ in the way they accomplish their task i.e. convert high level language into machine language. Through this article we will talk about the basic working of both and distinguish the basic difference between compiler and interpreter.
 
Compiler
compiler is a piece of code that translates the high level language into machine language. When a user writes a code in a high level language such as Java and wants it to execute, a specific compiler which is designed for Java is used before it will be executed. The compiler scans the entire program first and then translates it into machine code which will be executed by the computer processor and the corresponding tasks will be performed.  
Compiler working
Shown in the figure is basic outline of the compilation process, here program written in higher level language is known as source program and the converted one is called object program.
 
Interpreter
Interpreters are not much different than compilers. They also convert the high level language into machine readable binary equivalents. Each time when an interpreter gets a high level language code to be executed, it converts the code into an intermediate code before converting it into the machine code. Each part of the code is interpreted and then execute separately in a sequence and an error is found in a part of the code it will stop the interpretation of the code without translating the next set of the codes.  
Interpreter working
Outlining the basic working of the interpreter the above figure shows that first a source code is converted to an intermediate form and then that is executed by the interpreter.
 
The main differences between compiler and interpreter are listed below:
·         The interpreter takes one statement then translates it and executes it and then takes another statement. While the compiler translates the entire program in one go and then executes it.
·         Compiler generates the error report after the translation of the entire page while an interpreter will stop the translation after it gets the first error.
·         Compiler takes a larger amount of time in analyzing and processing the high level language code comparatively interpreter takes lesser time in the same process.
·         Besides the processing and analyzing time the overall execution time of a code is faster for compiler relative to the interpreter.

In the field of computers, the instructions given by the user are normally of high level language, whereas the computer will understand the instructions only in the binary format, the language of a computer is known as machine language. The sole purpose of the compiler and interpreter is to convert the user given high level language into machine level language so as to make the computer understand and executed the users driven instruction set. “If both the interpreter and compiler are used for sole purpose then what is the significance of each, for this reason the current report if aimed at exploring the difference between a compiler and interpreter”. A compiler will translate the high level language input given by the user into the machine language, i.e. in the binary codes, whereas an interpreter also converts the high-level language into machine level language but the interpreter will initially generate an intermediate code and then convert the high level language to machine level language.

The following context doles out brief description on the differences among the compiler and interpreter

Difference between compiler and interpreter:
Even though the compiler and interpreter are used for converting the high level language to machine language, there exist few variations between the compiler in the style and functionalities in converting the languages.

Compiler is a unique program that runs the instructions that are written in a certain programming language and convert them into the machine code that a computer can understand. The interpreter just does the same work as of the compiler, but the major variation is that, it converts the high level language into an intermediate code which is executed by the processor.  Normally a developer compose the instructions set by using any kind of programming language such as C, Java, Pascal, Python etc. The instruction written by the programmer is referred as the source code. The programmer must initiate the compiler or interpreter that is pertained to the language used for writing source code. Interpreter investigates and runs each line of source code in sequence, without considering the whole program at once. Nevertheless, programs shaped by compilers run greatly faster than the same instructions executed by an interpreter.

Basic differences between Compiler and Interpreter:
  • Compiler translates the high level instruction into machine language, but the interpreter translates the high level instruction into an intermediate code.
  • The compiler executes the entire program at a time, but the interpreter executes each and every line individually.
  • Compiler reports the list of errors that are caused during the process of execution, but the interpreter quits translating soon after finding an error, the progression of the other lines of the program will be done after refining the error.
  • Autonomous executable file is generated by the compiler while interpreter is compulsory for an interpreter program.

Differences on the basis of Various characteristics:
  • In a compiler the analyzing and processing time of the program is more, while an interpreter spends less time for the program analyzing and processing.
  • The resulting code of the compiler is in the form of machine code or binary format, in case of interpreter the resulting code is in the form of the intermediate code.
  • In case of compiler, the resulting code is executed by the computer hardware, in an interpreter; another program interprets the resulting code.
  • The execution of the program is fast in the compiler; in an interpreter the program execution speed is comparatively slow.

Differences on the basis of programming:
  • The compiler will verify syntax of program, whereas the interpreter verifies the keywords of a program.
  • The compiler will verify the entire program at a time, but the interpreter verifies the program concurrently in the editor.
  • The execution of the program in the interpreter is done line by line but the compiler executes the program on the whole.

Thursday, 6 December 2012

Drupal Subject

http://www.anilsagar.com/content/drupal-7-tutorial-part-14-drupal-7-file-system-structure-explained

http://websule.com/tutorials/drupal-basics/drupal-technology-stack

Friday, 30 November 2012

online jobs

<a href="http://www.onlinejobsfree.com/?id=1161537"><img src="http://www.onlinejobsfree.com/mem/images/300-

Monday, 19 November 2012

Differences between PHP4 and PHP5

Differences between PHP4 and PHP5:


Here's a quick overview of what has changed between PH4 and PHP5. PHP5 for the most part is backwards compatible with PHP4, but there are a couple key changes that might break your PHP4 script in a PHP5 environment. If you aren't already, I stronly suggest you start developing for PHP5. Many hosts these days offer a PHP5 environment, or a dual PHP4/PHP5 setup so you should be fine on that end. Using all of these new features is worth even a moderate amount of trouble you might go through finding a new host!

Note: Some of the features listed below are only in PHP5.2 and above.

Object ModelThe new OOP features in PHP5 is probably the one thing that everyone knows for sure about. Out of all the new features, these are the ones that are talked about most!

Passed by ReferenceThis is an important change. In PHP4, everything was passed by value, including objects. This has changed in PHP5 -- all objects are now passed by reference.

PHP Code:
$joe = new Person();$joe->sex 'male';
$betty $joe;$betty->sex 'female';

echo 
$joe->sex// Will be 'female'  
The above code fragment was common in PHP4. If you needed to duplicate an object, you simply copied it by assigning it to another variable. But in PHP5 you must use the new clone keyword.

Note that this also means you can stop using the reference operator (&). It was common practice to pass your objects around using the & operator to get around the annoying pass-by-value functionality in PHP4.

Class Constants and Static Methods/Properties
You can now create class constants that act much the same was as define()'ed constants, but are contained within a class definition and accessed with the :: operator.

Static methods and properties are also available. When you declare a class member as static, then it makes that member accessible (through the :: operator) without an instance. (Note this means within methods, the $this variable is not available)

Visibility
Class methods and properties now have visibility. PHP has 3 levels of visibility:
  1. Public is the most visible, making methods accessible to everyone and properties readable and writable by everyone.
  2. Protected makes members accessible to the class itself and any subclasses as well as any parent classes.
  3. Private makes members only available to the class itself.
Unified Constructors and DestructorsPHP5 introduces a new unified constructor/destructor names. In PHP4, a constructor was simply a method that had the same name as the class itself. This caused some headaches since if you changed the name of the class, you would have to go through and change every occurrence of that name.

In PHP5, all constructors are named __construct(). That is, the word construct prefixed by two underscores. Other then this name change, a constructor works the same way.

Also, the newly added __destruct() (destruct prefixed by two underscores) allows you to write code that will be executed when the object is destroyed.

Abstract ClassesPHP5 lets you declare a class as abstract. An abstract class cannot itself be instantiated, it is purely used to define a model where other classes extend. You must declare a class abstract if it contains any abstract methods. Any methods marked as abstract must be defined within any classes that extend the class. Note that you can also include full method definitions within an abstract class along with any abstract methods.

InterfacesPHP5 introduces interfaces to help you design common APIs. An interface defines the methods a class must implement. Note that all the methods defined in an interface must be public. An interface is not designed as a blueprint for classes, but just a way to standardize a common API.

The one big advantage to using interfaces is that a class can implement any number of them. You can still only extend on parent class, but you can implement an unlimited number of interfaces.

Magic Methods
There are a number of "magic methods" that add an assortment to functionality to your classes. Note that PHP reserves the naming of methods prefixed with a double-underscore. Never name any of your methods with this naming scheme!

Some magic methods to take note of are __call, __get, __set and __toString. These are the ones I find most useful.

Finality
You can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

The __autoload FunctionUsing a specially named function, __autoload (there's that double-underscore again!), you can automatically load object files when PHP encounters a class that hasn't been defined yet. Instead of large chunks of include's at the top of your scripts, you can define a simple autoload function to include them automatically.

PHP Code:
function __autoload($class_name) {
     require_once 
"./includes/classes/$class_name.inc.php";
}  
Note you can change the autoload function or even add multiple autoload functions usingspl_autoload_register and related functions.

Standard PHP LibraryPHP now includes a bunch of functionality to solve common problems in the so-named SPL. There's a lot of cool stuff in there, check it out!

For example, we can finally create classes that can be accessed like arrays by implementing the ArrayAccess interface. If we implement the Iterator interface, we can even let our classes work in situations like the foreach construct.


Miscellaneous Features

Type Hinting
PHP5 introduces limited type hinting. This means you can enforce what kind of variables are passed to functions or class methods. The drawback is that (at this time), it will only work for classes or arrays -- so no other scalar types like integers or strings.

To add a type hint to a parameter, you specify the name of the class before the $. Beware that when you specify a class name, the type will be satisfied with all of its subclasses as well.

PHP Code:
function echo_user(User $user) {
    echo 
$user->getUsername();
}  
If the passed parameter is not User (or a subclass of User), then PHP will throw a fatal error.

ExceptionsPHP finally introduces exceptions! An exception is basically an error. By using an exception however, you gain more control the simple trigger_error notices we were stuck with before.

An exception is just an object. When an error occurs, you throw an exception. When an exception is thrown, the rest of the PHP code following will not be executed. When you are about to perform something "risky", surround your code with a try block. If an exception is thrown, then your following catch block is there to intercept the error and handle it accordingly. If there is no catch block, a fatal error occurs.

PHP Code:
try {
    
$cache->write();
} catch (
AccessDeniedException $e) {
    die(
'Could not write the cache, access denied.');
} catch (
Exception $e) {
   die(
'An unknown error occurred: ' $e->getMessage());
}  
E_STRICT Error Level
There is a new error level defined as E_STRICT (value 2048). It is not included in E_ALL, if you wish to use this new level you must specify it explicitly. E_STRICT will notify you when you use depreciated code. I suggest you enable this level so you can always stay on top of things.

Foreach Construct and By-Reference Value
The foreach construct now lets you define the 'value' as a reference instead of a copy. Though I would suggest against using this feature, as it can cause some problems if you aren't careful:

PHP Code:
foreach($array as $k => &$v) {
    
// Nice and easy, no working with $array[$k] anymore
    
$v htmlentities($v);
}
// But be careful, this will have an unexpected result because
// $v will still be a reference to the last element of the $array array
foreach($another_array as $k => $v) {

}  


New Functions

PHP5 introduces a slew of new functions. You can get a list of them from the PHP Manual.

New Extensions
PHP5 also introduces new default extensions.
  • SimpleXML for easy processing of XML data
  • DOM and XSL extensions are available for a much improved XML-consuming experience. A breath of fresh air after using DOMXML for PHP4!
  • PDO for working with databases. An excellent OO interface for interacting with your database.
  • Hash gives you access to a ton of hash functions if you need more then the usual md5 or sha1.
Compatibility IssuesThe PHP manual has a list of changes that will affect backwards compatibility. You should definately read through that page, but here is are three issues I have found particularly tiresome:
  • array_merge() will now give you warnings if any of the parameters are not arrays. In PHP4, you could get away with merging non-arrays with arrays (and the items would just be added if they were say, a string). Of course it was bad practice to do this to being with, but it can cause headaches if you don't know about it.
  • As discussed above, objects are now passed by references. If you want to copy a object, make sure to use the clone keyword.
  • get_*() now return names as they were defined. If a class was called MyTestClass, then get_class() will return that -- case sensitive! In PHP4, they were always returned in lowercase.
__________________