Wednesday, June 11, 2008

Create Virtual Host in the httpd.conf file

>
ServerName hrapplication.com
DocumentRoot "C:\xampp\htdocs\sf_sandbox\web"
DirectoryIndex index.php

Options Indexes FollowSymLinks
AllowOverride All
Allow from All



Adding Host


Go to C:\Windows\System32\drivers\etc

Thursday, May 22, 2008

Site for the AJAX

http://www.ajaxian.com/

Browser cookie restriction research

Nicholas C. Zakas was doing some prep work for his new book when he delved into browser cookie restrictions for the big four browsers:

The most interesting fact I discovered is that Safari places no limit
on the number of cookies that can be set per domain. In fact, you can
set enough cookies on the client to cause a server error as the cookie
header can be too long to parse.

He also found out that:

  • Microsoft indicated that Internet Explorer 8 increased the cookie limit per domain to 50 cookies but I've found that IE7 also allows 50 cookies per domain. Granted, this may have been increased with a system patch rather than having the browser's first version ship like this, but it's still more than the 20 that was commonly understood to be the limit.
  • Firefox has a per-domain cookie limit of 50 cookies.
  • Opera has a per-domain cookie limit of 30 cookies.
  • Safari/WebKit is the most interesting of all as it appears to have no perceivable limit through Safari 3.1. I tested setting up to 10,000 cookies and all of them were set and sent along in the Cookie header. The problem is that the header size exceeded the limit that the server could process, so an error occurred.

So the prevailing knowledge that browsers limit per-domain cookies to 20 is no longer valid. Another interesting inconsistency is how browsers react when too many cookies are set. With the exception of Safari, which sets all cookies regardless of the number, there are two approaches:

  1. The least recently used (LRU) approach automatically kicks out the oldest cookie when the cookie limit has been reached in order to allow the newest cookie some space. Internet Explorer and Opera use this approach.
  2. Firefox does something strange: it seems to randomly decide which cookies to keep although the last cookie set is always kept. There doesn't seem to be any scheme it's following at all. The takeaway? Don't go above the cookie limit in Firefox.

The total size of cookies also varies from browser to browser. This is another one that is a little hard to comprehend, but here's what my tests show:

  • Firefox and Safari allow cookies with up to 4097 characters, that's 4096 for the name and value and one for the equals sign.
  • Opera allows cookies with up to 4096 characters, which is for the name, value, and equals sign.
  • Internet Explorer allows cookies with up to 4095 characters, which is for the name, value and, equals sign.

Execute PHP syntax in .HTML file

If you want to run PHP code in .html extention file
Then Follow following procedures.

1. Write Following code in the .htaccess file
---------------------------------------------
RemoveHandler .html .htm
AddType application/x-httpd-php .php .htm .html
-----------------------------------------------------

2. Upload it to your server (to your WWW root) where your
.html files are located in which contains PHP code.

Thats the idea.

Check Disk Space in Linux

Linux / Unix df command

About df

Report how much free disk space is available for each mount you have.

Syntax

df [OPTION]... [FILE]...
-a, --all include dummy file systems
-B, --block-size=SIZE use SIZE-byte blocks
-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
-H, --si likewise, but use powers of 1000 not 1024
-i, --inodes list inode information instead of block usage
-k like --block-size=1K
-l, --local limit listing to local file systems
--no-sync do not invoke sync before getting usage info (default)
-P, --portability use the POSIX output format
--sync invoke sync before getting usage info
-t, --type=TYPE limit listing to file systems of type TYPE
-T, --print-type print file system type
-x, --exclude-type=TYPE limit listing to file systems not of type TYPE
--version output version information and exit

Examples

df

In the above example when performing just the df command with no additional switches or specification of the file or directory you would get a listing of all file systems and their used and available space.

df -h

The above command is one of the most commonly used commands as it displays the sizes in an easy to read format as shown in the below example.
Filesystem Size Used Avail Use% Mounted on
/dev/hda2 28G 7.6G 19G 29% /
tmpfs 252M 0 252M 0% /lib/init/rw
tmpfs 252M 0 252M 0% /dev/shm
/dev/hda1 464M 37M 403M 9% /boot
/dev/hda3 8.3G 429M 7.5G 6% /var
nfs6:/home 520G 461G 60G 89% /home
mirrors:/mirrors 1.4T 1.1T 233G 83% /mirrors
/dev/mapper/big-phat 77G 36G 42G 46% /space
mailstore:/var/mail 9.9G 4.8G 4.7G 51% /var/mail

df -b public_html

In the above example this command would display the amount of free space in the public_html directory. Below is an example of the output may display when performing this command.

Filesystem avail
nfs.computerhope.com:/home 10068252

Related commands

du
find
ls

Online Regular Expression Testing Tool

http://gskinner.com/RegExr/

Auto redirect HTTP to HTTPS (SSL)

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

VI Commands

Summary of VI Commands

#
Starting

* vi /filename/.....start vi, edit specified file
* vi -R /filename/..start vi read-only, edit specified file
* view /filename/...start vi read-only, edit specefied file


#
Stopping

* :q!...............stop without saving data
* zz................save data and stop
* :wq...............save data and stop
* :x................save data and stop


#
Recovering After System Failure

* vi -r .............display names of files that can be recovered
* vi -r /filename/...start vi, recover specified file


#
Controlling the Display

* ^L................redisplay the current screen
* :set number ......display internal line numbers
* :set nonumber.....do not display internal line numbers


#
Moving the Cursor

* h.................move cursor one position left
* j.................move cursor one position down
* k.................move cursor one position up
* l.................move cursor one position right
* LEFT..............move cursor one position left
* DOWN..............move cursor one position down
* UP................move cursor one position up
* RIGHT.............move cursor one position right
* BACKSPACE.........move cursor one position left
* SPACE.............move cursor one position right
* -.................move cursor to beginning of previous line
* +.................move cursor to beginning of next line
* RETURN............move cursor to beginning of next line
* O.................move cursor to begining of current line
* $.................move cursor to end of current line
* ^.................move cursor to first non-space/tab in current line
* w.................move cursor forward to first character of next word
* e.................move cursor forward to last character of next word
* b.................move cursor backward to first character of previous word
* W.................same as w; ignore punctuation
* E.................same as e; ignore punctuation
* B.................same as b; ignore punctuation
* ).................move forward to next sentence beginning
* (.................move backward to previous sentence beginning
* }.................move forward to next paragraph beginning
* {.................move backward to previous paragraph beginning
* H.................move cursor to top line
* M.................move cursor to middle line
* L.................move cursor to last line


#
Moving Through the Editing Buffer

* ^F................move down(forward) one screenful
* ^B................move up(backward) one screenful
* n^F...............move down n screenfuls
* n^B...............move up n screenfuls
* ^D................move down a half screenful
* ^U................move up a half a screenful
* n^D...............move down n lines
* n^U...............move up n lines


#
Searching for a Pattern

* /rexp.............search forward for specified regular expression
* /.................repeat forward search for previous pattern
* ?rexp.............search backward for specified regular expression
* ?.................repeat backward search for previous pattern
* n.................repeat last / or ? command, same direction
* N.................repeat last / or ? ? command, opposite direction


#
Special Characters to Use in Regular Expressions

* /./...............match any single character except newline
* *.................match zero or more of the preceding characters
* ^.................match the beginning of a line
* $.................match the end of a line
* /<................match the beginning of a word
* />................match the end of a word
* []................match one of the enclosed characters
* [^]...............match any character taht is not enclosed
* \.................interpret the following symbol literally


#
Line Numbers

* nG................jump to line number n
* 1G................jump to first line in editing buffer
* G.................jump to last line in editing buffer
* :map g1G..........define macro so g will be the same as 1G


#
Inserting

* i.................change to insert mode: insert before cursor position
* a.................change to insert mode: insert after cursor position
* I.................change to insert mode: insert at start of current line
* A.................change to insert mode: insert at end of current line
* o.................change to insert mode: open below current line
* O.................change to insert mode: open above current line
* ESCAPE............leave insert mode, change to command mode


#
Making Changes

* r.................replace exactly 1 character (do not enter input mode)
* R.................replace by typing over
* s.................replace 1 character by insertion
* C.................replace from cursor to end of line by insertion
* cc................replace entire current line by insertion
* S.................replace entire current line by insertion
* cmove.............replace from cursor to move by insertion
* ~.................change the case of a letter


#
Replacing a Pattern

* :s/pattern/replace/.............substitute, current line
* :lines/pattern/replace/ ........substitute, specified line
* :line, lines/pattern/replace/..substitute, specified range
* :%s/pattern/replace/...........substitute, all lines


#
Undoing or Repeating a Change

* u.................undo last command that modified the editing buffer
* U.................restore current line
* /./...............repeat last command that modified the editing buffer


#
Controlling the Length of Lines

* rReturn...........replace a character with a newline
* J.................join lines
* :set wm=n.........auto line break within n positions of right margin


#
Deleting

* x.................delete character at cursor
* X.................delete character to left of cursor
* D.................delete from cursor to end of line
* dd................delete entire current line
* dmove .............delete from cursor to move
* dG................delete from current line to end of editing buffer
* d1G...............delete from current line to start of editing buffer
* :/lined/..........delete specified line
* :/line/, /lined/..delete specified range


#
Copying the Last Deletion

* P.................copy buffer; insert after/below cursor
* p.................copy buffer; insert before/above cursor
* xp................transpose two characters
* deep..............transpose two words(start to the left of first word)
* ddp...............transpose two lines


#
Copying and Moving Lines

* :linecotarget.........copy specified line; insert below target
* :line, linecotarget...copy specified range; inster below target
* :linemtarget..........move specified line; insert below target
* :line,linemtarget move.specified range; insert below target


#
Executing Shell Commands

* :!command...........pause vi, execute specified shell command
* :!!.................pause vi, execute previous shell command
* :sh.................pause vi, start a shell
* :!csh ...............pause vi, start a new C-Shell


#
Reading Data

* :liner file .........insert contents of file after specified line
* :r file..............insert contents of file after current line
* :liner !command......insert output of command after specified line
* :r !command .........insert output of command after current line
* :r !look pattern.....insert words that begin with specified pattern


#
Using Shell Commands to Process Data

* n!!command...........execute command on n lines
* !move command........execute command from cursor to move
* !movefmt.............format lines from cursor to move


#
Writing Data

* :w...................write data to original file
* :w file..............write data to specified file
* :w>> file............append data to specified file


#
Changing the File While Editing

* :e file..............edit the specified file
* :e! file.............edit the specified file, omit automatic check


#
Abbreviations

* :ab short long....set short as an abbreviation for long
* :ab...............display current abbreviations
* :una short........cancel abbreviation short

Example for Mod RewriteRule

#--MOD Rewirite--
RewriteEngine On
RewriteRule ^dir/(.*) /home/httpd/vhosts/jyvepresence.com/httpdocs/index.php?status=$1

#-----------------------
# URL will be
# http://www.domain.com/dir/vikrant
# It will execute index.php
# $1 == vikrant
#------------------------

RewriteRule ^/?([^/]*\.png|[^\./]*)[:;,\.]*$ /home/httpd/vhosts/jyvepresence.com/httpdocs/index.php?status=$1 [L,NS]

#-----------------------
# URL will be
# http://www.domain.com/vikrant.png OR http://www.domain.com/vikrant
# It will execute index.php
# $1 == vikrant.png OR $1 == vikrant
#------------------------

2 -------------------------------------
Old dynamic url:
Code:
www.domain.com/catalog.php?cat=widgets&product_id=1234
New static url:
Code:
www.domain.com/catalog/widgets-1234.html
Code:
#start .htaccess code
RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} ^cat\=([^&]+)\&product_id\=([^&]+)$
RewriteRule ^$ /catalog/%1-%2.html [R=301,L]


Reg Expression notes:
[^&]+ mean find any character except the "&" since it is what seperates the variables in a string. you can back reference matches in a rewrite condition using ()'s just like your rewrite rules but to call them you have to use a % instead of a $.

Benefits:
1. You don't have to hand write 1,000's of 301 redirects

2. Spiders can easily pick up the 301 and pass the scores and index the new urls much faster than having to crawl the entire site over from scratch.

3. Users clicking old dynamic urls in the SERPS will not get a 404 error. They'll go straight to the new static urls.

3 -----------------------------

Browser Dependent Content


Description:

At least for important top-level pages it is sometimes necessary to provide the optimum of browser dependent content, i.e. one has to provide a maximum version for the latest Netscape variants, a minimum version for the Lynx browsers and a average feature version for all others.
Solution:

We cannot use content negotiation because the browsers do not provide their type in that form. Instead we have to act on the HTTP header "User-Agent". The following condig does the following: If the HTTP header "User-Agent" begins with "Mozilla/3", the page foo.html is rewritten to foo.NS.html and and the rewriting stops. If the browser is "Lynx" or "Mozilla" of version 1 or 2 the URL becomes foo.20.html. All other browsers receive page foo.32.html. This is done by the following ruleset:

RewriteCond %{HTTP_USER_AGENT} ^Mozilla/3.*
RewriteRule ^foo\.html$ foo.NS.html [L]

RewriteCond %{HTTP_USER_AGENT} ^Lynx/.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/[12].*
RewriteRule ^foo\.html$ foo.20.html [L]

RewriteRule ^foo\.html$ foo.32.html [L]

4-----------------------------------------------------

Simple Example

Just to help illustrate how you could use this information let's assume we had 3 web pages:

http://www.desilva.biz/wd_010427.php
http://www.desilva.biz/grafix_index.php
http://www.desilva.biz/hw_010506.php

and we want to re-direct our readers visiting each page above to their new versions at:

http://www.desilva.biz/refresh.html
http://www.desilva.biz/grafix.html
http://www.desilva.biz/cpuspeed.html

.htaccess

RewriteEngine on
RewriteRule ^wd_010427\.php$ refresh.html [R=301,L]
RewriteRule ^grafix_index\.php$ grafix.html [R=301,L]
RewriteRule ^hw_010506\.php$ cpuspeed.html [R=301,L]

URL Rewriting Guide

I found this Link very very useful for URL Rewriting

http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

tar --help

Create tar archive
==================

tar -cvf back_htdoc.tar htdocs/
tar -zcvf back_htdoc.tar.gz htdocs/

-c for create a new archive
-v for create a new archive
-f for use archive file or device ARCHIVE
-j, --bzip2 for filter the archive through bzip2
-z, --gzip, for filter the archive through gzip



un-tar
======

tar -xf back_htdoc.tar

-x for extract archive
-f for use archive file or device ARCHIVE
-z, --ungzip filter the archive through gzip

list files in tar
=================

tar -tvf archive.tar

-t for list
-v for create a new archive
-f for use archive file or device ARCHIVE

HTTP Authentication to Folder. (.htaccess /.htpasswd)

Write Following code in .htaccess file and save it into the folder which you want to
authonticate.

Change the path (In red) and enter the Folder path which you want to authenticate.

------------------------------------------------------------------

AuthUserFile /mnt/web/guide/somewhere/somepath/.htpasswd
AuthGroupFile /dev/null
AuthName "Somewhere.com's Secret Section"
AuthType Basic

require valid-user


--------------------------------------------------------------------
To create an .htpasswd file, login to the server via telnet(Command line) go to the directory you specified in AuthUserFile. In the example, this is /mnt/web/guide/somewhere/somepath. Then use the htpasswd program with the -c switch to create your .htpasswd in the current directory. (as per following)

----------------------------------------
htpasswd -c .htpasswd username
Adding password for username.
New password:
password
Re-type new password:
password
---------------------------------------

To delete users, open the .htpasswd file in a text editor and delete the appropriate lines:

Apache's Module (Somthing useful in httpd.conf for Web Programmer)

If you want to include any New settings whithout editing
httpd.conf file then copy following line once into your server
httpd.conf file. And later if you want to add new Module then edit subdomain.conf
and restart the server.
#------------------------------------------
Include /home/jyve_conf/subdomain.conf
#------------------------------------------


DirectoryIndex: sets the file that Apache will serve if a directory
is requested. If you requested http://yourdomain.com then server will automatically search index.html first for default file if not found then search for any mathch in the follwing list. You can list any file which you want to serve as default when user request for directory
#-------------------------------------------------------
DirectoryIndex index.html index.html.var index.php3
#-------------------------------------------------------


if your .htaccess is file is not working then add following lines in httpd.conf
(red) is folder path where .htaccess file located.
#-------------------------------------------------------------

AllowOverride All

#-------------------------------------------------------------

CronTab Quick Reference

What is Cron Tab ?
cron is a unix utility that allows tasks to be automatically run in the background at regular intervals by the cron daemon often termed as cron jobs.
Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.

Restriction
You can execute crontab if your name appears in the file
/usr/lib/cron/cron.allow. If that file does not exist, you can use
crontab if your name does not appear in the file
/usr/lib/cron/cron.deny.
If only cron.deny exists and is empty, all users can use crontab. If neither file exists, only the root user can use crontab. The allow/deny files consist of one user name per line.

Commands
export EDITOR=vi ;to specify a editor to open crontab file.

crontab -e Edit your crontab file, or create one if it doesn't already exist.
crontab -l Display your crontab file.
crontab -r Remove your crontab file.
crontab -v Display the last time you edited your crontab file. (This option is only available on a few systems.)

Crontab File
A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval.
* * * * * command to be executed
- - - - -
| | | | |
| | | | +----- day of week (1 - 7) (monday = 1)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)

Environment
cron invokes the command from the user's HOME directory with the shell, (/usr/bin/sh).
cron supplies a default environment for every shell, defining:
HOME=user's-home-directory
LOGNAME=user's-login-id
PATH=/usr/bin:/usr/sbin:.
SHELL=/usr/bin/sh

Users who desire to have their .profile executed must explicitly do so
in the crontab entry or in a script called by the entry.

Disable Email
By default cron jobs sends a email to the user account executing the cronjob. If this is not needed put the following command At the end of the cron job line .

>/dev/null 2>&1

Generate Log File
To collect the cron execution execution log in a file :

30 18 * * * rm /home/someuser/tmp/* > /home/someuser/cronlogs/clean_tmp_dir.log

Examples :
Cron set For Database BackUp

5 21 * * * mysqldump -u root -pclarion --opt specto | gzip > /backup1/amodd/spec
to_`date +%Y%m%d%H%M`.gz

Cron Set for run PHP File ..
* 0,6,12,18 * * * /usr/bin/php -q /var/www/html/vikrant/goskype/expertblog/blogsadmin/runcron.php > /dev/null

Important Linux Commands

Tar , UnTar and UnZip
--------------------------------
tar -zxf 18012005.tar vikrant/
tar -zcf newtitle.tar *.php
unzip myzip.zip

Folder SIZE
----------------
du -skh * | less -- Check the folder size
du -skh *| grep M | less -- Check the folder size which has MB

SCP:
-------------
-->Upload File to Server
# scp config.php username@www.youdomain.com:/home/rootdir/filename.php

-->Download file from server on Currnet directory.
# scp username@www.youdomain.com:/home/rootdir/filename.php .

Fetch (Download files from server)
-----------------------------------------
#wget http://yuordomain.com .

List Contents of Directory
---------------------------------
ls -l | wc -- (Get Number of Files /Content)
ls -lah -- (Human redable file size)

Check ServerLoad
----------------------
w

How to create SubDomains by editing httpd.conf

VirtualHost:
If you want to maintain multiple domains/hostnames on your
machine you can setup VirtualHost containers for them.

Types of Virtual Hosting
1) IP-Based Virtual Hosting
2) Name-Based Virtual Hosting
3) Dynamic Virtual Hosting

Good Example how to set subDomains under NameBased Virtual Hosting :

NOTE: NameVirtualHost cannot be used without a port specifier
(e.g. :80) if mod_ssl is being used, due to the nature of the
SSL protocol.

Change Apache's httpd.conf file

NameVirtualHost 215.51.182.53


ServerName *.yourdomain.com
ServerAlias yourdomain.com
DocumentRoot /home/rootdir #Directory where Scritpting files are located.
ErrorLog logs/error_log #Error are recorded in error_log file located /var/logs/httpd
CustomLog logs/visit_log combined # URL visit information recorded in visit_log file located /var/logs/httpd



ServerName subdomain.youydomain.com
ServerAlias subdomain.youydomain.com
DocumentRoot /home/rootdir/subdomain
ErrorLog logs/error_log
CustomLog logs/visit_log



ServerName subdomain1.youydomain.com
ServerAlias subdomain1.youydomain.com
DocumentRoot /home/rootdir/subdomain
ErrorLog logs/error_log
CustomLog logs/visit_log


NOTE :
You can create n number of SubDoamins on one IP address

MySQL - Database BackUp

The most common use of mysqldump is probably for making a backup of an entire database:

shell> mysqldump --opt db_name > backup-file.sql

You can read the dump file back into the server like this:

shell> mysql db_name <> mysql -e "source /path-to-backup/backup-file.sql" db_name

mysqldump is also very useful for populating databases by copying data from one MySQL server to another:

shell> mysqldump --opt db_name | mysql --host=remote_host -C db_name

It is possible to dump several databases with one command:

shell> mysqldump --databases db_name1 [db_name2 ...] > my_databases.sql

If you want to dump all databases, use the --all-databases option:

shell> mysqldump --all-databases > all_databases.sql

If tables are stored in the InnoDB storage engine, mysqldump provides a way of making an online backup of these (see command below). This backup just needs to acquire a global read lock on all tables (using FLUSH TABLES WITH READ LOCK) at the beginning of the dump. As soon as this lock has been acquired, the binary log coordinates are read and lock is released. So if and only if one long updating statement is running when the FLUSH... is issued, the MySQL server may get stalled until that long statement finishes, and then the dump becomes lock-free. So if the MySQL server receives only short (in the sense of "short execution time") updating statements, even if there are plenty of them, the initial lock period should not be noticeable.

shell> mysqldump --all-databases --single-transaction > all_databases.sql

For point-in-time recovery (also known as “roll-forward”, when you need to restore an old backup and replay the changes which happened since that backup), it is often useful to rotate the binary log (see Section 5.11.3, “The Binary Log”) or at least know the binary log coordinates to which the dump corresponds:

shell>
mysqldump --all-databases --master-data=2 > all_databases.sql
or
shell> mysqldump --all-databases --flush-logs --master-data=2 > all_databases.sql

MySql IFNULL, IF, CASE-WHEN-THEN -ELSE-END

IFNULL(expr,expr1)
--------------------------------------------
If 1st_ expr is null then retrun 2nd_expr

SELECT IFNULL(1,0);
-> 1
SELECT IFNULL(NULL,10);
-> 10
SELECT IFNULL(1/0,10);
-> 10
SELECT IFNULL(1/0,'yes');
-> 'yes'
--------------------------------------------------------------
CASE WHEN condiion THEN expr1 ELSE expr3 END
--------------------------------------------------------------

SELECT (CASE 2 WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "more" END) as ans;
-> two

SELECT CASE WHEN 1<0 style="color: rgb(255, 0, 0);">THEN "true" ELSE "false" END;
->false
--------------------------------------------------------------
IF(condition,expr,expr1)
--------------------------------------------------------------

SELECT IF(0.1<>0,1,0);
-> 1
SELECT IF(STRCMP('test','test1'),'no','yes');
-> no

What's New in PHP 5?

Introduction

Only time will tell if the PHP 5 release will be as successful as the releases of its two predecessors (PHP 3 and PHP 4). The new features and changes aim to rid PHP of any weaknesses it may have had and make sure that it stays in the lead as the best web scripting language on the globe.

This book covers PHP 5 and its new features in great detail. However, for those of you familiar with PHP 4, and are eager to know what is new in PHP 5, then this chapter is for you.

The chapter will cover:

  • The new language features
  • News concerning PHP extensions
  • Other noteworthy changes

Language Features

New Object Oriented model

When Zeev Suraski added the object-oriented syntax back in the days of PHP 3, it was added as "syntactic sugar for accessing collections". The object-oriented model also had support for inheritance and allowed a class (and object) to aggregate both methods and properties, but not much more. When Zeev and Andi rewrote the scripting engine for PHP 4, it was a completely new engine, running much faster, much more stable and with many more features. However, the object-oriented model first introduced in PHP 3, was barely touched.

Although the object model had serious limitations it was used extensively around the world, often in very large PHP applications. This impressive use of the OOP paradigm with PHP 4 despite its weaknesses led to it being the main focus for the PHP 5 release.

So what were some of the limitations in PHP 3 and 4? The biggest limitation (which led to further limitations) was the fact that the copy semantics of objects were the same as for native types. So how did this actually affect the PHP developer? When you'd assign a variable (that points to an object) to another variable, a copy of the object would be created. Not only did this impact performance but it usually also lead to obscure behavior and bugs in PHP 4 applications because many developers thought that both variables would be pointing at the same object which wasn't the case. They were pointing at separate copies of the same object, changing one would not change the other.

For example:

class Person {
var
$name;
function
getName() {
return
$this->name;
}
function
setName($name) {
$this->name = $name;
}
function
Person($name) {
$this->setName($name);
}
}

function
changeName($person, $name) {
$person->setName($name);
}

$person = new Person("Andi");
changeName($person, "Stig");
print
$person->getName();

In PHP 4, this piece of code would print out "Andi". The reason is that we pass the object $person to the changeName() function by-value, and thus, $person is copied and changeName() works on a copy of $person.

This behavior is not very intuitive, as many developers would expect the Java-like behavior. In Java variables actually hold a handle (or pointers) to the object, and therefore, when it is copied only the handle and not the entire object is duplicated.
There were two kinds of users in PHP 4, the ones who were aware of this problem and the ones who weren't. The latter would usually not notice this problem and their code was written in a way where it didn't really matter if the problem existed or not. Surely some of these people had sleepless nights trying to track down weird bugs which they couldn't pinpoint. The former group dealt with this problem by always passing and assigning objects by reference. This would prevent the engine from copying their objects but would be quite a headache as the code included numerous & signs.

The old object model not only led to the above-mentioned problems but also led to fundamental problems that prevented implementing some additional features on top of the existing object model.

In PHP 5, the infrastructure of the object model was rewritten to work with object handles. Unless you explicitly clone an object by using the clone keyword you will never create behind the scene duplicates of your objects. In PHP 5, there is neither a need to pass objects by reference nor assigning them by reference.

Note: Passing by reference and assigning by reference is still supported, in case you want to actually change a variable's content (whether object or other type).

New Object Oriented Features

The new object oriented features are too numerous to give a detailed description in this section. The object oriented language chapter goes over each feature in detail.

The following is a list of the main new features:

1. public/private/protected access modifiers for methods and properties

Allows the use of common OO access modifiers to control access to methods and properties.

class MyClass {
private
$id = 18;

public function
getId() {
return
$this->id;
}
}

2. Unified constructor name __construct()

Instead of the constructor being the name of the class, it should now be declared as __construct(), making it easier to shift classes inside class hierarchies.

class MyClass {
function
__construct() {
print
"Inside constructor";
}
}

3. Object destructor support by defining a __destructor() method

Allows defining a destructor function that runs when an object is destroyed.


class MyClass {
function
__destruct() {
print
"Destroying object";
}
}

?>

4. Interfaces

Gives the ability for a class to fulfill more than one is-a relationships. A class can inherit from one class only but may implement as many interfaces as it wants.

interface Display {
function
display();
}

class
Circle implements Display {
function
display() {
print
"Displaying circle ";
}
}

5. instanceof operator

Language level support for is-a relationship checking. The PHP 4 is_a() function is now deprecated.

if ($obj instance of Circle) {
print
'$obj is a Circle';
}

6. final methods

The final keyword allows you to mark methods so that an inheriting class can't overload them.

class MyClass {
final function
getBaseClassName() {
return
__CLASS__;
}
}

7. final classes

After declaring a class as final, it can't be inherited. The following example would error out:

final class FinalClass {
}

class
BogusClass extends FinalClass {
}

8. Explicit object cloning

In order to clone an object you have to use the clone keyword. You may declare a __clone() method which will be called during the clone process (after the properties have been copied from the original object).

class MyClass {
function
__clone() {
print
"Object is being cloned";
}
}
$obj = new MyClass();
clone
$obj;

9. Class constants

Classes definitions can now include constant values, and are referenced using the class.

class MyClass {
const
SUCCESS = "Success";
const
FAILURE = "Failure";
}
print
MyClass::SUCCESS;

10. Static members

Classes definitions can now include static members (properties), accessible via the class. Common usage of static members is in the Singleton pattern.

class Singleton {
static private
$instance = NULL;

private function
__construct() {
}

static public function
getInstance() {
if (
self::$instance == NULL) {
self::$instance = new Singleton();
}
return
self::$instance;
}
}

11. Static methods

You can now define methods as static allowing them to be called from non-object context. Static methods don't define the $this variable as they aren't bound to any specific object.

class MyClass {
static function
helloWorld() {
print
"Hello, world";
}
}
MyClass::helloWorld();

?>

12. abstract classes

A class may be declared as abstract so as to prevent it from being instantiated. However, you may inherit from an abstract class.

abstract class MyBaseClass {
function
display() {
print
"Default display routine being called";
}
}

13. abstract methods

A method may be declared as abstract, thereby deferring its definition to an inheriting class. A class that includes abstract methods must be declared as abstract.

abstract class MyBaseClass {
abstract function display();
}

14. Class type hints

Function declarations may include class type hints for their parameters. If the functions are called with an incorrect class type an error occurs.

function expectsMyClass(MyClass $obj) {

}

15. Support for dereferencing objects which are returned from methods.

In PHP 4, you could not directly dereference objects which are returned from methods. You would have to first assign the object to a dummy variable and then dereference it.
PHP 4:

$dummy = $obj->method();
$dummy->method2();

PHP 5:

$obj->method()->method2();

16. Iterators

PHP 5 allows both PHP classes and PHP extension classes to implement an Iterator interface. Once you implement this interface you will be able to iterate instances of the class by using the foreach() language construct.

$obj = new MyIteratorImplementation();
foreach (
$obj as $value) {
print
"$value";
}

For a more complete example, please refer to the "Advanced OOP & Design Patterns" chapter.

17. __autoload()

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class). In PHP 5, this is no longer necessary. You may define an __autoload() function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is giving a last chance to load the class before PHP bails out with an error.

function __autoload($class_name) {
include_once(
$class_name . "php");
}

$obj = new MyClass1();
$obj2 = new MyClass2();

Other New Language Features

1. Exception handling

PHP 5 adds the ability for the well known try/throw/catch structured exception handling paradigm. You are only allowed to throw objects which inherit from the Exception class.

class SQLException extends Exception {
public
$problem;
function
__construct($problem) {
$this->problem = $problem;
}
}

try {
...
throw new SQLException("Couldn't connect to database");
...
}
catch (SQLException $e) {
print
"Caught an SQLException with problem $obj->problem";
}
catch (Exception $e) {
print
"Caught unrecognized exception";
}

Currently for backwards compatibility purposes most internal functions do not throw exceptions. However, new extensions are making use of this capability and you can use it in your own source code. Also, similar to the already existing set_error_handler() you may use set_exception_handler() to catch an unhandled exception before the script terminates.

2. foreach with references

In PHP 4, you could not iterate through an array and modify its values. PHP 5 supports this by allowing you to mark the foreach() loop with the & (reference) sign, thus making any values you change affect the array you're iterating over.

foreach ($array as &$value) {
if (
$value === "NULL") {
$value = NULL;
}
}

3. default values for by-reference parameters

In PHP 4, default values could only be given to parameters which are passed by-value. Giving default values to by-reference parameters is now supported.

function my_func(&$arg = null) {
if (
$arg === NULL) {
print
'$arg is empty';
}
}
my_func();

General PHP changes

XML and Web Services

Following the changes in the language, the XML updates in PHP 5 are most probably the most significant and exciting. The enhanced XML functionality in PHP 5 puts it on par with other web technologies in some areas and overtakes them in others.

The Foundation

XML support in PHP 4 was implemented using a variety of underlying XML libraries. SAX support was implemented using the old Expat library, XSLT was implemented using the Sablotron library (or using libxml2 via the DOM extension) and DOM was implemented using the more powerful libxml2 library by the GNOME project.

Using a variety of libraries did not make PHP 4 excel when it came to XML support. Maintenance was poor, new XML standards weren't always supported, performance wasn't as good as it could have been, and interoperability between the varies XML extensions did not exist.

In PHP 5, all XML extensions have been rewritten to use the superb libxml2 XML toolkit (http://www.xmlsoft.org/). It is a very feature rich, highly maintained and efficient implementation of the XML standards bringing the cutting edge of XML technology to PHP.
All the above mentioned extensions (SAX, DOM and XSLT) now use libxml2 including the new additional extensions SimpleXML and SOAP.

SAX

As mentioned, the new SAX implementation has switched from using Expat to libxml2. Although the new extension should be compatible there may be some small subtle differences. Developers who still want to work with the Expat library can do so by configuring and building PHP accordingly (not recommended).

DOM

Although DOM support in PHP 4 was also based on the libxml2 library, it was quite buggy, had memory leaks and the API in many cases was not W3C compliant. The DOM extension went through a thorough facelift for PHP 5. Not only was the extension mostly rewritten it is now also W3C complaint. For example, function names now use studlyCaps as described by the W3C standard making it easier for you to read general W3C documentation and implementing what you learnt, right away in PHP. In addition, the DOM extension now supports three kinds of schemas for XML validation, DTD, XML Schema and RelaxNG.

As a result of these changes PHP 4 code using DOM will not always run in PHP 5. However, in most cases adjusting the function names to the new standard will probably do the trick.

XSLT

In PHP 4, there were two extensions that supported XSL Transformations. The first was using the Sablotron extension and the second was using the XSLT support in the DOM extension. In PHP 5, a new XSL extension was written and, as mentioned, is based on the libxml2 extension. As in PHP 5, the XSL Transformation does not take the XSLT stylesheet as a parameter but depends on the DOM extension to load it, the stylesheet can be cached in memory and may be applied to many documents saving execution time

SimpleXML

Probably when looking back in a year or two it will be clear that SimpleXML has revolutionized the way PHP developers work with XML files. SimpleXML could really be called "XML for Dummies". Instead of having to deal with DOM or even worse SAX, SimpleXML represents your XML file as a native PHP object. You can read, write or iterate over your XML file with ease accessing elements and attributes.

Consider the following XML file:

<clients>
<
client>
<
name>John Doename>
<
account_number>87234838account_number>
client>
<
client>
<
name>Janet Smithname>
<
account_number>72384329account_number>
client>
clients>

The following piece of code prints each client's name and account number:

$clients = simplexml_load_file('clients.xml');
foreach (
$clients->client as $client) {
print
"$client->name has account number $client->account_number ";
}

It's obvious how simple SimpleXML really is.

And in case there is something advanced you need to do to your SimpleXML object which isn't supported in this lightweight extension, you can convert it to a DOM tree by calling dom_import_simplexml(), manipulate it in DOM and covert it back to SimpleXML using simplexml_import_dom(). Thanks to both extensions using the same underlying XML library switching between these two has been made a reality.

SOAP

Official native SOAP support in PHP 4 was lacking. The most commonly used SOAP implementation was PEAR's but as it was implemented entirely in PHP it could not perform as well as a built-in C extension. Other available C extensions never reached stability and wide adoption and, therefore, were not included in the main PHP 5 distribution.

SOAP support in PHP 5 was completely rewritten as a C extension and, although it was only completed at a very late stage in the beta process, it was incooperated into the default distribution due to its thorough implementation of most of the SOAP standard.

The following calls SomeFunction() defined in a WSDL file:

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);

New MySQLi (MySQL Improved) extension

For PHP 5, MySQL AB (http://www.mysql.com) has written a new MySQL extension that allows you to take full advantage of the new functionality in MySQL 4.1 and later. As opposed to the old MySQL extension, the new one gives you both a functional and an object oriented interface so that you can choose what you prefer. New features supported by this extension include prepared statements and variable binding, SSL and compressed connections, transaction control, replication support and more...

SQLite extension

Support for SQLite (http://www.sqlite.org) was first introduced in the PHP 4.3.x series. It is an embedded SQL library which does not require an SQL server and is very suitable for applications which don't require the scalability of SQL servers or if you're deploying at an ISP who doesn't give you access to an SQL server. Contrary to what its name implies SQLite is very feature rich and supports transactions, sub-selects, views and large DB files. It is mentioned here as a PHP 5 feature because it was introduced so late in the PHP 4 series and as it takes advantage of PHP 5 by providing an object oriented interface and supporting iterators.

Tidy extension

PHP 5 includes support for the useful Tidy (http://tidy.sf.net/) library. It allows PHP developers to parse, diagnose, clean and repair HTML documents. The Tidy extension supports both a functional and an object oriented interface, and it's API uses the PHP 5 exception mechanism.

Perl extension

Although not bundled in the default PHP 5 package, the Perl extension allows you to call Perl scripts, use Perl objects and use other Perl functionality natively from within PHP. This new extension sits within the PECL (PHP Extension Community Library) repository a http://pecl.php.net/package/perl.

Other New Things in PHP 5:

New memory manager

The Zend Engine features a new memory manager. The two main advantages are better support for multi-threaded environments (allocations don't need to do any mutual exclusion locks) and after each request freeing the allocated memory blocks is much more efficient. As this is an underlying infra-structure change you will not notice it directly as the end-user.

Dropped support for Windows 95

Running PHP on the Windows 95 platform is not supported anymore due to it not supporting functionality which PHP uses. As Microsoft has officially stopped supporting it over a year ago the PHP development community decided that this is a wise decision.

Summary

You must surely be impressed by the amount of improvements in PHP 5. As mentioned earlier, this chapter doesn't cover all of the improvements but only the main ones. Other improvements include additional features, a lot of bug fixes and very much improved infrastructure. The following chapters will cover PHP 5 and will give you in-depth coverage of the mentioned new features and others which were omitted.

Javascript Cookies

// JavaScript Document
/**
* Sets a Cookie with the given name and value.
*
* name Name of the cookie
* value Value of the cookie
* [expires] Expiration date of the cookie (default: end of current session)
* [path] Path where the cookie is valid (default: path of calling document)
* [domain] Domain where the cookie is valid
* (default: domain of calling document)
* [secure] Boolean value indicating if the cookie transmission requires a
* secure transmission
*/
function setCookie(name, value, path, domain, secure)
{
var today = new Date();
var expires = new Date(today.getTime() + 150 * 24 * 60 * 60 * 1000);
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}

/**
* Gets the value of the specified cookie.
*
* name Name of the desired cookie.
*
* Returns a string containing value of specified cookie,
* or null if cookie does not exist.
*/
function getCookie(name)
{
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1)
{
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1)
{
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}

/**
* Deletes the specified cookie.
*
* name name of the cookie
* [path] path of the cookie (must be same as path used to create cookie)
* [domain] domain of the cookie (must be same as domain used to create cookie)
*/
function deleteCookie(name, path, domain)
{
if (getCookie(name))
{
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}

PHP Interview Questions

Q:1 What are the differences between Get and post methods in form submitting.
give the case where we can use get and we can use post methods?
A:1

When to use GET or POST

The HTML 2.0 specification says, in section Form
Submission (and the HTML 4.0 specification repeats this with minor
stylistic changes):

–>If the processing of a form is idempotent
(i.e. it has no lasting observable effect on the state of the
world), then the form method should be GET. Many database searches
have no visible side-effects and make ideal applications of query
forms.

–>If the service associated with the processing of a form has side
effects (for example, modification of a database or subscription to
a service), the method should be POST.

How the form data is transmitted?

quotation from the HTML 4.0 specification

–> If the method is “get” - -, the user agent
takes the value of action, appends a ? to it, then appends the form
data set, encoded using the application/x-www-form-urlencoded
content type. The user agent then traverses the link to this URI. In
this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post
transaction using the value of the action attribute and a message
created according to the content type specified by the enctype
attribute.

Quote from CGI FAQ

Firstly, the the HTTP protocol specifies
differing usages for the two methods. GET requests should always be
idempotent on the server. This means that whereas one GET request
might (rarely) change some state on the Server, two or more
identical requests will have no further effect.

This is a theoretical point which is also good
advice in practice. If a user hits “reload” on his/her browser, an
identical request will be sent to the server, potentially resulting
in two identical database or
guestbook entries, counter increments, etc. Browsers may reload a
GET URL automatically, particularly if cacheing is disabled (as is
usually the case with CGI output), but will typically prompt the
user before
re-submitting a POST request. This means you’re far less likely to
get inadvertently-repeated entries from POST.

GET is (in theory) the preferred method for
idempotent operations, such as querying a database, though it
matters little if you’re using a form. There is a further practical
constraint that many systems have built-in limits to the length of a
GET request they can handle: when the total size of a request (URL+params)
approaches or exceeds 1Kb, you are well-advised to use POST in any
case.

I would prefer POST when I don’t want the status to
be change when user resubmits. And GET
when it does not matter.



Q:2 Who is the father of PHP and explain the changes in PHP versions?
A:2 Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3
is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current
generation of PHP, which uses the
Zend engine
under the
hood. PHP 5 uses
Zend engine 2 which,
among other things, offers many additionalOOP features


Q:3 How can we submit a form without a submit button?
A:3 The main idea behind this is to use Java script submit() function in
order to submit the form without explicitly clicking any submit button.
You can attach the document.formname.submit() method to onclick,
onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the
form after xx seconds once the loading is done (can be seen in online
test sites).


Q:4 In how many ways we can retrieve the data in the result set of
MySQL using PHP?
A:4 You can do it by 4 Ways1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc


Q:5 What is the difference between mysql_fetch_object and
mysql_fetch_array?
A:5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference -
an object is returned, instead of an array. Indirectly, that means that
you can only access the data by the field names, and not by their
offsets (numbers are illegal property names).


Q:6 What is the difference between $message and $$message?
A:6 It is a classic example of PHP’s variable variables. take the
following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the
$$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like
this${$message} => $mizanSometimes it is convenient to be able to have variable variable
names. That is, a variable name which can be set and used dynamically.


Q:7 How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP?
A:7 preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);
echo $found[1];


Q:8 How can we create a database using PHP and MySQL?
A:8 We can create MySQL database with the use of
mysql_create_db(“Database Name”)


Q:9 What are the differences between require and include,
include_once and require_once?
A:9

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. include() produces a
Warning while 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.

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.

require_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.



Q:10 Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
A:10 Yes we can use include() more than one time in any page though it is
not a very good practice.


Q:11 What are the different tables present in MySQL, which type of
table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ?
A:11 Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.


Q:12 Functions in IMAP, POP3 AND LDAP?
A:12 You can find these specific information in PHP Manual.


Q:13 How can I execute a PHP script using command line?
A:13 As of version 4.3.0, PHP supports a new SAPI type (Server
Application Programming Interface) named CLI which means Command Line
Interface. Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument. For
example, “php myScript.php”, assuming “php” is the command to invoke the
CLI program.
Be aware that if your PHP script was written for the Web CGI interface,
it may not execute properly in command line environment.


Q:14 Suppose your Zend engine supports the mode Then how can u
configure your PHP Zend engine to support mode ?
A:14 In php.ini file:
set
short_open_tag=on
to make PHP support


Q:15 Shopping cart online validation i.e. how can we configure Paypal,
etc.?
A:15 We can find the detail documentation about different paypal
integration process at the following site


PayPal PHP

SDK : http://www.paypaldev.org



Q:16 What is meant by nl2br()?
A:16 Inserts HTML line breaks (
before all newlines in a string
string nl2br (string); Returns string with ” inserted before all
newlines. For example: echo nl2br(”god bless\n you”) will output “god
bless
you” to your browser.


Q:17 Draw the architecture of Zend engine?
A:17 The Zend Engine is the internal compiler and runtime engine used by
PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an
abbreviation of their names. In the early days of PHP4, it worked as
follows:
The PHP script was loaded by the Zend Engine and compiled into Zend
opcode. Opcodes, short for operation codes, are low level binary
instructions. Then the opcode was executed and the HTML generated sent
to the client. The opcode was flushed from memory after execution.Today, there are a multitude of products and techniques to help you
speed up this process. In the following diagram, we show the how modern
PHP scripts work; all the shaded boxes are optional.
PHP Scripts are loaded into memory and compiled into Zend opcodes.


Q:18 What are the current versions of apache, PHP, and MySQL?
A:18 As of February, 2007 the current versions arePHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4Note: visit www.php.net,

http://dev.mysql.com/downloads/mysql/
,
www.apache.org to get current
versions.


Q:19 What are the reasons for selecting lamp (Linux, apache, MySQL,
PHP) instead of combination of other software programs, servers and
operating systems?
A:19 All of those are open source resource. Security of Linux is very
very more than windows. Apache is a better server that IIS both in
functionality and security. MySQL is world most popular open source
database. PHP is more faster that asp or any other scripting language.


Q:20 How can we encrypt and decrypt a data present in a MySQL table
using MySQL?
A:20 AES_ENCRYPT () and AES_DECRYPT ()


Q:21 How can we encrypt the username and password using PHP?
A:21 The functions in this section perform encryption and decryption, and
compression and uncompression:

encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()


Q:22 What are the features and advantages of object-oriented
programming?
A:22 One of the main advantages of OO programming is its ease of
modification; objects can easily be modified and added to a system there
by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are
also easier for non-technical personnel to understand and easier for
them to participate in the maintenance and enhancement of a system
because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many
objects are standard across systems and can be reused. Components that
manage dates, shipping, shopping carts, etc. can be purchased and easily
modified for a specific system


Q:23 What are the differences between procedure-oriented languages and
object-oriented languages?
A:23 Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can
affect any code that follows it.
If a function is used multiple times in a system (i.e., a piece of code
that manages the date), it is often simply cut and pasted into each
program (i.e., a change log, order function, fulfillment system, etc).
If a date change is needed (i.e., Y2K when the code needed to be changed
to handle four numerical digits instead of two), all these pieces of
code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which
the instructions operates on) are kept separate. Multiple sets of code
can access and modify one set of data. One set of code may rely on data
in multiple places. Multiple sets of code and data are required to work
together. Changes made to any of the code sets and data sets can cause
problems through out the system.Object-Oriented programming takes a radically different approach:Code and data are merged into one indivisible item – an object (the
term “component” has also been used to describe an object.) An object is
an abstraction of a set of real-world things (for example, an object may
be created around “date”) The object would contain all information and
functionality for that thing (A date
object it may contain labels like January, February, Tuesday, Wednesday.
It may contain functionality that manages leap years, determines if it
is a business day or a holiday, etc., See Fig. 1). Ideally, information
about a particular thing should reside in only one place in a system.
The information within an object is encapsulated (or hidden) from the
rest of the system.
A system is composed of multiple objects (i.e., date function, reports,
order processing, etc., See Fig 2). When one object needs information
from another object, a request is sent asking for specific information.
(for example, a report object may need to know what today’s date is and
will send a request to the date object) These requests are called
messages and each object has an interface that manages messages.
OO programming languages include features such as “class”, “instance”,
“inheritance”, and “polymorphism” that increase the power and
flexibility of an object.


Q:24 What is the use of friend function?
A:24 Sometimes a function is best shared among a number of different
classes. Such functions can be declared either as member functions of
one class or as global functions. In either case they can be set to be
friends of other classes, by using a friend specifier in the class that
is admitting them. Such functions can use all attributes of the class
which names them as a friend, as if they were themselves members of that
class.
A friend declaration is essentially a prototype for a member function,
but instead of requiring an implementation with the name of that class
attached by the double colon syntax, a global function or member
function of another class provides the match.


Q:25 What are the differences between public, private, protected,
static, transient, final and volatile?
A:25 Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized.
volatile:
a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.


Q:26 What are the different types of errors in PHP?
A:26 Three are three types of errors:1. Notices: These are trivial,
non-critical errors that PHP encounters while executing a script - for
example, accessing a variable that has not yet been defined. By default,
such errors are not displayed to the user at all - although, as you will
see, you can change this default behavior.2. Warnings: These are more serious errors - for example, attempting
to include() a file which does not exist. By default, these errors are
displayed to the user, but they do not result in script termination.3. Fatal errors: These are critical errors - for example,
instantiating an object of a non-existent class, or calling a
non-existent function. These errors cause the immediate termination of
the script, and PHP’s default behavior is to display them to the user
when they take place.


Q:27 What is the functionality of the function strstr and stristr?
A:27 strstr:

Returns part of haystack
string from the first occurrence of
needle to the end of
haystack.If needle is not found,
returns FALSE.

If needle is not a
string, it is converted to an integer and applied as the
ordinal value of a character.

This function is case-sensitive. For
case-insensitive searches, use
stristr().



Q:28 What are the differences between PHP 3 and PHP 4 and PHP 5?
A:28 Please read the release notes at
http://www.php.net.


Q:29 How can we convert asp pages to PHP pages?
A:29 there are lots of tools available for asp to PHP conversion. you can
search Google for that. the best one is available athttp://asp2php.naken.cc./


Q:30 What is the functionality of the function htmlentities?
A:30 Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities.


Q:31 How can we get second of the current time using date function?
A:31 $second = date(”s”);


Q:32 How can we convert the time zones using PHP?
A:32 By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0
', date(DATE_RFC1123, $stamp) ,'';?>


Q:33 What is meant by urlencode and urldocode?
A:33 URLencode returns a string in which all non-alphanumeric characters
except -_. have been replaced with a percent (%)
sign followed by two hex digits and spaces encoded as plus (+)
signs. It is encoded the same way that the posted data from a WWW form
is encoded, that is the same way as in
application/x-www-form-urlencoded
media type.

urldecode decodes any %##
encoding in the given string.



Q:34 What is the difference between the functions unlink and unset?
A:34 unlink() deletes the given file from the file system.
unset() makes a variable undefined.


Q:35 How can we register the variables into a session?
A:35 $_SESSION[’name’] = “Mizan”;


Q:36 How can we get the properties (size, type, width, height) of an
image using PHP image functions?
A:36 To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t


Q:37 How can we get the browser properties using PHP?
A:37 By using
$_SERVER['HTTP_USER_AGENT']
variable.



Q:38 What is the maximum size of a file that can be uploaded using PHP
and how can we change this?
A:38 By default the maximum size is 2MB. and we can change the following
setup at php.iniupload_max_filesize = 2M


Q:39 How can we increase the execution time of a PHP script?
A:39 by changing the following setup at php.inimax_execution_time = 30
; Maximum execution time of each script, in seconds


Q:40 How can we take a backup of a MySQL table and how can we restore
it. ?
A:40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or
for transferring the data to another SQL server (not necessarily a MySQL
server). The dump will contain SQL statements to create the table and/or
populate the table.
-t, –no-create-info
Don’t write table creation information (the CREATE TABLE statement).
-d, –no-data
Don’t write any row information for the table. This is very useful if
you just want to get a dump of the structure for a table!


Q:41 How can we optimize or increase the speed of a MySQL select
query?
A:41
  • first of all instead of using select * from table1, use select
    column1, column2, column3.. from table1
  • Look for the opportunity to introduce index in the table you are
    querying.
  • use limit keyword if you are looking for any specific number of
    rows from the result set.


Q:42 How many ways can we get the value of current session id?
A:42 session_id() returns the session id for the current session.


Q:43 How can we destroy the session, how can we unset the variable of
a session?
A:43 session_unregister — Unregister a global variable from the current
session
session_unset — Free all session variables


Q:44 How can we destroy the cookie?
A:44 Set the cookie in past.


Q:45 How many ways we can pass the variable through the navigation
between the pages?
A:45
  • GET/QueryString
  • POST


Q:46 What is the difference between ereg_replace() and eregi_replace()?
A:46 eregi_replace() function is identical to ereg_replace() except that
this ignores case distinction when matching alphabetic
characters.eregi_replace() function is identical to ereg_replace()
except that this ignores case distinction when matching alphabetic
characters.


Q:47 What are the different functions in sorting an array?
A:47 Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().


Q:48 How can we know the count/number of elements of an array?
A:48 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)


Q:49 What is the PHP predefined variable that tells the What types of
images that PHP supports?
A:49 Though i am not sure if this is wrong or not, With the exif
extension you are able to work with image meta data.


Q:50 How can I know that a variable is a number or not using a
JavaScript?
A:50 bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.


Q:51 List out some tools through which we can draw E-R diagrams for
mysql.
A:51 Case Studio
Smart Draw


Q:52 How can I retrieve values from one database server and store them
in other database server using PHP?
A:52 we can always fetch from one database and rewrite to another. here
is a nice solution of it.$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);$db2 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);At this point you can only fetch records from you previous ResultSet,
i.e $res1 - But you cannot execute new query in $db1, even if you
supply the link as because the link was overwritten by the new db.so at this point the following script will fail
$res3 = mysql_query(”query”,$db1); //this will failSo how to solve that?

take a look below.
$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);

$db2 = mysql_connect(”host”,”user”,”pwd”, true)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);

So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$db2 with this optional parameter set to ‘true’, so both link will
remain live.

now the following query will execute successfully.
$res3 = mysql_query(”query”,$db1);

Thanks goes to Hasan and Hasin for this solution.



Q:53 List out the predefined classes in PHP?
A:53 Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter


Q:54 How can I make a script that can be bi-language (supports
English, German)?
A:54 You can maintain two separate language file for each of the
language. all the labels are putted in both language files as variables
and assign those variables in the PHP source. on runtime choose the
required language option.


Q:55 What are the difference between abstract class and interface?
A:55 Abstract class: abstract classes are the class where one or more
methods are abstract but not necessarily all method has to be abstract.
Abstract methods are the methods, which are declare in its class but not
define. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods are
abstract. That means all the methods only declared but not defined. All
the methods must be define by its implemented class.


Q:56 How can we send mail using JavaScript?
A:56 JavaScript does not have any networking capabilities as it is
designed to work on client site. As a result we can not send mails using
JavaScript. But we can call the client side mail protocol mailto
via JavaScript to prompt for an email to send. this requires the client
to approve it.


Q:57 How can we repair a MySQL table?
A:57 The syntex for repairing a MySQL table is
REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]
This command will repair the table specified if the quick is given the
MySQL will do a repair of only the index tree if the extended is given
it will create index row by row


Q:58 What are the advantages of stored procedures, triggers, indexes?
A:58 A stored procedure is a set of SQL commands that can be compiled and
stored in the server. Once this has been done, clients don’t need to
keep re-issuing the entire query but can refer to the stored procedure.
This provides better overall performance because the query has to be
parsed only once, and less information needs to be sent between the
server and the client. You can also raise the conceptual level by having
libraries of functions in the server. However, stored procedures of
course do increase the load on the database server system, as more of
the work is done on the server side and less on the client (application)
side.Triggers will also be implemented. A trigger is effectively a type of
stored procedure, one that is invoked when a particular event occurs.
For example, you can install a stored procedure that is triggered each
time a record is deleted from a transaction table and that stored
procedure automatically deletes the corresponding customer from a
customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read
through the entire table to find the relevant rows. The larger the
table, the more this costs. If the table has an index for the columns in
question, MySQL can quickly determine the position to seek to in the
middle of the data file without having to look at all the data. If a
table has 1,000 rows, this is at least 100 times faster than reading
sequentially. If you need to access most of the rows, it is faster to
read sequentially, because this minimizes disk seeks.


Q:59 What is the maximum length of a table name, database name, and
fieldname in MySQL?
A:59 The following table describes the maximum length for each type of
identifier.

Identifier Maximum Length
(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255

There are some restrictions on the characters that may appear in
identifiers:



Q:60 How many values can the SET function of MySQL take?
A:60 MySQL set can take zero or more values but at the maximum it can
take 64 values


Q:61 What are the other commands to know the structure of table using
MySQL commands except explain command?
A:61 describe Table-Name;


Q:62 How many tables will create when we create table, what are they?
A:62 The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,


Q:63 What is the purpose of the following files having extensions 1) .frm
2) .myd 3) .myi? What do these files contain?
A:63 In MySql, the default table type is MyISAM.
Each MyISAM table is stored on disk in three files. The files have names
that begin with the table name and have an extension to indicate the
file type.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,


Q:64 What is maximum size of a database in MySQL?
A:64 If the operating system or filesystem places a limit on the number
of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of
files in a directory can place a practical limit on the number of tables
in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database
performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM
storage engine in MySQL 3.23, the maximum table size was increased to
65536 terabytes (2567 – 1 bytes). With this larger allowed table size,
the maximum effective table size for MySQL databases is usually
determined by operating system constraints on file sizes, not by MySQL
internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
that can be created from several files. This allows a table to exceed
the maximum individual file size. The tablespace can include raw disk
partitions, which allows extremely large tables. The maximum tablespace
size is 64TB.
The following table lists some examples of operating system file-size
limits. This is only a rough guide and is not intended to be definitive.
For the most up-to-date information, be sure to check the documentation
specific to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB


Q:65 Give the syntax of Grant and Revoke commands?
A:65 The generic syntax for grant is as following
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY
[password]
now rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific
database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
password is simply the password of userThe generic syntax for revoke is as following
> REVOKE [rights] on [database/s] FROM [username@hostname]
now rights can be as explained above
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition


Q:66 Explain Normalization concept?
A:66 The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data
from horizontal rows. We want to ensure that there is no duplication of
data in a given row, and that every column stores the least amount of
information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a
horizontal row, Second Normal Form (or 2NF) deals with redundancy of
data in vertical columns. As stated earlier, the normal forms are
progressive, so to achieve Second Normal Form, your tables must already
be in First Normal Form.Third Normal Form

I have a confession to make; I do not often use Third Normal Form. In
Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the table



Q:67 How can we find the number of rows in a table using MySQL?
A:67 Use this for mysql
>SELECT COUNT(*) FROM table_name;


Q:68 How can we find the number of rows in a result set using PHP?
A:68 $result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;


Q:69 How many ways we can we find the current date using MySQL?
A:69 SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()


Q:70 What are the advantages and disadvantages of Cascading Style
Sheets?
A:70 External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be
created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style Sheets

Advantages

Classes can be created for use on multiple tag types in the document.
Selector and grouping methods can be used to apply styles under complex
contexts. No additional downloads necessary to receive style information

Disadvantages

This method can not control styles for multiple documents at once

Inline Styles

Advantages

Useful for small quantities of style definitions. Can override other
style specification methods at the local level so only exceptions need
to be listed in conjunction with other style methods

Disadvantages

Does not distance style information from content (a main goal of
SGML/HTML). Can not control styles for multiple documents at once.
Author can not create or control classes of elements to control multiple
element types within the document. Selector grouping methods can not be
used to create complex element addressing scenarios



Q:71 What type of inheritance that PHP supports?
A:71 In PHP an extended class is always dependent on a single base class,
that is, multiple inheritance is not supported. Classes are extended
using the keyword ‘extends’.


Q:72 What is the difference between Primary Key and
Unique key?
A:72 Primary Key: A column in a table whose values uniquely identify the
rows in the table. A primary key value cannot be NULL.

Unique Key: Unique Keys are used to uniquely identify each row in the
table. There can be one and only one row for each unique key value. So
NULL can be a unique key.There can be only one primary key for a table but there can be more
than one unique for a table.




Q:73
The structure of table view buyers is as follows:

Field Type Null Key Default Extra
user_pri_id int(15)
PRI null auto_increment
userid varchar(10) YES
null

the value of user_pri_id the last row 999 then What will happen in
the following conditions?

Condition1: Delete all the rows and insert another row then.
What is the starting value for this auto incremented field user_pri_id ,
Condition2: Delete the last row(having the field value 999) and
insert another row then. What is the value for this auto incremented
field user_pri_id

A:73 In both cases let the value for auto increment field be n then next
row will have value n+1 i.e. 1000


Q:74 What are the advantages/disadvantages of MySQL and PHP?
A:74 Both of them are open source software (so free of cost), support
cross platform. php is faster then ASP and JSP.


Q:75 What is the difference between GROUP BY and ORDER BY in Sql?
A:75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns
it should sort the result. If two rows will hawe the same value in col1
it will try to sort them according to col2 and so on.GROUP BY
[col1],[col2],…,[coln]; Tels DBMS to group results with same value of
column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
you want to count all items in group, sum all values or view average


Q:76 What is the difference between char and varchar data types?
A:76 Set char to occupy n bytes and it will take n bytes even if u r
storing a value of n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘mizan’, if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if each
char takes a byte. rest 10 bytes will be free.


Q:77 What is the functionality of md5 function in PHP?
A:77 Calculate the md5 hash of a string. The hash is a 32-character
hexadecimal number. I use it to generate keys which I use to identify
users etc. If I add random no techniques to it the md5 generated now
will be totally different for the same string I am using.


Q:78 How can I load data from a text file into a table?
A:78 you can use LOAD DATA INFILE file_name; syntax to load data
from a text file. but you have to make sure thata) data is delimited
b) columns and data matched correctly


Q:79 How can we know the number of days between two given dates using
MySQL?
A:79 SELECT DATEDIFF(’2007-03-07′,’2005-01-01′);


Q:80 How can we know the number of days between two given dates using
PHP?
A:80 $date1 = date(’Y-m-d’);
$date2 = ‘2006-08-15′;
$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);