Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Ebook of php


Published on

Designing Web Applications Using PHP

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Ebook of php

  1. 1. Designing Web Applications Using PHP 1
  2. 2. DisclaimerThe copyright of the content used in the courseware will remain with principle Company 2
  4. 4. CHAPTER -1 Introduction TO HTMLA brief history of HTML HTML was originally developed by Tim Berners-Lee while at CERN, and popularized bythe Mosaicbrowser developed at NCSA. During the course of the 1990s it has blossomed with theexplosive growth of the Web. During this time, HTML has been extended in a number of ways.The Web depends on Web page authors and vendors sharing the same conventions for HTML.This has motivated joint work on specifications for HTML.A brief history of SGMLHTML is an SGML application conforming to International Standard ISO 8879 -- StandardGeneralized Markup Language SGML (defined in [ISO8879]). SGML provides a means fordefining markup languages. The basic idea is to annotate the text of a document with markup tagsthat provide additional information about the document‘s structure and interpretation. A completediscussion of SGMLparsing, e.g. the mapping of a sequence of characters to a sequence of tagsand data, is left to the SGML standard.An SGML application consists of several parts:1. The SGML declaration. The SGML declaration specifies which characters and delimiters may appear in the application.2. The document type definition (DTD). The DTD defines the syntax of markup constructs. The DTD may include additional definitions such as numeric and named character entities.3. A specification that describes the semantics to be ascribed to the markup. This specification also imposes syntax restrictions that cannot be expressed within the DTD.4. Document instances containing data (contents) and markup. Each instance contains a referenceto the DTD to be used to interpret it.HTML syntaxIn this section, we discuss the syntax of HTML elements, attributes, and comments. 4
  5. 5. EntitiesCharacter entity references are numeric or symbolic names for characters that may be included inan HTML document. They are useful when your authoring tools make it difficult or impossible toenter a character you may not enter often. You will see character entities throughout thisdocument; they begin with a "&" sign and end with a semi-colon (;). Some examples include: "&lt;" represents the < sign. "&gt;" represents the > sign. "&quot; represents the " mark. å (in decimal) represents the letter "a" with a small circle above it. И (in decimal) represents the Cyrillic capital letter "I". 水 (in hexadecimal) represents to the Chinese character for water.ElementsAn SGML application defines elements that represent structures or desired behavior. An elementtypically consists of three parts: a start tag, content, and an end tag.An element‘s start tag is written <element-name>, where element-name is the name of theelement. An element‘s end tag is written with a slash before the element name: </element-name>.For example,<pre>The content of the PRE element is preformatted text.</pre>AttributesElements may have associated properties, called attributes, to which authors assign values.Attribute/value pairs appear before the final ">" of an element‘s start tag. Any number of (legal)attribute value pairs, separated by spaces, may appear in an element‘s start tag. They may appearin any order.HTML commentsHTML comments have the following syntax:<!-- this is a comment --><!-- and so is this one,which occupies more than one line -->White space is not permitted between the markup declaration open delimiter("<!") and thecomment open delimiter ("--"), but is permitted between the comment close delimiter ("--") andthe markup declaration close delimiter (">"). A common error is to include a string of hyphens ("-- 5
  6. 6. -") within a comment. Authors should avoid putting two or more adjacent hyphens insidecomments.List of Elements<A attribute=”…”>…</A> Anchor is a container element that is use to create a Hyperlink.Attributes HREF = ‖…‖ Specifies the URL of the document to be linked To. HREF = ‖…‖ Specifies the name of the anchor you are Created TARGET = ‖…‖ Specifies which window the link will be loaded into.The target can be a name of a frame that you specified in the FRAME tag.<LI attribute> Used to mark text as a list item in any of the following list type <OL> or <UL><OL Attribute></OL> Puts the enclosed items marked with <LI>, in a numbered list.Attributes TYPE =‖…‖ Specifies the type of numbering to be used to for labeling items. Possible values are : A,a,I,I,1. START =‖…‖ Specifies the starting value for the numbering sequence.<UL attributes></UL> Puts the enclosed items marked with <LI>, in a bulleted list.Attributes TYPE = ‖…‖ Specifies the type of bullet used to label the item Possible values are : DISC,CIRCLE,SQUARE.<FRAMESET attributes=”…”></FRAMESET> Define the set of frames that will make up the page.The FRAMES and NOFRAMES tags goinside this. The FRAMESET tag is used instead of the BODY tag. 6
  7. 7. Attributes BORDER =‖…‖ Specifies the width (in pixels) of the border drawn around the frame. COLS =‖….‖ Creates the frames as columns and specifies the width of each column. ROWS =‖…‖ Creates the frames as rows and specifies the width of each row. SCROLLING =‖…‖ Determines whether or not scroll bars are displayed on all the frames. Possible values are ―yes‖, ‖no‖, and ―auto‖.<FRAME attribute1=”…”>Define the source document that should be placed within a frameset. Attributes BORDER = ‖…‖ Specifies the width (in pixel) of the border drawn around the frame. NAME = ‖…‖ Defines a name for frame. SCROLLING = ‖…‖ Specifies if the frame with scrollbar or not. Possible values are ―yes‖, ‖no‖, and ―auto‖. SRC = ‖…‖ Specifies the source file for frame.<TABLE attribute1=”…”></Table>Creates a table that can include any number of row and column. Attributes BORDER = ‖…‖ Specifies the width of the border around the table. If set to 0, there will be no border. BACKGROUND = ‖…‖ Specifies the image that is to be tiled as the background image . BGCOLOR = ‖…‖ Specifies the background color of the table. BORDERCOLOR = ‖…‖ Specifies the border color of the table. WIDTH = ‖…‖ Specifies the width of the table on the page. CELLSPACING =‖…‖ Specifies the amount of the space between the cell in the table CELLPADDING =‖…‖ Specifies the amount the space between the edges of the cell and the text inside.<CAPTION attribute1=”…”></CAPTION>Specifies the caption of the table. 7
  8. 8. AttributesALIGN = ”…” Specifies the position of the caption. Possible values are LEFT,RIGHT,BOTTOM, or TOP<TR Attributes =”…”</TR>Specifies a table row. It can enclose the table heading and table data. Attributes ALIGN = ‖…‖ Specifies the horizontal alignment of the row contents. Possible values are LEF, RIGHT and CENTER. ROWSPAN = ‖…‖Specifies the number of rows the cell will span.<TH Attribute1=”...”>…</TH> Specifies heading to a cellAttributes ALIGN =‖…‖ Specifies the horizontal alignment of the cell contents possible values are LEFT, RIGHT and CENTER.<TD Attribute1=”…”>TR Thease go inside the tags and they define the data in a cell. End tag may be used.Attributes BACKGROUND = ‖…‖ Specifies the address of the image to be tiled as background BGCOLOR = ‖…‖ Specifies the background color for the individual cell . ALIGN = ‖…‖ Specifies the horizontal alignment of the cell contents . Possible values are LEFT, RIGHT and CENTER. COLLSPAN = ‖…‖ Specifies the number of columns the cell will span . WIDTH = ‖…‖ Specifies the width of the cell . HEIGHT = ‖…‖ Specifies the height of the cell .<FORM Attribute1=”…”>….</Form> Specifies a form. Form can be used to send user input to the server in the form of NAME/VALUE pair.Attributes ACTION = ‖…‖ Specifies the address to be used in carrying out the action of the form, usually the address of the CGI file. You can also specifies a mailto address to have the contents of the form emailed to you 8
  9. 9. instead of passed to the server. METHOD = ‖…‖ Post and get method are both used for sending data from the form to the backend. The only difference being POST sends the data independent of the URL of the target whereas GET Send along with the URL itself. TARGET =‖…‖ Specifies which window the result of the form will be loaded. The target can be the name of a frame that you specify in the FRAME tag or one of the following<INPUT Attribute1=”…”> Specifies a control or input are for a form which a NAME/VALUE pair will be returned tothe server.AttributesALIGN = ‖…‖ If the TYPE is IMAGE then this Specifies the alignment of the surrounding text with the image possible values are TOP,MIDDLE, BOTTOM, LEFT, or RIGHT.CHECKED = ‖…‖ Use this attribute with RADIO of CHECKBOX, and it will be pre- Selected when the form loads.MAXLENGTH = ‖…‖ Specifies the maximum number of characters that can be entered in a text input area.NAME = ‖….‖ Specifies the name of the control or input area.0 (part of the NAME/VALUE pair).SIZE = ‖….‖ Specifies the size of the text entry area that is displayed by the browser.SRC = ‖….‖ If the TYPE is image, then this Specifies the address of the image to be used.TYPE = ‖…‖ Specifies the type of control being use. Possible TypesCHECKBOX Creates a checkbox. If the user checks it, the corresponding name/value pair is sent to the server.IMAGE 9
  10. 10. Like the SUBMIT Type, you can have the form sent immediately when the user clicks on animage. Along with the normal information ,when a form is submitted by clicking on animage, the coordinates of the clicked point (measured in pixels from the upper-left cornerof the image) are also sent. The X-coordinates is submitted with a ―x‖ appended to the nameand the y-coordinates has a ―y‖ appended to the name.PASSWORD Creates a single line entry text box just like the text type, however, user input is not echoed on the screen. RADIO Creates a radio list of alternatives of which only one can be selected. Each alternative must have the same name, but different values can be assigned to each. RESET Creates a 3-D button that clears the entire form to original values when clicked. You can Give the button a name by using the VALUE attribute. SUBMIT Creates a 3-D button that submits the form when clicked. You can give the button a name by using the VALUE attribute. TEXT Creates a single line text entry box. You can specifies the size of the text box by using the size attributes . <SELECT Attribute1=”…” ></SELECT> Creates a drop-down list of items. The OPTION tag placed inside opening andclosing SELECT tags define the list items.Attributes MULTIPLE Specifies that multiple items may be selected. NAME = ‖…‖ Specifies the name of the list. SIZE = ‖…‖ Specifies how many items should be visible. 10
  11. 11. <OPTION value=”…”> item Specifies an item in the drop down list. Placed within the opening and closing select tags. Any text following the option tag is what the user will see in the list. Attributes VALUE = ‖…‖ Specifies the value to be returned(part of the NAME/VALUE pair). SELECTED This item will be highlighted when the page loads.<TEXTAREA Attribute1=”…”>…</TEXTAREA> Creates a multi-lined text entry box. Any text placed in between the tags is used as thedefault text string that is displayed when the page is loaded. Attributes COLS = ‖…‖ Specifies how wide the text box will be. ROWS = ‖…‖ Specifies how high the text box will be. NAME = ‖…‖ Specifies the name of the text box for use by the program that is processing the form. WRAP = ‖…‖ Specifies how text will wrap. Possible values are ―HARD‖, ―SOFT‖ or ―NONE‖.<B>…</B> Bold faces the enclosed text.<BIG>…</BIG> Makes the enclosed text one size larger .<BLINK>…</BLINK> Makes the enclosed text blink continually.<BR> Inserts a line break.<CENTER>…</CENTER> Center the enclosed elements. This tag will center everything including images, text, Tables , forms, etc.<DIV ALIGN=”…”>…</DIV> Specifies the alignment of the enclosed elements. Can be used to divide a document intosections that are aligned differently. In future browsers, more attributes will probably be supported.Attributes 11
  12. 12. ALIGN = ‖…‖ Sets the alignment of the division. Possible values are ―Center‖, ―right‖, or ―left‖.<FONT attribute=””>……..</Font> Sets the font properties for the enclosed text. Attributes SIZE = ‖…‖ Sets the size of the font to any number between 1 and 7 with 3 being default. Relative sizes also words e.g. SIZE=+2 COLOR = ‖…‖ Specifies the color of the font. FACE = ‖…‖ Specifies the face of the font. A list can be defined (separated by commas) and the browser will use the first one available of that computer.<HR attirbute1=”…”> Inserts a horizontal line Attributes SIZE = ‖…‖ Specifies the thickness of the line. COLOR = ‖…‖ Specifies the color of the line . WIDTH =‖….‖ Specifies the length of the line as percentage of the screen e.g. WIDTH=90% ALIGN = ‖…‖ Specifies the alignment of the file. RIGHT, LEFT or CENTER. NOSHADE The line is drawn Solid.<l>…..</I> The enclosed text is ITALIC.<U>…..</U> The enclosed text is Underline<P attribute>…..</P> Designates the enclosed text as a plain paragraph . The end tag is optional Attributes ALIGN = ‖….‖ Specifies the alignment for the paragraph. Possible values are ―center‖, ―right‖, ―left‖ .<PRE>…..</PRE> Displays text in fixed-width type without collapsing spaces.<SUP>…..</SUP> Renders the enclosed text in superscript .<SUB>…..</SUB> Renders the enclosed text in subscript . 12
  13. 13. CHAPTER -2 Introduction To Cascading Style SheetAn introduction to Cascading Style Sheets CSS is the acronym for: ‗Cascading Style Sheets‘. CSS is an extension to basic HTML thatallows you to style your web pagesSTYLE SHEETS Details With HTMLTEXT PROPERTIES PROPERTY DESCRIPTION VALUES EXAMPLES Text-transform The case of the text is set capitalize P{text-transform: capitalize uppercase H1{text-transform: lowercase uppercase} none Text-align Aligns the contents Left H4{ text – align : center} horizontally across this page Right Center Justify Text-indent Indents the text in XX units XX units P{text-height: 7em} the paragraph by the specified number of characters. X Line-height Specifies the height of the XX units P{line-height: 12pt} text along with the line space above the line and below the line Word-spacing Specifies the space between XX units P{word-spacing:4pt} the words Letter-spacing Specifies the space between XX units P{letter-spacing:1pt} the characters Text-decoration Specifies the formatting for Underline H1{text-decoration: the text. overline underline} line-through Blink None 13
  14. 14. FONT PROPERTIES PROPERTY DESCRIPTION VALUES EXAMPLES Font-family Specifies the name of the Family Name P{font-family : Comic font to be applied Sans MS} Font-style Specifies the style of the Normal H2{font-family:Comic text to be displayed Italic MS, font- style:italic} Oblique Font-weight Specifies the weight of Lighter P{font-weight:bold} boldness of the font . Normal Bold Bolder 100-900 Font-Size Specifies the size of the XX units P{font-size:12pt} fontClassification Properties PROPERTY DESCRIPTION VALUES EXAMPLES List-style-type Specifies the symbol Disc Ul{list-style-type:upeer-alpha} that appears in front Circle Square of a list item. Decimal Lower- roman Upper- roman Alpha Upper-alpha List-style- image Specifies the Image to url(URL name) image:url(../images/smiley.gif} Server as a bullet for list items. 14
  15. 15. List-style- Specifies the position of Inside Ul{list-style-position: outside} position the bullet that appears outside ul { list-style-position: inside} in the list itemColor And Background Properties Property Description Value Example Color Specifies Color Hex P {color: red} name value rgb P{color:#fffffff} (R%,G%,B%) p {color:10%,20%,20%} rgb(R , G, B) P{color:255,200,0} Background- color Specifies the Color name hex H1 {background-color: green} background value color rgb(R%,G%,B%) rgb(R,G,B) Background- Specifies the url(URLname) Body {background-image: image background url(..image/sand.gif)} image. Background- repeat Specifies how Repeat Body {background- background repeat-x image:url(..images/sand.gif); image will be repeat-y placed. no-repeat Background- Specifies if the Scroll Body {background- image: attachment image is fixed Fixed url(../images/sand.gif); or will it also background-attachment: fixed} move. Background- Specifies the Vertical % Body{background-image: position position of the horiZontal % url(…images/sand.gif); background top,center background position:center} image. bottom,left, right 15
  16. 16. Placement Properties PROPERTIES DESCRIPTION VALUE EXAMPLE Margi-top Specifies the position of XX units % auto Div {margin-top: 2em} the text in the page. Margin-bottom Specifies the bottom XX units % auto Div {margin-bottom: 10%} margin of the text. Margin-left Specifies the left XX units % auto Div {margin-left : 6em} margin of the text. Margin-right Specifies the right XX units % auto Div {margin-left: 1em} margin of the text. Border-style Set the style of the Dotted Table {border-style: dashed} element‘s border solid double groove ridge inset outset Border-color Sets the color of the Color name Table {border-color: red} element‘s border. hex value rgb(R%, G%,B%) rgb(R,G,B) Border Sets the width color, Width Table {border: thick double border-top and style of the border value style red} Table border-bottom simultaneously. value color {border {border-top: border-left value thin dashed red } border-right 16
  17. 17. CHAPTER- 3 Introduction TO PHPWhat is PHP? PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Sourcegeneral-purpose scripting language that is especially suited for Web development and can beembedded into HTML.Example 1.1. An introductory example<html> <head> <title>My First PHP Application</title> </head> <body> <?php echo "Hi, Im a PHP script!"; ?> </body></html>What can PHP do? Anything. PHP is mainly focused on server-side scripting, so you can do anything otherCGI program can do, such as collect form data, generate dynamic page content, or send and receivecookies. But PHP can do much more.There are three main areas where PHP scripts are used:Server-side scripting : This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information. 17
  18. 18. Command line scripting : You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on unix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.Writing desktop applications : PHP is probably not the very best language to create a desktop application with a graphicaluser interface, but if you know PHP very well, and would like to use some advanced PHP featuresin your client-side applications you can also use PHP-GTK to write such programs. You also havethe ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, notavailable in the main distribution. If you are interested in PHP-GTK, visit its own website.PHP can be used on all major operating systems, including Linux, many Unix variants (includingHP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others.PHP has also support for most of the web servers today. This includes Apache, Microsoft InternetInformation Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server,Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has amodule, for the others supporting the CGI standard, PHP can work as a CGI processor. So withPHP, you have the freedom of choosing an operating system and a web server. Furthermore, youalso have the choice of using procedural programming or object oriented programming, or amixture of them. Although not every standard OOP feature is implemented in PHP 4, many codelibraries and large applications (including the PEAR library) are written only using OOP code.What do I need? In this tutorial we assume that your server has activated support for PHP and that all filesending in .php are handled by PHP. On most servers, this is the default extension for PHP files,but ask your server administrator to be sure. If your server supports PHP, then you do not need todo anything. Just create your .php files, put them in your web directory and the server willautomatically parse them for you. There is no need to compile anything nor do you need to installany extra tools. Think of these PHP-enabled files as simple HTML files with a whole newfamily of magical tags that let you do all sorts of things. Most web hosts offer PHP support, but ifyour host does not, consider reading the » PHP Links section for resources on finding PHPenabled web hosts. Let us say you want to save precious bandwidth and develop locally. In thiscase, you will want to install a web server, such as » Apache, and of course » PHP.You will most likely want to install a database as well, such as » MySQL. 18
  19. 19. You can either install these individually or choose a simpler way. Our manual hasinstallation instructions for PHP (assuming you already have some web server set up). In case youhave problems with installing PHP yourself, we would suggest you ask your questions on our »installation mailing list. If you choose to go on the simpler route, then » locate a pre-configuredpackage for your operating system, which automatically installs all of these with just a few mouseclicks. It is easy to setup a web server with PHP support on any operating system, includingMacOSX, Linux and Windows. On Linux, you may find » rpmfind and » PBone helpful forlocating RPMs. You may also want to visit » apt-get to find packages for Debian.History of PHPPHP/FI PHP succeeds an older product, named PHP/FI. PHP/FI was created by RasmusLerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume.He named this set of scripts Personal Home Page Tools. As more functionality was required,Rasmus wrote a much larger C implementation, which was able to communicate with databases,and enabled users to develop simple dynamic Web applications. Rasmus chose to » release thesource code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs init and improve the code.PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basicfunctionality of PHP as we know it today. It had Perl-like variables, automatic interpretation ofform variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeitmuch more limited, simple, and somewhat inconsistent.By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousandusers around the world (estimated), with approximately 50,000 domains reporting as having itinstalled, accounting for about 1% of the domains on the Internet. While there were several peoplecontributing bits of code to this project, it was still at large a one-man project. PHP/FI 2.0 wasofficially released only in November 1997, after spending most of its life in beta releases. It wasshortly afterwards succeeded by the first alphas of PHP 3.0.PHP 3 PHP 3.0 was the first version that closely resembles PHP as we know it today. Itwas created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found 19
  20. 20. PHP/FI 2.0 severely underpowered for developing an eCommerce application they were workingon for a University project. In an effort to cooperate and start building upon PHP/FIs existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successorof PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted.One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition toproviding end users with a solid infrastructure for lots of different databases, protocols and APIs,PHP 3.0s extensibility features attracted dozens of developers to join in and submit new extensionmodules. Arguably, this was the key to PHP 3.0s tremendous success. Other key featuresintroduced in PHP 3.0 were the object oriented syntax support and the much more powerful andconsistent language syntax. The whole new language was released under a new name, that removedthe implication of limited personal use that the PHP/FI 2.0 name held. It was named plain PHP,with the meaning being a recursive acronym - PHP: Hypertext Preprocessor.By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) andhundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed onapproximately 10% of the Web servers on the Internet.PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.PHP 4 By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans andZeev Suraski had begun working on a rewrite of PHPs core. The design goals were to improveperformance of complex applications, and improve the modularity of PHPs code base. Suchapplications were made possible by PHP 3.0s new features and support for a wide variety of thirdparty databases and APIs, but PHP 3.0 was not designed to handle such complex applicationsefficiently.The new engine, dubbed Zend Engine (comprised of their first names, Zeev and Andi ), metthese design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on thisengine, and coupled with a wide range of additional new features, was officially released in May2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improvedperformance of this version, PHP 4.0 included other key features such as support for many moreWeb servers, HTTP sessions, output buffering, more secure ways of handling user input andseveral new language constructs. 20
  21. 21. Today, PHP is being used by hundreds of thousands of developers (estimated), and several millionsites report as having it installed, which accounts for over 20% of the domains on the Internet.PHPs development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.PHP 5 PHP 5 was released in July 2004 after long development and several pre-releases. It ismainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other newfeatures.Your first PHP-enabled page Create a file named hello.php and put it in your web servers root directory( DOCUMENT_ROOT ) with the following content:Example : Our first PHP script: hello.php <html> <head> <title>PHP Test</title> </head> <body> <?php echo <p>Hello World</p>; ?> </body> </html>Use your browser to access the file with your web servers URL, ending with the "/hello.php" filereference. When developing locally this URL will be something like http://localhost/hello.php orhttp:// but this depends on the web servers configuration. If everything isconfigured correctly, this file will be parsed by PHP and the following output will be sent to yourbrowser:<html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p> 21
  22. 22. </body></html>This program is extremely simple and you really did not need to use PHP to create a page like this.All it does is display: Hello World using the PHP echo() statement. Note that the file does notneed to be executable or special in any way. The server finds out that this file needs to beinterpreted by PHP because you used the ".php" extension, which the server is configured to passon to PHP. Think of this as a normal HTML file which happens to have a set of special tagsavailable to you that do a lot of interesting things.If you tried this example and it did not output anything, it prompted for download, or you see thewhole file as text, chances are that the server you are on does not have PHP enabled, or is notconfigured properly. Ask your administrator to enable it for you using the Installation chapter of themanual. If you are developing locally, also read the installation chapter to make sure everything isconfigured properly. Make sure that you access the file via http with the server providing you theoutput. If you just call up the file from your file system, then it will not be parsed by PHP. If theproblems persist anyway, do not hesitate to use one of the many » PHP support options. The pointof the example is to show the special PHP tag format. In this example we used <?php to indicatethe start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closingtag, ?> . You may jump in and out of PHP mode in an HTML file like this anywhere you want.For more details, read the manual section on the basic PHP syntax.A Note on Line Feeds: Line feeds have little meaning in HTML, however it is still a good idea to make yourHTML look nice and clean by putting line feeds in. A linefeed that follows immediately after aclosing ?> will be removed by PHP. This can be extremely useful when you are putting in manyblocks of PHP or include files containing PHP that arent supposed to output anything. At the sametime it can be a bit confusing. You can put a space after the closing ?> to force a space and a linefeed to be output, or you can put an explicit line feed in the last echo/print from within your PHPblock.A Note on Text Editors: There are many text editors and Integrated Development Environments (IDEs) that you canuse to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP EditorsList. If you wish to recommend an editor, please visit the above page and ask the page maintainerto add the editor to the list. Having an editor with syntax highlighting can be helpful. 22
  23. 23. A Note on Word Processors: Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimalfor editing PHP files. If you wish to use one for this test script, you must ensure that you save thefile as plain text or PHP will not be able to read and execute the script.A Note on Windows Notepad: If you are writing your PHP scripts using Windows Notepad, you will need to ensure thatyour files are saved with the .php extension. (Notepad adds a .txt extension to files automaticallyunless you take one of the following steps to prevent it.) When you save the file and are promptedto provide a name for the file, place the filename in quotes (i.e. " hello.php "). Alternatively, youcan click on the Text Documents drop-down menu in the Save dialog box and change the settingto "All Files". You can then enter your filename without quotes.Now that you have successfullycreated a working PHP script, it is time to create the most famous PHP script! Make a call to thephpinfo() function and you will see a lot of useful information about your system and setup such asavailable predefined variables, loaded PHP modules, and configuration settings. Take some timeand review this important information 23
  24. 24. CHAPTER- 4 Variables And Input OutputVariables Variables in PHP are quite different from compiled languages such as C and Java. This isbecause their weakly typed nature, which in short means you doesn‘t need to declare variablesbefore using them, you don‘t need to declare their type and, as a result, a variable can change thetype of its value as much as you want. Variables in PHP are preceded with a $ sign, and similar tomost modern languages, they can start with a letter (A-Za-z) or (underscore) and can then containas many alphanumeric characters and underscores as you like.Examples of legal variable names  $count  $_Obj  $A123Example of illegal variable names  $123  $*ABCAs previously mentioned,you don‘t need to declare variables or their type before using them inPHP.The following code example uses variables:  $PI = 3.14;  $radius = 5;  $circumference = $PI * 2 * $radius;You can see that none of the variables are declared before they are used.Also, the fact that $PI is afloating-point number, and $radius (an integer) is not declared before they are initialized. PHP doesnot support global variables like many other programming languages (except for some special pre-defined variables, which we discuss later). Variables are local to their scope, and if created in afunction, they are only available for the lifetime of the function. Variables that are created in themain script (not within a function) aren‘t global variables; you cannot see.Indirect References to Variables An extremely useful feature of PHP is that you can access variables by using indirectreferences, or to put it simply, you can create and access variables byname at runtime. 24
  25. 25. Consider the following example: $name = "John"; $$name = "Registered user"; print $John; This code results in the printing of "Registered user."The bold line uses an additional $ to access the variable with name specified by the value of$name("John") and changing its value to "Registered user".Therefore, a variable called $John is created.You can use as many levels of indirections as you want by adding additional $signs in front of avariable.Managing VariablesThree language constructs are used to manage variables. They enable you to check if certainvariables exist, remove variables, and check variables‘ truth values.  Isset : Determine whether a variable is set 1. Cheack ing an variable if (isset($first_name)) { print $first_name is set; } 2. Checking an array element if (isset($arr["offset"])) { ... } 3. Checking an object property if (isset($obj->property)) { ... }  Unset :Unset a given variable 1. destroy a single variable <?php unset($var); ?> 2. destroy a single element of an array <?php unset($arr[quux]); ?> 3. destroy more than one variable <?php unset($foo1, $foo2, $foo3); ?>  empty : Determine whether a variable is empty 25
  26. 26. SuperglobalsPHP does not support global variables (variables that can automatically be accessed from anyscope). However, certain special internal variables behave like global variables similar to otherlanguages. These variables are called superglobals and are predefined by PHP for you to use.Some examples of these superglobals are $_GET[ ] An array that includes all the GET variables that PHP received from the client browser. $_POST[ ] An array that includes all the POST variables that PHP received from the client browser. $_COOKIE[ ] An array that includes all the cookies that PHP received from the client browser. $_ENV[ ] An array with the environment variables. $_SERVER[ ] An array with the values of the web-server variables.Basic Data Types Eight different data types exist in PHP, five of which are scalar and each of the remainingthree has its own uniqueness. The previously discussed variables can contain values of any ofthese data types without explicitly declaring their type. The variable ―behaves‖ according to thedata type it contains.These Data Types are 1. Booleans 2. Integers 3. Floating point numbers 4. Strings 5. Arrays 6. Objects 7. Resources 8. NULLBooleansThis is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE .Note: The boolean type was introduced in PHP 4.To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive. <?php $foo = True; // assign the value TRUE to $foo ?> 26
  27. 27. Usually you use some kind of operator which returns a boolean value, and then pass it on to acontrol structure. <?php // == is an operator which test equality and returns a boolean if ($action == "show_version") { echo "The version is 1.23"; } // this is not necessary... if ($show_separators == TRUE) { echo "<hr><br>"; } // ...because you can simply type if ($show_separators) { echo "<hr><br>"; } ?>Integers An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.Integers can be specified in decimal (10-based), hexadecimal (16-based) octal (8-based) notationoptionally preceded by a sign (- or +).If you use the octal notation, you must precede the numberwith a 0 (zero), to use hexadecimal notation precede the number with 0x .Example Integer literals <?php $a = 1234; // decimal number $a = -123; // a negative number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) ?> 27
  28. 28. Floating point numbersFloating point numbers (also known as "floats", "doubles", or "real numbers") can be specifiedusing any of the following syntaxes: <?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?>Strings A string is series of characters.Arrays An array in PHP is actually an ordered map. A map is a type that associates values to keys.Objects To create a new object, use the new statement to instantiate a class .Resources A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.Null The special NULL value represents that a variable has no value. NULL is the only possiblevalue of type NULL. A variable is considered to be NULL if it has been assigned the constant NULL. it has not been set to any value yet. it has been unset().Syntax: There is only one value of type NULL, and that is the case-insensitive keyword NULL. <?php $var = NULL; ?>Note: The null type was introduced in PHP 4. 0 28
  29. 29. Basic Output Construct Echo() and print() are basic output function used in PHP. Both Have little Difference Whichis Echo ExampleEcho “This is my Printing line” . ”I will Learn It” ;OrEcho(“This is my Printing Line”);Note: Difference Is that Second Version of echo can‘t Except More than One parameter‘s.Print Exampleprint(“This is my printing line”);Orprint(“This is my printing line” . ”Parse Error”);Difference Between Echo And Print ()• Unlike echo, print can accept only one argument.• Unlike ehco , print return a value, which represents whether the print statement succeeded. 29
  30. 30. CHAPTER- 5 OperatorsUnary Operator Incrementing/Decrementing Operators PHP supports C-style pre- and post-increment and decrement operators.Note: The increment/decrement operators do not affect boolean values.Decrementing NULL values has no effect too, but incrementing them results in 1 .Increment/decrement Operators Example Name Effect ++$a Pre-increment Increments $a by one, then returns $a. $a++ Post-increment Returns $a, then increments $a by one. --$a Pre-decrement Decrements $a by one, then returns $a. $a-- Post-decrement Returns $a, then decrements $a by one.Heres a simple example script:<?php echo "<h3>Post increment</h3>"; $a = 5; echo "Should be 5: " . $a++ . "<br />"; echo "Should be 6: " . $a . "<br />"; echo "<h3>Pre increment</h3>"; $a = 5; echo "Should be 6: " . ++$a . "<br />"; echo "Should be 6: " . $a . "<br />"; echo "<h3>Post decrement</h3>"; $a = 5; echo "Should be 5: " . $a-- . "<br />"; echo "Should be 4: " . $a . "<br />"; echo "<h3>Pre decrement</h3>"; $a = 5; echo "Should be 4: " . --$a . "<br />"; echo "Should be 4: " . $a . "<br />";?> 30
  31. 31. PHP follows Perls convention when dealing with arithmetic operations on character variables andnot Cs. For example, in Perl Z+1 turns into AA, while in C Z+1 turns into [ ( ord(Z) == 90,ord([) == 91 ). Note that character variables can be incremented but not decremented and even soonly plain ASCII characters (a-z and A-Z) are supported.Example . Arithmetic Operations on Character Variables <?php $i = W; for ($n=0; $n<6; $n++) { echo ++$i . "<br/>"; } ?>The above example will output: X Y Z AA AB ACBinary Operator Binary operators are used on two operands: 2+3 14 * 3.1415 $i – 1These examples are also simple examples of expressions. PHP can only perform binary operationson two operands that have the same type. However, if the two operands have different types, PHPautomatically converts one of them to the other‘s type, according to the following rules (unlessstated differently, such as in the concatenation operator).Type of One of the Operands Type of the Other Operand Conversion PerformedInteger Floating point The integer operand is converted to a floating point number.Integer String The string is converted to a number. If the converted. string‘s 31
  32. 32. type is real, the integer operand is converted to a real as well.Real String The sting is converted to a real.Booleans, nulls, and resources behave like integers, and they convert in the following manner:Boolean: False = 0, True = 1Null = 0Resource = The resource‘s # (id)Binary Operators Numeric Operators All the binary operators (except for the concatenation operator) workonly on numeric operands. If one or both of the operand share strings, Booleans, nulls, or resources,they are automatically converted to their numeric equivalents before the calculation is performed(according to the previous table). Operator Name Value+ Addition The sum of the two operands.- Subtraction The difference between the two operands* Multiplcation The product of the two operands.Concatenation Operator (.) The concatenation operator concatenate two strings. This operator works onlyon strings; thus, any non-string operand is first converted to one.The following example would print out "The year is 2011": <?php $year = 2011; print "The year is " . $year; ?>The integer $year is internally converted to the string "2011" before it is concatenated with thestring‘s prefix, "The year is". 32
  33. 33. Assignment Operators Assignment Operators enable you to write a value to a variable. The first Operand (the one on the left of the assignment operator or l value) must be a variable . The value of an assignment is the final value assigned to the variable.For example: The expression $var = 5 has the value 5 (and assigns 5 to $var).In addition to the regular assignment operator =, several other assignment operators are compositesof an operator followed by an equal sign. These composite operators apply the operator taking thevariable on the left as the first operand and the value on the right (the r value) as the secondoperand, and assign the result of the operation to the variable on the left.For example: $counter += 2; // This is identical to $counter = $counter + 2; $offset *= $counter ; // This is identical to $offset = $offset * $counter; The following list show the valid composite assignment operators: +=, -=, *=, /=, %=,By-Reference Assignment Operator PHP enables you to create variables as aliases for other variables. You can achieve this byusing the by-reference assignment operator =&. After a variable aliases another variable, changesto either one of them affects the other.For example: $name = "Judy"; $name_alias =& $name; $name_alias = "Jonathan"; print $name; The result of this example is JonathanWhen returning a variable by-reference from a function (covered later in this book), you also needto use the assign by-reference operator to assign the returned variable to a variable:$retval =& func_that_returns_by_reference();Comparison Operators Comparison operators, as their name implies, allow you to compare two values. You may 33
  34. 34. also be interested in viewing the type comparison tables, as they show examples of various typerelated comparisons. Example Name Result $a == $b Equal TRUE if $a is equal to $b. $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4) $a != $b Not equal TRUE if $a is not equal to $b. $a <> $b Not equal TRUE if $a is not equal to $b. $a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the Same type. (introduced in PHP 4) $a < $b Less than TRUE if $a is strictly less than $b. $a > $b Greater than TRUE if $a is strictly greater than $b. $a <= $b Less than or equal to TRUE if $a is less than or equal to $b. $a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.Comparison Operators If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement. <?php var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true var_dump("1" == "1e0"); // 1 == 1 -> true switch ("a") { case 0: echo "0"; break; case "a": // never reached because "a" is already matched with 0 echo "a"; break; } ?> 34
  35. 35. Logical Operators Example Name Result $a and $b And TRUE if both $a and $b are TRUE $a or $b Or TRUE if either $a or $b is TRUE $a xor $b Xor TRUE if either $a or $b is TRUE, but not both. ! $a Not TRUE if $a is not TRUE. $a && $b And TRUE if both $a and $b are TRUE $a || $b Or TRUE if either $a or $b is TRUEThe reason for the two different variations of "and" and "or" operators is that theyoperate at different precedences. (See Operator Precedence.)Example: Logical operators illustrated<?php // foo() will never get called as those operators are short-circuit $a = (false && foo()); $b = (true || foo()); $c = (false and foo()); $d = (true or foo()); // "||" has a greater precedence than "or" $e = false || true; // $e will be assigned to (false || true) which is true $f = false or true; // $f will be assigned to false var_dump($e, $f); // "&&" has a greater precedence than "and" $g = true && false; // $g will be assigned to (true && false) which is false $h = true and false; // $h will be assigned to true var_dump($g, $h);?> 35
  36. 36. CHAPTER- 6 Selection ConstructsIF Statements If statements are the most common conditional constructs, and they exist in mostprogramming languages. The expression in the if statement is referred to as theTruth Expression. If the truth expression evaluates to true, the statement or statement list following it areexecuted; otherwise, they‘re not. You can add an else branch to an if tatement to execute code onlyif all the truth expressions in the if statement evaluated to false:<?php if ($var >= 50) { print $var is in range; } else { print $var is invalid; }?>Notice the braces that delimit the statements following if and else, which make these statements astatement block. In this particular case, you can omit the braces because both blocks contain onlyone statement in them It is good practice to write these braces even if they‘re not syntacticallyrequired. Doing so improves readability, and it‘s easier to add more statements to the if block later(for example, during debugging). The elseif construct can be used to conduct a series of conditionalchecks and only execute the code following the first condition that is met.For example: if ($num < 0) { print $num is negative; } elseif ($num == 0) 36
  37. 37. { print $num is zero; } elseif ($num > 0) { print $num is positive; }Statement List if ( expr ) statement elseif ( expr ) statement elseif ( expr ) statement ... else statementSwitch Statements You can use the switch construct to elegantly replace certain lengthy if/ elseif constructs. Itis given an expression and compares it to all possible case expressions listed in its body. Whenthere‘s a successful match, the following code is executed, ignoring any further case lines(execution does not stop when the next case is reached). The match is done internally using theregular equality operator (==), not the identical operator (===). You can use the break statement toend execution and skip to the code following the switch construct.Statement switch ( expr ) { case expr : statement list case expr : statement list 37
  38. 38. ... default: statement list }Usually, break statements appear at the end of a case statement list, although it is not mandatory. Ifno case expression is met and the switch construct contains default, the default statement list isexecuted. Note that the default case must appear last in the list of cases or not appear at all:Example switch ($answer) { case y: case Y: print "The answer was yesn"; break; case n: case N: print "The answer was non"; break; default: print "Error: $answer is not a valid answern"; break; } 38
  39. 39. CHAPTER- 7 Iteration Constructs ―They are used to manipulate same set of instruction more than once they are also known asloops. Following are the loops provided by PHP .‖While Loop While loops are the simplest kind of loops. In the beginning of each iteration, the while‘struth expression is evaluated. If it evaluates to true, the loop keeps on running and the statementsinside it are executed. If it evaluates to false, the loop ends and the statement(s) inside the loop isskipped.For example, here‘s one possible implementation of factorial, using a while loop (assuming$n contains the number for which we want to calculate the factorial):Example: $result = 1; while ($n > 0) { $result *= $n--; } print "The result is $result";Do...While Loop do statement while ( expr );The do...while loop is similar to the previous while loop, except that the truth expression is checkedat the end of each iteration instead of at the beginning. This means that the loop always runs at leastonce. do...while loops are often used as an elegant solution for easily breaking out of a code blockif a certain condition is met. Consider the following example: do { statement list if ($error) { 39
  40. 40. break; } statement list } while (false);Because do...while loops always iterate at least one time, the statements inside the loop areexecuted once, and only once. The truth expression is always false. However, inside the loop body,you can use the break statement to stop the execution of the statements at any point, which isconvenient. Of course, do...while loops are also often used for regular iterating purposes.For Loop PHP provides C-style for loops. The for loop accepts three arguments:for (start_expressions; truth_expressions; increment_expressions)Most commonly, for loops are used with only one expression for each of the start,truth, andincrement expressions, which would make the previous syntax table look slightly more familiarHere’s an Example:for ($i = 0; $i < 10; $i++){ print "The square of $i is " . $i*$i . "n";}The result of running this code isThe square of 0 is 0The square of 1 is 1...The square of 9 is 81Tip: PHP doesn‘t know how to optimize many kinds of loop invariants.For example, in the following for loop, count($array) will not be optimized to run only once. for ($i = 0; $i <= count($array); $i++) { }It should be rewritten as $count = count($array); for ($i = 0; $i <= $count; $i++) { …..}This ensures that you get the best performance during the execution of the loop. 40
  41. 41. Loop Control: Break And Continue Sometimes, you want to terminate the execution of a loop in the middle of an iteration. Forthis purpose, PHP provides the break statement. If break appears alone, as in break;the innermost loop is stopped. break accepts an optional argument of the amount of nesting levelsto break out of, break n ;Example break ; break expr; continue ; continue expr;which will break from the n innermost loops (break 1; is identical to break;). n can be any validexpression. In other cases, you may want to stop the execution of a specific loop iteration and beginexecuting the next one. Complimentary to break, continue provides this functionality. continuealone stops the execution of the innermost loop iteration and continues executing the next iterationof that loop. Continue n can be used to stop execution of the n innermost loop iterations. PHP goeson executing the next iteration of the outermost loop. As the switch statement also supports break,it is counted as a loop when you want to break out of a series of loops with break n. 41
  42. 42. CHAPTER- 8 Strings Strings are a sequence of characters that are always internally null terminated. However,unlike some other languages, such as C, PHP does not rely on the terminating null to calculate astring‘s length, but remembers its length internally. This allows for easy handling of binary data inPHP—for example,creating an image on-the-fly and outputting it to the browser. The maximum length of strings variesaccording to the platform and C compiler, but you can expect it to support at least 2GB. Don‘t writeprograms that test this limit because you‘re likely to first reach your memory limit. When writingstring values in your source code, you can use double quotes ("), single quotes () or here-docs todelimit them. Each method is explained in this section.Double Quotes Examples for double quotes: "PHP: Hypertext Pre-processor" "GET/HTTP/1.0n""1234567890" Strings can contain pretty much all characters. Some characters can‘t be written asis, however, and require special notation: An additional feature of double-quoted strings is thatcertain notations of variables and expressions can be embedded directly within them. Withoutgoing into specifics, here are some examples of legal strings that embed variables. The referencesto variables are automatically replaced with the variables‘ values, and if the values aren‘t strings,they are converted to their corresponding string representations (for example, the integer 123 wouldbe first converted to thestring "123"). "The result is $resultn" "The array offset $i contains$arr[$i]"In cases, where you‘d like to concatenate strings with values (such as variables andexpressions) and this syntax isn‘t sufficient, you can use the . (dot) operator to concatenate two ormore strings. This operator is covered in a later section.Single Quotes In addition to double quotes, single quotes may also delimit strings. However, in contrast todouble quotes, single quotes do not support all the double quotes‘ escaping and variablesubstitution. The following table includes the only two escapings supported by singlequotes :  n Newline. 42
  43. 43.  t Tab.  Backslash.  r Line feed.Difference Between Single Quoted And Double Quoted Strings The difference between singly and double quoted lines in how much interpretation PHPdoes of the characters between the quote signs before creating the string itself. If you enclose astring in single quotes, almost no interpretation will be performed; if you enclose it in doublequotes, PHP will splice in the values of any variables you include, as well as make substitutions forcertain special character sequences that begin with the backlash() character.For Example$statement=‘everything I say‘;$question_1=‖Do you have to take $statement so literally?<br>‖;$question_2=‘Do you have to take $statement so literally?<br>‘;echo $question_1;echo $question_2;You should expect to see the browser output: Do you have to take everything I say so literally? Do you have to take $statement so literally?Interpolation With Curly Braces We can use curly Braces within a string to differentiate a variable in a string.For Example $sport_1=”Cricket”; $sport _2=”Soccer”; $player=”I will play $sport_1 and $sport_2 Both”; echo “$player”; Will Give Output: I will play $sport_1and$sport_2 Both(Or) $player=”I will play {$sport_1}and{$sport_2} Both”; echo “$player”; Will Give Output I will play Cricket and Soccer Both 43
  44. 44. Concatenating Two String (.) Dot Operation Is used To Concat to Strings. For Example $str1=”This is”; $str2=”a book”; $sentence=$str1.$str2; print($sentence); will give output on browser This is a book. Print(“This is”. “….” .” a book.”); Will give output This is ….. a book.Concatination And Assignment Just as with arithmetic operators, PHP has a shothand operator(.=) that combinesconcatenation with assignment. The Following statement$my_string_var .= $new_addition; is exactly equivalent to:$my_string_var=$my_string_var . $new_addition;To add new String on the left use following version$my_string_var=$new_addition . $my_string_var;The Heredoc Syntax PHP Offers another way to specify a string, called the heredoc syntax. This syntax turns outto be extremely useful for specifying large chunks of variable-interpolated text, because it sparesyou from the need to escape internal quotes. It is especially useful in creating pages that containHTML forms. The operator in the heredoc syntax is (<<<).For Example $my_string_var=<<EOTEverything in this rather unnecessarily wordy Ramble of prose will be incorporated into theString that we are building up inevitably, inexorably, Character by character, line by line, until wereach that Blessed final line which is this one EOT; 44
  45. 45. Another Useful Form Example will be Echo<<<ENDOFFORM <form method=post action=”{[$_ENV[„PHP_SELF‟]}”> <input type=text name=firstname value=$firstname> <input type=submit name=submit value=SUBMIT> </form> ENDOFFORM;String Function PHP gives you a huge variety of functions for the munching and crunching of strings. If you‘re ever tempted to roll your own function that reads strings character-by-character to produce a new string, pause for a moment to think whether the task might be common. If so, there is probably a built-in function that handles it.strlen — Get string lengthint strlen ( string $string )Returns the length of the given string . <?php $str = abcdef; echo strlen($str); // 6 $str = ab cd ; echo strlen($str); // 7 ?>strcmp — Binary safe string comparison int strcmp ( string $str1, string $str2 ) Note that this comparison is case sensitive. <?php $var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) { echo $var1 is equal to $var2 in a non case-insensitive string comparison; } ?>strcasecmp — Binary safe string comparison 45
  46. 46. int strcasecmp ( string $str1, string $str2 ) Note that this comparison is case sensitive. <?php $var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) { echo $var1 is equal to $var2 in a case-insensitive string comparison; } ?>str_repeat — Repeat a string string str_repeat ( string $input, int $multiplier )Returns input repeated multiplier times. <?php echo str_repeat("-=", 10); ?>strstr — Find first occurrence of a stringstring strstr ( string $haystack, string $needle, bool $before_needle ) Returns part of haystack string from the first occurrence of needle to the end of haystackFor Example $str1=" Computer Education"; $str2="Computer"; if(strstr($str1,$str2)) { echo "$str1 contains $str2"; } else { echo "$str1 Doesnot contains $str2"; }Will Give Output Computer Education Contains ComputerAnd $str1="Info Computer Education"; 46
  47. 47. $str2="Computer"; $str3=strstr($str1,$str2); echo "$str3"; Will give output Computer Educationstr_split — Convert a string to an arrayarray str_split ( string $string [, int $split_length] ) <?php $str = "Hello Friend"; $arr1 = str_split($str); $arr2 = str_split($str, 3); print_r($arr1); print_r($arr2); ?>The above example will output:Array( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d)Array( 47
  48. 48. [0] => Hel [1] => lo [2] => Fri [3] => end)str_replace() Replace all occurrences of the search string with the replacement stringExamples<?php // Provides: <body text=black> $bodytag = str_replace("%body%", "black", "<body text=%body%>"); // Provides: Hll Wrld f PHP $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"); $onlyconsonants = str_replace($vowels, "", "Hello World of PHP"); // Provides: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); $newphrase = str_replace($healthy, $yummy, $phrase); // Use of the count parameter is available as of PHP 5.0.0 $str = str_replace("ll", "", "good golly miss molly!", $count); echo $count; // 2 // Order of replacement $str = "Line 1nLine 2rLine 3rnLine 4n"; $order = array("rn", "n", "r"); $replace = <br />; // Processes rns first so they arent converted twice. $newstr = str_replace($order, $replace, $str); // Outputs: apearpearle pear $letters = array(a, p); $fruit = array(apple, pear); $text = a p; 48
  49. 49. $output = str_replace($letters, $fruit, $text); echo $output;?>substr() Return part of a stringExample <?php $rest = substr("abcdef", 0, -1); // returns "abcde" $rest = substr("abcdef", 2, -1); // returns "cde" $rest = substr("abcdef", 4, -4); // returns "" $rest = substr("abcdef", -3, -1); // returns "de" ?>strrrev() Reversing a string with strrev()Example: <?php echo strrev("Hello world!"); // outputs "!dlrow olleH" ?>str_shuffle() The str_shuffle() function randomly shuffles all the characters of a string.Example: <?php echo str_shuffle("Hello World"); ?>The output of the code above could be: H leooWlrlducfirst() Make a strings first character uppercase 49
  50. 50. Example <?php $foo = hello world!; $foo = ucfirst($foo); // Hello world! $bar = HELLO WORLD!; $bar = ucfirst($bar); // HELLO WORLD! $bar = ucfirst(strtolower($bar)); // Hello world! ?>ucwords () Uppercase the first character of each word in a string.Returns a string with the firstcharacter of each word in str capitalized, if that character is alphabetic. The definition of a word isany string of characters that is immediately after a whitespace (These are: space, form-feed,newline, carriage return, horizontal tab, and vertical tab).Example: <?php $foo = hello world!; $foo = ucwords($foo); // Hello World! $bar = HELLO WORLD!; $bar = ucwords($bar); // HELLO WORLD! $bar = ucwords(strtolower($bar)); // Hello World! ?>strtolower — Make a string lowercase string strtolower ( string $str ) Returns string with all alphabetic characters converted to lowercase.Note that alphabetic is determined by the current locale. This means that in i.e. the default "C"locale, characters such as umlaut-A (Ä) will not be converted.Example: <?php $str = "Mary Had A Little Lamb and She LOVED It So"; 50
  51. 51. $str = strtolower($str); echo $str; // Prints mary had a little lamb and she loved it so ?>strtoupper — Make a string uppercasestring strtoupper ( string $string ) Returns string with all alphabetic characters converted to uppercase. Note that alphabetic isdetermined by the current locale. For instance, in the default "C" locale characters such as umlaut-a(ä) will not be converted.Example: <?php $str = "Mary Had A Little Lamb and She LOVED It So"; $str = strtoupper($str); echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO ?>explode — Split a string by string .array explode ( string $delimiter, string $string [, int $limit] ) Returns an array of strings, each of which is a substring of string formed by splitting it onboundaries formed by the string delimiter .<?php // Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 // Example 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // foo echo $pass; // *?>The PHP Date() Function The PHP date() function formats a timestamp to a more readable date and time. 51
  52. 52. A timestamp is a sequence of characters, denoting the date and/or time at which a certain eventoccurred.Syntax date( format , timestamp ) Parameter DescriptionFormat Required. Specifies the format of the timestampTimestamp Optional. Specifies a timestamp. Default is the current date and timeFormats the Date The required format parameter in the date() function specifies how to format thedate/time.Here are some characters that can be used: d - Represents the day of the month (01 to 31) m - Represents a month (01 to 12) Y - Represents a year (in four digits)Other characters, like"/", ".", or "-" can also be inserted between the letters to add additionalformatting: <?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d") ?>The output of the code above could be something like this: 2009/05/11 2009.05.11 2009-05-11 52
  53. 53. More Formates Date Function Parameter Description Format Required. Specifies how to return the result: D The day of the month (from 01 to 31) D A textual representation of a day (three letters) J The day of the month without leading zeros (1 to 31) l (lowercase L) A full textual representation of a day N The ISO-8601 numeric representation of a day (1 for Monday through 7 for Sunday) S The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j) W A numeric representation of the day (0 for Sunday through 6 for Saturday) Z The day of the year (from 0 through 365) W The ISO-8601 week number of year (weeks starting on Monday) F A full textual representation of a month (January through December) M A numeric representation of a month (from 01 to 12) M A short textual representation of a month (three letters) N A numeric representation of a month, without leadingzeros (1 to 12) T The number of days in the given month L Whether its a leap year (1 if it is a leap year, 0 otherwise) O The ISO-8601 year number Y A four digit representation of a year Y A two digit representation of a year A Lowercase am or pm A Uppercase AM or PM B Swatch Internet time (000 to 999) G 12-hour format of an hour (1 to 12) G 24-hour format of an hour (0 to 23) H 12-hour format of an hour (01 to 12) H 24-hour format of an hour (00 to 23 I Minutes with leading zeros (00 to 59) S Seconds, with leading zeros (00 to 59) 53
  54. 54. E The timezone identifier (Examples: UTC, Atlantic/Azores) I (capital i) Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise) O Difference to Greenwich time (GMT) in hours (Example: +0100) T Timezone setting of the PHP machine (Examples:EST, MDT) Z Timezone offset in seconds. The offset west of UTC isnegative, and the offset east of UTC is positive (-43200 to 43200) C The ISO-8601 date (e.g. 2004-02-12T15:19:21+00:00) R The RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07 +0200) U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)Example<?php echo("Result with date():<br />"); echo(date("l") . "<br />"); echo(date("l dS of F Y h:i:s A") . "<br />"); echo("Oct 3,1975 was on a ".date("l", mktime(0,0,0,10,3,1975))."<br />"); echo(date(DATE_RFC822) . "<br />"); echo(date(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br /><br />"); echo("Result with gmdate():<br />"); echo(gmdate("l") . "<br />"); echo(gmdate("l dS of F Y h:i:s A") . "<br />"); echo("Oct 3,1975 was on a ".gmdate("l", mktime(0,0,0,10,3,1975))."<br />"); echo(gmdate(DATE_RFC822) . "<br />"); echo(gmdate(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br />");?>The output of the code above could be something like this:Result with date(): Tuesday Tuesday 24th of January 2006 02:41:22 PM Oct 3,1975 was on a Friday Tue, 24 Jan 2006 14:41:22 CET 1975-10-03T00:00:00+0100 54
  55. 55. Result with gmdate(): Tuesday Tuesday 24th of January 2006 01:41:22 PM Oct 3,1975 was on a Thursday Tue, 24 Jan 2006 13:41:22 GMT 1975-10-02T23:00:00+0000Adding a Timestamp The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used. The mktime() function returns the Unix timestamp for a date.The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 197000:00:00 GMT) and the time specified.Syntax for mktime() mktime(hour,minute,second,month,day,year,is_dst)To go one day in the future we simply add one to the day argument of mktime(): <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?>The output of the code above could be something like this: Tomorrow is 2009/05/12Runtime Configuration The behavior of the date/time functions is affected by settings in php.ini.Date/Time configuration options: Name Default Description Changeabledate.default_latitude "31.7667" Specifies the default latitude PHP_INI_ALL (available since PHP 5). This option is used by date_sunrise() and date_sunset() 55
  56. 56. date.default_longitude "35.2333" Specifies the default longitude PHP_INI_ALL (available since PHP 5). This option is used by date_sunrise() and date_sunset()date.sunrise_zenith "90.83" Specifies the default sunrise zenith PHP_INI_ALL (available since PHP 5). This option is used by date_sunrise() and date_sunset()date.sunset_zenith "90.83" Specifies the default sunset PHP_INI_ALL zenith (available since PHP 5). This option is used by date_sunrise() and date_sunset()date.timezone ―‖ Specifies the default timezone PHP_INI_ALL (available since PHP 5.1)PHP checkdate() FunctionDefinition and UsageThe checkdate() function returns true if the specified date is valid, and false otherwise.A date is valid if:  month is between 1 and 12 inclusive  day is within the allowed number of days for the particular month  year is between 1 and 32767 inclusiveSyntax :checkdate(month , day , year) Parameter DescriptionMonth Required. Specifies the monthDay Required. Specifies the dayYear Required. Specifies the year Example <?php var_dump(checkdate(12,31,2000)); var_dump(checkdate(2,29,2003)); var_dump(checkdate(2,29,2004)); ?> 56
  57. 57. The output of the code above will be: bool(true) bool(false) bool(true)PHP getdate() FunctionDefinition and UsageThe getdate() function returns an array that contains date and time information for a Unixtimestamp. The returning array contains ten elements with relevant information needed whenformatting a date string: [seconds] - seconds [minutes] - minutes [hours] - hours [mday] - day of the month [wday] - day of the week [year] - year [yday] - day of the year [weekday] - name of the weekday [month] - name of the monthSyntaxgetdate(timestamp)Parameter Description timestamp Optional. Specifies the time in Unix time formatExample<?php print_r(getdate()); ?>The output of the code above could be:Array( [seconds] => 45 [minutes] => 52 [hours] => 14 [mday] => 24 57
  58. 58. [wday] => 2 [mon] => 1 [year] => 2006 [yday] => 23 [weekday] => Tuesday [month] => January [0] => 1138110765)Example<?php $my_t=getdate(date("U")); print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]"); ?>The output of the code above could be: Wednesday, January 25, 2006PHP gettimeofday() FunctionDefinition and UsageThe gettimeofday() function returns an array that contains current time information.The meaning of the returning array keys:  [sec] - seconds since the Unix Epoch  [usec] - microseconds  [minuteswest] - minutes west of Greenwich  [dsttime] - type of dst correctionSyntax gettimeofday(return_float)Parameter Description return_float Optional. Makes gettimeofday() return a float when it is set to true.Example <?php echo(gettimeofday(true) . "<br /><br />"); print_r(gettimeofday()); ?>The output of the code above could be: 58