WEB TECHNOLOGIES MATERIAL
By
P.Ravi Teja Asst .Professor, C.S.E.Dept, G.I.S.T-S.P.S.R.Nellore Ph: 900!0"0!#
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page
UNIT-I Introduction To Web Server A web server is the combination of computer and the program installed on it. Web server interacts with the client through a web browser. It delivers the web pages to the client and to an application by using the web browser. and the HTTP protocols respectively. We can also define the web server as the package of large number of programs installed on a computer connected to Internet or intranet for downloading the reuested files using !ile Transfer Protocol" serving e#mail and building and publishing web pages. A web server works on a client server model. A computer connected to the Internet or intranet must have a server program. The most commonly used Web servers are Apache" which has been implemented for a variety of computer platforms" and $icrosoft%s Internet Information &erver 'II&(" which runs under Windows operating systems.
.
•
There are many types of web server" )nterprise uses according to their need. &ome of the popular categories of web servers are # HTTP &erver # It handles HTTP reuest coming from clients browser and transfer the static pages to client in response to their reuest. This pages runs of the client browser. It generally contains the static pages. !TP &erver # This type of server used for file transfer from one machine '*omputer( to another using the internet or intranet. It uses !ile Transfer Protocols to transfer file from one computer to another. &uch type of server uses some file transfer policies" authentication" login validation etc $ail &erver # A $ail &erver store and retrieve mail messages from client mail bo+.
•
Application &erver # It is installed database and web servers
•
•
•
•
•
Apache Tomcat is popular web server being used today for the implementation of some ,ava technologies. It is a open source software used for implementing web applications. In the ne+t e+ample of servlet we will use the Apache Tomcat as a web server.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page !
Web Server Operation *lients and servers is a natural conseuence of information distribution" this configuration offers some additional benefits for the Web. Web servers need not be involved in this display process" they can handle many clients. Web browsers initiate network communications with servers by sending them -/s. A -/ can specify one of two different things0 the address of a data file stored on the server that is to be sent to the client" or a program stored on the server that the client wants e+ecuted" with the output of the program returned to the client. All the communications between a Web client and a Web server use the standard Web protocol" Hyperte+t Transfer Protocol 'HTTP(. When a Web server begins e+ecution" it informs the operating system under which it is running that it is now ready to accept incoming network connections through a specific port on the machine. While in this running state" the server runs as a background process in the operating system environment. A Web client" or browser" opens a network connection to a Web server" sends information reuests and possibly data to the server" receives information from the server" and closes the connection. The primary task of a Web server is to monitor a communications port on its host machine" accept HTTP commands through that port" and perform the operations specified by the commands. All HTTP commands include a -/" which includes the specification of a host server machine. When the -/ is received" it is translated into either a file name or a program name. All current Web servers have a common ancestry0 the first two servers" developed at *)1 in )urope and 1*&A at the -niversity of Illinois. *urrently" the most common server configuration is Apache running on some version of -1I2.
General Server Characteristics The file structure of a Web server has two separate directories. The root of one of these is called the $o%&'e(t root. The file hierarchy that grows from the document root stores the Web documents to which the server has direct access and normally serves to clients. The root of the other directory is called the server root. This directory" along with its descendant directories" stores the server and its support software. The files stored directly in the document root are those available to clients through top#level -/s. Typically" clients do not access the document root directly in -/s3 rather" the server maps reuested -/s to the document root" whose location is not known to clients. !or e+ample" suppose that the site name is www.tunias.com 'not a real site4at least" not yet(" which we will assume to be a -1I2#based system. &uppose further that the document root is named topdocs and is stored in the 5admin5web directory" making its address 5admin5web5topdocs. A reuest for a file from a client with the -/ http055www.tunias.com5petunias.html will cause the server to search for the file with the file path 5admin5web5topdocs5petunias.html. /ikewise" the -/ http055www.tunias.com5bulbs5tulips.html will cause the server to search for the file with the address 5admin5web5topdocs5bulbs5tulips.html $any servers allow part of the servable document collection to be stored outside the directory at the document root. The secondary areas from which documents can be served are called virt&al $o%&'e(t
trees . !or e+ample" srcinalsystem configuration server machine. might have the server store allofitsservable servable documents from thethe primary disk on of thea server /ater" the collection documents might outgrow that disk" in which case part of the collection could be stored on a secondary disk. This secondary disk might reside on the server machine or on some other machine on a local area network.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page "
$any servers can support more than one site on a computer" potentially reducing the cost of each site and making their maintenance more convenient. &uch secondary hosts are called virt&al hosts. &ome servers can serve documents that are in the document root of other machines on the Web3 in this case" they are called pro)* servers. Although Web servers were srcinally designed to support only the HTTP protocol" many now support ftp" gopher" news" and mailto.
Apache HTTP Server The Apache HTTP Server" commonly referred to as Apache "is web server software notable for playing a key role in the initial growth of the World Wide Web. In 6778 it became the first web server software to surpass the 977 million website milestone. Apache was the first viable alternative to the 1etscape *ommunications *orporation webinserver namedand :racle iPlanet Web &erverApache (" and since evolved to rival other web servers terms'currently of functionality performance. Typically is runhas on a -ni+#like operating system. Apache is developed and maintained by an open community of developers under the auspices of the Apache &oftware !oundation. The application is availa ble for a wide variety of operating systems " including -ni+" ;1-" !reeB&<" /inu+" &olaris" 1ovell 1etWare" Amiga:&" $ac :& 2 " $icrosoft Windows" :&56" TP!" and e*om&tation. eleased under the Apache /icense " Apache is open#source software. Apache was srcinally based on due to a rewrite.
1*&A HTTPd code. The 1*&A code is since removed from Apache"
When Apache begins e+ecution" it reads its configuration information from a file and sets its parameters to operate accordingly. A new copy of Apache includes default configuration information for a =typical> operation. The site manager modifies this configuration information to fit his or her particular needs and tastes. !or historical reasons" there are three configuration files in an Apache server0 httpd.conf" srm.conf" and access.conf. :nly one of these" httpd.conf" actually stores the directives that control an Apache server%s behavior. The other two point to httpd.conf" which is the file that contains the list of directives that specify the server%s operation. &ince April 988? Apache has been the most popular HTTP server software in use. As of $ay 6799 Apache was estimated to serve ?@ of all websites and ?? of the million busiest.CD Stro(+hol$ was a fork of the Apache HTTP &erver" which included the &ecure &ocket /ayer software to enable https. It was created by *61et" which was eventually purchased by ed Hat. &trongholdEs last support date was 677C#96#@9 Nae According to the !AF in the Apache pro,ect website" the name Apache was chosen out of respect to the 1ative American tribe Apache 'Inde( and its superior skills in warfare and strategy. In addition the website claims that the nameEs story result ing from the server being A Pat%h* server 'since it was a con,unction of software patches( is popular but incorrect.?D !eat"res Apache supports a variety of features" many implemented as compiled modules which e+tend the core functionality. These can range from server#side programming language support to authentication schemes. &ome common language interfaces support Perl" Python" Tcl" and PHP. Popular authentication modules include modGaccess" modGauth" modGdigest" and modGauthGdigest" the successor to modGdigest. A sample of other features include &ecure &ockets /ayer and Transport /ayer &ecurity support ' modGssl(" a pro+y module ' modGpro+y(" a -/ rewriter 'also known as a rewrite engine " P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page #
implemented under modGrewrite(" custom log files 'modGlogGconfig(" and filtering support 'modGinclude and modGe+tGfilter(. Popular compression methods on Apache include the e+ternal e+tension module" modGgip" implemented to help with reducti on of the sie 'weight( of web pages served over HTTP. $od&ecurity is an open source intrusion detection and prevention engine for web applications. Apache logs can be analyed through a web browser using free scripts such as AW&tats5W@Perl or isitors. irtual hosting allows one Apache installation to serve many different actual websites. !or e+ample" one machine with one Apache installation could simultaneously serve www.e+ample.com" www.e+ample.org" testJK.test#server.e+ample.edu" etc. Apache features configurable error messages"
Although the main design goal of Apache is not to be the LfastestL web server" Apache does have performance comparable to other Lhigh#performanceL web servers. Instead of implementing a single architecture" Apache provides a variety of $ultiProcessing $odules '$P$s( which allow Apache to run in a process#based" hybrid 'process and thread( or event#hybrid mode" to better match the demands of each particular infrastructure. This implies that the choice of correct $P$ and the correct configuration is important. Where compromises in performance need to be made" the design of Apache is to reduce latency and increase throughput" relative to simply handling more reuests" thus ensuring consistent and reliable processing of reuests within reasonable time#frames. The Apache version considere d by the Apache !oundati on as providing high#perf ormance is the multi# threaded version which mi+es the use of several processes and several threads per process. While this architecture works faster than the previous multi#process based topology 'because threads have a lower overhead than processes(" it does not match the performances of the event#based architecture provided by other servers" especially when they process events with several worker threads. This difference can be easily e+plained by the overhead that one thread per connection brings 'as opposed to a couple of worker threads per *P-" each processing many connection events(. )ach thread needs to maintain its own stack" environment" and switching from one thread to another is also an e+pensive task for *P-s.
Internet In#oration Services Internet In#oration Services 'IIS( M formerly called Internet In#oration Server M is a web server application and set of feature e+tension modules created by $icrosoft for use with $icrosoft Windows. It
is the most used web server after Apache HTTP &erver . II& K.C supports HTTP" HTTP&" !TP" !TP&" &$TP and 11TP. It is an integral part of Windows &erver family of products" as well as certain editions of Windows 2P" Windows ista and Windows K. II& is not turned on by default when Windows is installed.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page $
!rom the point of view of the site manager" the most important difference between Apache and II& is that Apache is controlled by a configuration file that is edited by the manager to change Apache%s behavior. With II&" server behavior is modified by changes made through a window#based management program" named the II& snap#in" which controls both II& and ftp. This program allows the site manager to set parameters for the server. Histor$ The first $icrosoft web server was a research pro,ect at )uropean $icrosoft Windows 1T Academic *entre ')$WA*(" part of the -niversity of )dinburgh in &cotl and" and was distributed as freeware. However" since the )$WA* server was unable to scale sufficiently to handle the volume of traffic going to microsoft.com" $icrosoft was forced to develop its own web server" II&.
Almost every version of II& was released either alongside or with a version of $icrosoft Windows operating system. II& 9.7 was initially released as a free add#on" a set of web#based services for Windows 1T @.C9. However" II& 6.7 was included with Windows 1T J.7. II& @.7" which was included with &ervice Pack @ of Windows 1T J" introduced the Active &erver Pages dynamic scripting environment. II& J.7 was released as part of an L:ption PackL for Windows 1T J.7 and dropped support for the ;opher protocol.citation neededD II& C.7 shipped with Windows 6777 and introduced additional authentication methods" management enhancem ents including a new $$* based administration application" support for the Web
II& 9.7" Windows 1T @.C9 available as a free add#on
•
II& 6.7" Windows 1T J.7
•
II& @.7" Windows 1T J.7 &ervice Pack 697D
•
II& J.7" Windows 1T J.7 :ption Pack
•
II& C.7" Windows 6777
•
• •
II& C.9" Windows 2P Professional and Windows 2P $edia *enter )dition 'reuires retail *<( II& ?.7" Windows &erver 677@ and Windows 2P Professional +?J )dition II& K.7" Windows &erver 677N and Windows ista 'Home Premium" Business" )nterprise and -ltimate editions(
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected]
Page %
•
II& K.C" Windows &erver 677N 6 and Windows K 'Home Premium" Professional" )nterprise and -ltimate editions(
&sa'e
As of :ctober 6799" II& is the second most used server in the world" after used on 9C.?? of servers and responds to 96.J? of total reuests.
Apache HTTP &erver . It is
Sec"rit$
)arlier versions of II& were hit with a number of vulnerabilities" especially the *A#6779#9@ which led to the infamous *ode ed worm3 however" both versions ?.7 and K.7 currently have no reported issues with this specific vulnerability. In II& ?.7 $icrosoft opted to change the behaviour of pre#installed I&API handlers" many of which were culpri ts in the vulnerabilities of J.7 and C.7" thus reducing the attack surface of II&. In addition" II& ?.7 added a feature called LWeb &ervice )+tensionsL that prevents II& from launching any program without e+plicit permission by an administrator. In the current release" II& K" the components are provided as modules so that only the reuired components have to be installed" thus further reducing the attack surface. In addition" security features are added such as euest !iltering" which re,ects suspicious -/s based on a user#defined rule set. By default II& C.9 and lower run websites in#proc ess under the &O&T)$ account" a default Windows account with EsuperuserE rights. -nder ?.7 all reuest handling processes have been brought under a 1etwork &ervices account with significantly fewer privileges so that should there be a vulnerability in a feature or in custom code it wonEt necessarily compromise the entir e system given the sandbo+ed environment these worker processes run in. II& ?.7 also contained a new kernel HTTP stack 'http.sys( with a stricter HTTP reuest parser and response cache for both static and dynamic content. According to &ecunia" as of une 6799" II& K had a total of ? resolved vulnerabilities while II& ? had a total of 99 vulnerabilities out of which 9 was still unpatched. The unpatched security advisory has a severity rating of 6 out of C. In une 677K" a ;oogle study of N7 million domains concluded that while the II& market share was 6@ at the time" II& servers hosted J8 of the worlds malware" same as Apache servers whose market share was ??. The study also observed the geographical location of these dirty servers and suggested that the cause of this could be the use of pirated copies of Windows for which security updates were unavailable. This is no longer the case0 $icrosoft supplies security updates to all users. !eat"res The architecture of II& K is modular. $odules" also called e+tensions" can be added or removed individually so that only modules reuired for specific functionality have to be installed. II& K includes native modules as part of the full installation. These modules are individual features that the server uses to process reuests and include the following0 •
•
HTTP modules M -sed to perform tasks specific to HTTP in the reuest#processing pipeline" such as responding to information and inuiries sent in client headers" returning HTTP errors" and redirecting reuests. &ecurity modules M -sed to perform tasks related to security in the reuest#processing pipeline" such as specifying authentication schemes" performing -/ authoriation" and filtering reuests.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page &
•
•
•
•
*ontent modules M -sed to perform tasks related to content in the reuest#processing pipeline" such as processing reuests for static files" returning a default page when a client does not specify a resource in a reuest" and listing the contents of a directory. *ompression modules M -sed to perform tasks related to compression in the reuest# processing pipeline" such as compressing responses" applying ;ip compression transfer coding to responses" and performing pre#compression of static content. *aching modules M -sed to perform tasks related to caching in the reuest#processing pipeline" such as storing processed information in memory on the server and using cached content in subseuent reuests for the same resource. /ogging and
(AMPP (AMPP is a free and open source cross#platform web server solution stack package" consisting mainly of the Apache HTTP &erver " $y&F/ database" and interpreters for scripts written in the PHP and Perl programming languages. 2A$PPEs name is an acronym for0 •
2 'to be read as LcrossL" meaning cross#platform(
•
Apache HTTP &erver
•
$y&F/
•
PHP
•
Perl
The program is released under the terms of the ;1- ;eneral Public /icense and acts as a free web server capable of serving dynamic pages. 2A$PP is available for $icrosoft Windows" /inu+" &olaris" and $ac :& 2" and is mainly used for web development pro,ects. This software is useful while we are creating dynamic webpages using programming languages like PHP" &P" &ervlets. Re)"ireents an* #eat"res
2A$PP reuires only one ip" tar" K" or e+e file to be downloaded and run" and little or no configuration of the various components that make up the web server is reuired. 2A$PP is regularly updated to incorporate the latest releases of Apache5$y&F/5PHP and Perl. It also comes with a number of other modules including :pen&&/ and php$yAdmin. Installing 2A$PP takes less time than installing each of its components separately. &elf#contained" multiple instances of 2A$PP can e+ist on a single computer" and any given instance can be copied from one computer to another. It is offered in both a full" standard version and a smaller version. &se :fficially" 2A$PPEs designers intended it for use only as a development tool" to allow website designers and programmers to test their work on their own computers without any access to the Internet. To make this as easy as possible" many important security features are disabled by default.6D In practice" however" 2A$PP is sometimes used to actually serve web pages on the World Wide Web. A special tool is provided to password#protect the most important parts of the package. P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page '
2A$PP also provides support for creating and manipulating databases in others.
$y&F/ and &F/ite among
:nce 2A$P P is installed we can treat our localhost like a remote host by connecting using an !TP client. -sing a program like !ileQilla has many advantages when installing a content management system '*$&( like oomla. We can also connect to localhost via !TP with our HT$/ editor. The default $y&F/ user is LrootL while there is no default $y&F/ password.
WAMP WAMPs are packages of independently#created programs instal led on computers that use a $icrosoft Windows operating system.WA$P is an acronym formed from the initials of the operating system $icrosoft Windows and the principal components of the package0 Apache" $y&F/ and one of PHP" Perl or Python. Apache is a web server. $y&F/ is an open#source database. PHP is a scripting language that can manipulate information held in a database and generate web pages dynamically each time content is reuested by a browser. :ther programs may also be included in a package" such as php$yAdmin which provides a graphical user interface for the $y&F/ database manager" or the alternative scripting languages Python or Perl. )uivalent packages are $A$P 'for the Apple $ac( and /A$P 'for the /inu+ operating system(. This is a list of A$P ' Apache" $y&F/" Perl5PHP5Python( solution stacks for all computer platforms3 these software bundles are used to run dynamic Web sites or servers . There are /A$Ps 'for /inu+(3 WA$Ps 'for Windows(3 $A$Ps 'for $acintosh(3 &A$Ps 'for &olaris(3 and !A$Ps 'for !reeB&<(.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected]
Page (
The difference between wamp" lamp and +ampp. All these three are used for serving php websites and acts as the local server so that we can see our working website without uploading it first. .
+ap
wamp stands for windows" apache" mysl" php. The best advantage of using wamp is that it is easy to setup configuration in wamp. But when i started using wamp" some times i faced problems while running php code " may be it was my coding problem but what else. $ostly people talk that wamp is not good for beginner but i say that wamp is very easy to use and it is best for both beginner and advanced users.
,app
+ampp is stands +#os" apache" mysl" php "isperl. it can used forand anyitsoperating system. +ampp easy for to use than wamp. Its cpanel very+#os nicemeans and good forbebeginner start" pause and stop button work very nicely by functionality. We can add other services to +ampp also. I personally use +ampp for my development.
lap lamp stands for linu+" apache" mysl" php. Its functionality is same as wamp and +ampp. I want to tell we one thing that the main functionality of all these three'wamp" +ampp" lamp( are same i.e compile and run the php code" manage database s and other stuff. All these softw ares give us ease in our development so that the comple+ity of handling all the services'databases handling" code manipulation( becomes easy for us.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page )
(AMPP INSTALATION PROCESS
&elect )nglish language and click ok
*lick on 1e+t button P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page
&elect destination folder and press ne+t
Tick check bo+es install Apache as &ervice and $y&Fl as service and click install
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page !
Then installation process started wait until installing completed
After installation get completed it will check for necessary port for Apache and $y&F/
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page "
After finshing installation it will lanch the 2A$PP control panel
There check whether the Apache and $y&F/ in running mode or not. if not use start option to start both servers. Then press apache Adimin button it will open a e+plorer window there select language )nglish.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page #
To place our documents in server check where the server is installed.*heck for +ampp older in that check for htdocs folder And create a new folder and rename to our own and place our application on that.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page $
1e+t open )+plorer in the url give http055localhost5te,a and press enter It will launch our application
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page %
WAMP Installation
*lick on ne+t button and select license agreement
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page &
*lick on install button
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page '
After installation *lick on ne+t button then installation process get completed In left corner we get wamp control panel click on that.
*lick on local host for localhost To place our documents in server check where the server is installed.*heck for wamp older in that check for www folder and create a new folder and rename to our own and place our application on that.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page (
And follow the same process as 2A$PP to launch application
The H$perte,t Trans#er Protocol All Web communications transactions use the same protocol0 the Hyperte+t Transfer Protocol 'HTTP(. The current version of HTTP is 9.9" formally defined as !* 6?9?" which was approved in une 9888. !* 6?9? is available at the Web site for the World Wide Web *onsortium 'W@*("
[email protected]. This section provides a brief introduction to HTTP. HTTP consists of two phases0 the reuest and the response. )ach HTTP communication 'reuest or response( between a browser and a Web server consists of two parts0 a header and a body. The header contains information about the communication3 the body contains the data of the communication if there is any.
The Re)"est Phase The general form of an HTTP reuest is as follows0 9. HTTP method
Email:
[email protected] Page !)
Among the methods given in Table" ;)T and P:&T are the most freuently used. P:&T was srcinally designed for tasks such as posting a news article to a newsgroup. Its most common use now is to send form data from a browser to a server" along with a reuest to e+ecute a program on the server that will process the data. !ollowing the first line of an HTTP communication is any number of header fields" most of which are optional. The format of a header field is the field name followed by a colon and the value of the field. There are four categories of header fields0 9. Ge(eral0 !or general information" such as the date 6. Re&est0 Included in reuest headers @. Respo(se0 !or response headers J. E(tit*0 -sed in both reuest and response headers :ne common reuest field is the Accept field" which specifies a preference of the browser for the $I$) type of the reuested document. $ore than one Accept field can be specified if the browser is willing to accept documents in more than one format. !or e+ample3 we might have any of the following0 Accept0 te+t5plain Accept0 te+t5html Accept0 image5gif A wildcard character" the asterisk 'R(" can be used to specify that part of a $I$) type can be anything. !or e+ample" if any kind of te+t is acceptable" the Accept field could be as follows0 Accept0 te+t5R The Host0 host (a'e reuest field gives the name of the host. The Host field is reuired for HTTP 9.9. The If#$odified#&ince0 $ate reuest field specifies that the reuested file should be sent only if it has been modified since the given date. If the reuest has a body" the length of that body must be given with a *ontent#length field" which gives the length of the response body in bytes. P:&T method reuests reuire this field because they send data to the server. The header of a reuest must be followed by a blank line" which is used to separate the header from the body of the reuest. euests that use the ;)T" H)A<" and <)/)T) methods do not have bodies. In these cases" the blank line signals the end of the reuest. A browser is not necessary to communicate with P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page !
a Web server3 telnet can be used instead. *onsider the following command" given at the command line of any widely used operating system0 S telnet blanca.uccs.edu http This command creates a connection to the http port on the blanca.uccs .edu server. The server respond s with the following0 Trying 96N.98N.9?6.?7 ... *onnected to blanca )scape character is EDE.
The connection to the server is now complete" and HTTP commands such as the following can be given0 ;)T 5Uuser95respond.html HTTP59.9 Host0 blanca.uccs.edu
The Response Phase The general form of an HTTP response is as follows0 9. &tatus line 6. esponse header fields @. Blank line J. esponse body The status line includes the HTTP version used" a three#digit status code for the response" and a short te+tual e+planation of the status code. !or e+ample" most responses begin with the following0 HTTP59.9 677 :V The status codes begin with 9" 6" @" J" or C. The general meanings of the five categories specified by these first digits are shown in Table
:ne of the more common stat us codes is one users never want to see0 J7J 1ot !ound" which means the reuested file could not be found. :f course" 677 :V is what users want to see" because it means that the reuest was handle without error. The C77 code means that the server has encountered a problem and was not able to fulfill the reuest.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page !!
After the status line" the server sends a response header" which can contain several lines of information about the response" each in the form of a field. The only essential field of the header is *ontent#type The following is the response header for the reuest
TTP!.! /00 1 Date: Sat, /2 3&l* /009 //:!2:!! G4T Server: Apa%he/./. 5Ce(tS6 7ast-'o$ifie$: T&es, !8 4a* /00" !:8:8 G4T ETa+: !;"8098-!%-$a;29/$%9f80 A%%ept-ra(+es: ;*tes Co(te(t-le(+th: " Co((e%tio(: %lose Co(te(t-t*pe: te)tht'l, %harset<=T>-8 The response header must be followed by a blank line" as is the case for reuest headers. The response data follows the blank line. In the preceding e+ample" the response body would be the HT$/ file" respond.html. In HTTP versions prior to 9.9" when a server finished sending a response to the client" the communications connection was closed. However" the default operation of HTTP 9.9 is that the connection is kept open for a time so that the client can make several reuests over a short span of time without needing to reestablish the communications connection with the server. This change led to significant increases in the efficiency of the Web.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:
[email protected] Page !"
&NIT - II .i##erence bet+een PHP/ 0SP an* ASP •
•
•
•
•
•
•
•
•
•
PHP is an open#source page scripting5templating system that is very similar to &P and A&P. It defines its own scripting language" which looks and feels a lot like Perl. &P uses ava as its scripting language. A&P uses B&cript. PHP is very popular ## it is used on over a million web sites ## but its main advantage 'I$H:( seems to be that the language" being more LscriptyL and Perl#like" is less intimidating to the great unwashed mass of HT$/ monkeys and hackers. In the long run" &P and ava provide a more powerful system. Anything we can do with PHP " we can do with &P3 the rever se is not true &P is much more powerful" since it has access to all the ava libraries. PHP only has access to PHP libraries . &P is :b,ect#:riented" so leads to cleaner code thatEs easier to debug" maintain" and improve. 'PHP also allows ob,ects" but the ob,ect model is more primitive" and most scripted pages ignore PHP ob,ects and ,ust use normal variables.( &PEs concept of state management and persistence is more e+plicit and powerful than PHPEs. With &P" we can specify whether a variable persists for the page" the reuest" the session" or the application 'or if itEs ,ust local to the function(. The &P engine automatically does the right thing with cookies so we have access to the variable on later reuests. With PHP" we ,ust have LglobalL and Lnot globalL" we donEt have automatic session management" and have to do our state thing manually with cookies or hidden variables. PHP" www.php.netD" while loosely based on * and Perl" has never faced the overwhelming complications A&P has. PHP is an ob,ect oriented language # though scripts need not necessarily be developed that way 'there are still a vast number of developers preferring procedural programming" and PHP caters to both schools(. PHP is both cross platform and open source" available for every ma,or operating system and works with most web servers. It is easily e+tendable by anyone capable of coding in *" and comes pre# bundled with more functionality than A&P could ever offer. &imple capabilities" such as !TP" data compression" file uploads" 2$/" $
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page !#
•
•
•
•
A&P is significantly slower than PHP" for obvious reasons. Primarily" PHP runs on notoriously fast -ni+ and /inu+ servers which have for years outpaced Windows running on comparable hardware. A&P does not run on any operating system other than Windows" and even then" only in II& and PW&. I could discuss countless reasons why II& makes a terrible web server" but that would be a discussion all on itEs own. PHP runs on almost any web server" on almost any platform. I have even built a web server in PHP which was capable of e+ecuting PHP scripts. A&P natively supports only Access and $&&F/" whereas PHP natively supports a huge number of databases. They both support :
PHP History In 988C PHP developed by a contractor named asmus /erdorf developed a Perl5*;I script that enabled him to know how many visitors were reading his online rsum. The clamor for the PHP toolset prompted /erdorf to continue developing the language" with perhaps the most notable early change being a new feature for converting data entered in an HT$/ form into symbolic variables" encouraging e+portation into other systems. To accomplish this" he opted to continue development in * code rather than Perl. :ngoing additions to the PHP toolset culminated in 1ovember 988K with the release of PHP 6.7" or Personal Home Page5!orm Interpreter 'PHP5!I(. As a result of PHP%s rising popularity" the 6.7 release was accompanied by a number of enhancements and improvements from programmers worldwide. The new PHP release was e+tremely popular" and a core team of developers soon ,oined /erdorf. They kept the srcinal concept of incorporating code directly alongside HT$/ and rewrote the parsing engine" giving birth to PHP @.7. By the une 988N release of version @.7" more than C7"777 users were using PHP to enhance their Web pages.
Email:[email protected] Page !$
PHP 1
:n $ay 66" 6777" roughly 9N months after the first official announcement of the new development effort" PHP J.7 was released. $any considered the release of PHP J to be the language%s official debut within the enterprise development scene" an opinion backed by the language%s meteoric rise in popularity. ust a few months after the ma,or release" 1etcraft estimated that PHP had been installed on more than @.? million domains. PHP J added several enterprise#level improvements to the language" including the following0 Iprove* reso"rce han*lin'2:ne of version @.2%s primary drawbacks was scalability. This was largely because the designers underestimated how rapidly the language would be adopted for large#scale applications. The language wasn%t srcinally intended to run enterprise#class Web sites" and continued interest in using it for such purposes caused the developers to rethink much of the language%s mechanics in this regard. Ob3ect-oriente* s"pport2 ersion J incorporated a degree of ob,ect#oriented functionality" although it was largely considered an une+ceptional and even poorly conceived implementation. 1onetheless" the new features played an important role in attracting users used to working with traditional ob,ect#oriented programming '::P( languages. &tandard class and ob,ect development methodologies were made available in addition to features such as ob,ect overloading and run#time class information. A much more comprehensive ::P implementation has been made available in version C Native session-han*lin' s"pport2 HTTP session handling" available to version @.2 users through the third#party package PHP/IB ' http055phplib.sourceforge.net(" was natively incorporated into version J. This feature offers developers a means for tracking user activity and preferences with unparalleled efficiency and ease. Encr$ption2 The $*rypt 'http055mcrypt.sourceforge.net( library was incorporated into the default distribution" offering users both full and hash encryption using encryption algorithms including Blowfish" $
the reigning royalty the astring#parsing kingdom. The developers knew that e+pression functionality would ofplay ma,or role in the widespread acceptance of powerful PHP and regular opted to simply incorporate Perl%s functionality rather than reproduce it" rolling the P*) library package into PHP%s default distribution 'as of version J.6.7(.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page !%
PHP 7
ersion C was yet another watershed in the evolution of the PHP language. Although previous ma,or releases had enormous numbers of new library additions" version C contains improvements over e+isting functionality and adds several features commonly associated with mature programming language architectures0 %astl$ iprove* ob3ect-oriente* capabilities2 Improvements to PHP%s ob,ectoriented architecture is version C%s most visible feature. ersion C includes numerous functional additions such as e+plicit constructors and destructors" ob,ect cloning" class abstraction" variable scope" and interfaces" and a ma,or improvement regarding how PHP handles ob,ect management.
Tr$4catch han*lin'2
At press time" ? was in beta and scheduled to be released bytothe of 677K. The decision to designate this aPHP ma,or release 'version ?( is considered by many beconclusion a curious one" in part because only one particularly significant feature has been added4 -nicode support. However" in the programming world" the word si+(ifi%a(t is often implied to mean se)* or 'ar?eta;le" so don%t let the addition of -nicode support overshad ow the many other important features that have been added to PHP ?. A list of highlights is found here0 Z &nico*e s"pport2 1ative -nicode support has been added" making it much easier to build and maintain multilingual applications. Z Sec"rit$ iproveents2 A considerable number of security#minded improvements have been made that should greatly decrease the prevelance of securityrelated gaffes that to be frank aren%t so much a fault of the language" but are due to ine+perienced programmers running with scissors" so to speak. These changes are discussed in *hapter 6. Z Ne+ lan'"a'e #eat"res an* constr"cts2A number of new synta+ features have been added" including" most notably" a ?J#bit integer type" a revamped foreach looping construct for multidimensional arrays" and support for labeled breaks.
Downloading PHP P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page !&
PHP comes bundled with most /inu+ distributions. we should download the latest stable version from the PHP Web site. To decrease download time" choose from the appro+imately 977 mirrors residing in more than C7 countries" a list of which is available here0 http055www.php.net5mirrors.php. So"rce2 If /inu+ is our target server platform" or if we plan to compile from source for the Windows platform" choose this distribution format. Building from source on Windows isn%t recommended and isn%t discussed in this book. -nless our situation warrants very special circumstances" the prebuilt Windows binary will suit our needs ,ust fine. This distribution is compressed in Bip6 and ;ip formats. Veep in mind that the contents are identical3 the different compression formats are ,ust there for our convenience. Win*o+s :ip pac;a 'e2 If we plan to use PHP in con,unction with Apache on Windows" we should download this distribution because it%s the focus of the later installation instructions. Win*o+s installer2 This version offers a convenient Windows installer interface for installing and configuring PHP" and support for automatically configuring the II&" PW&" and 2itami servers. Although we could use this version in con,unction with Apache" it is not recommended. Instead" use the Windows ip package version. !urther" if we%re interested in configuring PHP to run with II&" see the later section titled =Installing II& and PHP on Windows.> A recent collaboration between $icrosoft and PHP product and services leader Qend Technologies /td. has resulted in a greatly improved process that is covered in that section.
Downloading Apache Apache is packaged with all mainstream /inu+ distributions" the following page offered a listing of 6C9 mirrors located inC6 global regions0 http055www.apache.org5mirrors5. 1avigate to this page and choose a suitable mirror by clicking the appropriate link. The resulting page will consist of a list of directories representing all pro,ects found under the Apache &oftware !oundation umbrella. )nter the httpd directory. This will take we to the page that includes links to the most recent Apache releases and various related pro,ects and utilities. The distribution is available in two formats0 So"rce2 If our target server platform is /inu+" consider downloading the source code. Although there is certainly nothing wrong with using one of the convenient binary versions" the e+tra time invested in learning how to compile from source will provide we with greater configuration fle+ibility. If our target platform is Windows and we%d like to compile from source" a separate source package intended for the Win@6 platform is available for download. However" note that this chapter does not discuss the Win@6 source installation process. Instead" this chapter focuses on the much more commonplace 'and recommended( binary installer. Binar$2 Binaries are available for a number of operating systems" among them $icrosoft Windows" &un &olaris" and :&56. We%ll find these binaries under the binaries directory.
&o which Apache version should we download[ Although Apache 6 was released more than five years ago" version 9.2 remains in widespread use. In fact" it seems that the ma,ority of shared#server I&Ps have yet to migrate to version 6.2. The reluctance to upgrade doesn%t have anything to do with issues regarding version 6.2" but rather is a testament to the amaing stability and power of version 9.2. !or standard use" the e+ternal differences between the two versions are practically undetectable3 therefore" consider going with Apache 6 to take advantage of its enhanced stability. In fact" if we plan to run Apache on Windows for either development or deployment purposes" it is recommended that we choose version 6 because it is a complete rewrite of the previous Windows distribution and is significantly more stable than its predecessor.
Installin' Apache an* PHP on Win*o+s P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page !'
The installation process follows0 <= &tart the Apache installer by double#clicking the apache_X.X.XX-win32-x86-no_ssl.msi icon. The 2s in this file name represent the latest stable version numbers of the distributions we downloaded in the previous section. >= The installation process begins with a welcome screen. Take a moment to read the screen and then click Ne)t. ?= The license agreement is displayed ne+t. *arefully read through the license. Assuming that we agree with the license stipulations" click Ne)t. 1= A screen containing various items pertinent to the Apache server is displayed ne+t. Take a moment to read through this information and then click Ne)t. 7= We will be prompted for various items pertinent to the server%s operation" including the network domain" the server name" and the administrator%s e#mail address. If we know this information" fill it in now3 otherwise" ,ust enter lo%alhost for the first two items and put in any e#mail address for the last. We can always change this information later in the httpd.conf file. We%ll also be prompted as to whether Apache should run as a service for all users or only for the current user. If we want Apache to automatically start with the operating system" which is recommended" then choose to install Apache as a service for all users. When we%re finished" click Ne)t. 9= We are prompted for a &etup Type0 Typical or *ustom. -nless there is a specific reason we don%t want the Apache documentation installed" choose Typicaland click 1e+t. :therwise" choose *ustom" click 1e+t" and on the ne+t screen" uncheck the Apache
;lobal )nvironment section0 Loa*Mo*"le php9Do*"le c24php94php9apache>=*ll A**T$pe application4,-http*-php =php PHPIni.ir c2Fphp9
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page !(
Because at the time of publication PHP ? wasn%t yet official" we should use the latest stable version of PHP C if we%re planning on running any production applications. To do so" we%ll need to make some minor changes to the previous lines" as follows0
Loa*Mo*"le php7Do*"le c24php74php7apache>=*ll A**T$pe application4,-http*-php =php PHPIni.ir c2Fphp7 <>= ename the php.ini#dist file to php.ini and save it to the *0\php? directory. The php.ini file contains hundreds of directives that are responsible for tweaking PHP%s behavior. The later section =*onfiguring PHP> e+amines php.ini%s purpose and contents in detail. 1ote that we can place this configuration file anywhere we please" but if we choose a nondefault location" we also need to configure PHP using the ##with#config#file#path option. Also note that there is another default configuration file at our disposal" php.ini#recommended. This file sets various nonstandard settings and is intended to better secure and optimie our installation" although this configuration may not be fully compatible with some of the legacy applications. *onsider using this file in lieu of php.ini#dist. = /ocate Apache in the list and make sure that it is started. If it is not started" highlight the label and click &tart the &ervice" located to the left of the label. If it is started" highlight the label and click estart the &ervice" so that the changes made to the httpd.conf file take effect. 1e+t" right#click Apache and choose Properties. )nsure that the startup type is set to Automatic.
Installing Apache and PHP on inu! The installationprocess follows0 <= -nip and untar Apache and PHP. In the following code" the 2 represents the latest stable version
numbers of the distributions we downloaded in the previous section0 '"n:ip http*->D(D((=tar=': tar ,v# http*->D(D((=tar '"n:ip php-((=tar=': tar ,v# php-((=tar
>= *onfigure and build Apache. At a minimum" we%ll want to pass the option Apache to enable the ability to load shared modules0
--e(a;le-so" which tells
c* http*->D(D(( =4con#i'"re --enable-so other optionsJ a;e ?= Install Apache0 a;e install 1= *onfigure" build" and install PHP 'see the section =*onfiguring PHP at Build Time on /inu+> for information regarding modifying installation defaults and incorporating third#party e+tensions into PHP(. In the following steps" APA*H)GI1&TA//G
Email:[email protected] Page ")
c* ==4php-(D(( =4con#i'"re --+ith-ap,s>KAPACHEDINSTALLD.IR4bin4ap,s other optionsJ a;e a;e install 7= PHP comes bundled with a configuration file that controls many aspects of PHP%s behavior. This file is known as php.ini" but it was srcinally named php.ini#dist. We need to copy this file to its appropriate location and rename it php.ini. The later section =*onfiguring PHP> e+amines php.ini%s purpose and contents in detail. 1ote that we can place this configuration file anywhere we please" but if we choose a non default location" we also need to configure PHP using the ##with#config#file#path option. Also note that there is another default configuration file at our disposal" php.ini#recommended. This file sets various nonstandard settings and is intended to better secure and optimie our installation" although this configuration may not be fully compatible with some of the legacy applications. *onsider using this file in lieu of php.ini#dist.To use this file" e+ecute the following command0 cp php=ini-recoen*e* 4"sr4local4lib4php=ini 9= :pen Apache%s configuration file" known as httpd.conf" and verify that the followinglines e+ist. 'The httpd.conf file is located at APA*H)GI1&TA//G
Because at the time of publication PHP ? wasn%t yet official" we should use the latest stable version of PHP C if we%re planning on running any production applications. In the case of PHP C" the lines will look like this0 Loa*Mo*"le php7Do*"le o*"les4libphp7=so A**T$pe application4,-http*-php =php
Believe it or not" that%s it. estart the Apache server with the following command0 4"sr4local4apache>4bin4apachectl restart
Con#i'"rin' PHP <=Enable Short Open Ta's &earch for the line that reads0 shortGopenGtag ] :ff If shortGopenGtag is set to LoffL" tags like L^[L will not be recognised as the start tag for a PHP script. In such a case" to begin a PHP script" you will need to code your script with an opening tag like L^[phpL. &ince many third party PHP scripts use L^[L" setting this to L:ffL will give you more problems than itEs worth" particularly since most" if not all" commercial web hosts that support PHP have no issues with your scripts using L^[L as the open tag. To fi+ this" change it to the following0 shortGopenGtag ] :n P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "
>=Ma'ic 8"otes By default" input data is not escaped with backslashes. That is" if your visitors enter an inverted comma 'single uote( into your web form" the script will receive that unadorned inverted comma 'single uote(. This is for the most part desirable unless you have special reuirements. If you want your input data to have the backslash 'L\L( prefi+" such as" for e+ample" to mimic your web hostEs settings" search for the following0 magicGuotesGgpc ] :ff and replace it with0 magicGuotesGgpc ] :n
?= Re'ister Globals A number of older scripts assume that all data sent by a form will automatically have a PHP variable of the same name. !or e+ample" if your form has an input field with a name of LsomethingL" older PHP scripts assume that the PHP processor will automatically create a variable called _something that contains the value set in that field. If you are running such scripts" you will need to look for the following field0 registerGglobals ] :ff and change it to the following0 registerGglobals ] :n WA1I1;0
1= .ispla$ Errors :n a LliveL website" you typically want errors in your script to be silently logged to a PHP error file. :n your own local machine" however" while you are testing and debugging a PHP script" it is probably more convenient to have error messages sent to the browser window when they appear. This way" you wonEt miss errors if you forget to check the error log file. If you want PHP to display error messages in your browser window" look for the following0 displayGerrors ] :ff And change it to0 displayGerrors ] :n P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "!
This value should always be set to L:ffL for a LliveL website.
7= Session Path If your script uses sessions" look for the following line0 3session.saveGpath ] L5tmpL The session.save_path sets the folder where PHP saves its session files. &ince L5tmpL does not e+ist on Windows" you will need to set it to a directory that does. :ne way is to create a folder called 'say( Lc0\tmpL 'the way you created c0\php earlier(" and point this setting to that folder. If you do that" change the line to the following0 session.saveGpath ] Lc0\tmpL 1otice that in addition to changing the path" I also removed the semi#colon 'L3L( prefi+ from the line. Alternatively" you can find out the current T)$P folder on your computer and use that. :r create a LtmpL folder in your PHP directory" like Lc0\php\tmpL and set the configuration file accordingly. The possibilities are endless. If you canEt decide" ,ust create Lc0\tmpL and do as I said above.
9= SMTP Server If your script uses the mail'( function" and you want the function to successfully send mail on your local machine" look for the following section0 mail functionD 3 !or Win@6 only. &$TP ] localhost smtpGport ] 6C 3 !or Win@6 only. 3sendmailGfrom ] me`e+ample.com *hange it to point to your &$TP server and email account. !or e+ample" if your &$TP server is Lmail.e+ample.comL and your email address is Lyouremail`e+ample.comL" change the code to0 mail functionD &$TP ] mail.e+ample.com smtpGport ] 6C sendmailGfrom ] youremail`e+ample.com
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ""
&NIT-III Ebe**in' PHP Co*e in O"r Web Pa'es
:ne of PHP%s advantages is that we can embed PHP code directly alongside HT$/. !or the code to do anything" the page must be passed to the PHP engine for interpretation. But the Web server doesn%t ,ust pass every page3 rather" it passes only those pages identified by a specific file e+tension 'typically .php( as configured per the instructions in php=ini. But even selectively passing only certain pages to the engine would nonetheless be highly inefficient for the engine to consider every line as a potential PHP command. Therefore" the engine needs some means to immediately determine which areas of the page are PHP#enabled. This is logically accomplished by delimiting the PHP code. There are four delimitation variants" .e#a"lt S$nta,
The default delimiter synta+ opens with ^[php and concludes with [S" like this0 ^h@SWelcome^5h@S ^[php echo L^pS&ome dynamic output here^5pSL3 [S ^pS&ome static output here^5pS If we save this code as test.php and e+ecute it from a PHP#enabled Web server" Short-Ta's
!or less motivated typists an even shorter delimiter synta+ is available. Vnown as short-ta+s, this synta+ forgoes the php reference reuired in the default synta+. However" to use this feature" we need to enable PHP%s shortGopenGtag directive. An e+ample follows0 ^[ print LThis is another PHP e+ample.L3 [S When short#tags synta+ is enabled and we want to uickly escape to and from PHP to output a bit of dynamic te+t" we can omit these statements using an output variation known as short-%ir%&it s*(ta)0 ^[]LThis is another PHP e+ample.L3[S This is functionally euivalent to both of the following variations0 ^[ echo LThis is another PHP e+ample.L3 [S ^[php echo LThis is another PHP e+ample.L3[S Script
PHP support for another mainstream delimiter variant" ^scriptS" is offered0 ^script language]LphpLS print LThis is another PHP e+ample.L3 ^5scriptS P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "#
ASP St$le
$icrosoft A&P pages employ a strategy" delimiting static from dynamic synta+ by using a predefined character pattern" opening dynamic synta+ with ^" and concluding with S. If we%re coming from an A&P background and prefer to continue using this escape synta+" PHP supports it. Here%s an e+ample0 ^ print LThis is another PHP e+ample.L3 S
Ebe**in' M"ltiple Co*e Bloc;s
We can escape to and from PHP as many times as reuired within a given page. !or instance" the following e+ample is perfectly acceptable0 ^htmlS ^headS ^titleS^[php echo LWelcome to my Web siteL3[S^5titleS ^5headS ^bodyS ^[php _date ] Luly 6?" 677KL3 [S ^pSTodayEs date is ^[]_date3[S^5pS ^5bodyS ^5htmlS Coents Sin'le-Line C S$nta,
PHP supports *XX single#line comment synta+" which is prefaced with a double slash '55(" like this0 ^[php 55 Title0 $y first PHP script 55 Author0 ason echo LThis is a PHP programL3 [S Shell S$nta, PHP also supports an alternative to the *XX#style single#line synta+" known as shell s*(ta)" which is prefaced with a hash mark 'Y(
^[php Y Title0 $y PHP program Y Author0 ason echo LThis is a PHP programL3 [S
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "$
M"ltiple-Line C S$nta, PHP also offers a multiple#line variant that can open and close the comment on different lines. Here%s an e+ample0
^[php 5R Title0 $y PHP Program Author0 ason
"ariables in PHP ariables are used for storing values" such as numbers" strings or function results" so that they can be used many times in a script. All variables in PHP start with a _ sign symbol. The correct way of setting a variable in PHP0 _varGname ] value3
PHP is a oosely Typed anguage In PHP a variable does not need to be declared before being set. PHP automatically converts the variable to the correct data type" depending on how they are set. In a strongly typed programming language" you have to declare 'define( the type and name of the variable before using it. In PHP the variable is declared automatically when you use it.
"ariable Na#ing $ules • • •
A variable name must start with a letter or an underscore LGL A variable name can only contain alpha#numeric characters and underscores 'a#Q" 7#8" and G ( A variable name should not contain spaces. If a variable name is more than one word" it should be separated with underscore '_myGstring(" or with capitaliation '_my&tring( %ariable Scope We can declare variables anywhere in a PHP script. The location of the declaration greatly influences the realm in which a variable can be accessed" however. This accessibility domain is known as its s%ope.
PHP variables can be one of four scope types0 Z /ocal variables Z !unction parameters Z ;lobal variables Z &tatic variables Local %ariables A variable declared in a function is considered lo%al. That is" it can be referenced only in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function. 1ote that when you e+it the function in which a local variable has been declared" that variable and its corresponding value are destroyed.
_+ ] J3 function assign+ '( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "%
_+ ] 73 printf'L\_+ inside function is d ^br 5SL" _+(3 assign+'(3 printf'L\_+ outside of function is d ^br 5SL" _+(3 :utput0 _+ inside function is 7 _+ outside of function is J !"nction Paraeters As in many other programming languages" in PHP" any function that accepts arguments must declare those arguments in the function header. Although those arguments accept values that come from outside of the function" they are no longer accessible once the function has e+ited.
!unction parameters are declared after the function name and inside parentheses. They are declared much like a typical variable would be0 55 multiply a value by 97 and return it to the caller function +97 '_value( _value ] _value R 973 return _value3 Global %ariables
In contrast to local variabl es" a +lo;al variable can be accessed in any part of the program. To modify a global variable" however" it must be e+plicitly declared to be global in the function in which it is to be modified. This is accomplished" conveniently enough" by placing the keyword ;/:BA/ in front of the variable that should be recognied as global. Placing this keyword in front of an already e+isting variable tells PHP to use the variable having that name. *onsider an e+ample0 _somevar ] 9C3 function addit'( ;/:BA/ _somevar3 _somevarXX3 echo L&omevar is _somevarL3 addit'(3 The displayed value of _somevar would be 9?. However" if you were to omit this line" ;/:BA/ _somevar3 the variable _somevar would be assigned the value 9 because _somevar would then be considered local within the addit'( function. This local declaration would be implicitly set to 7 and then incremented by 9 to display the value 9. Static %ariables
In contrast to the variables declared as function parameters" which are destroyed on the function%s e+it" a static variable does not lose its value when the function e+its and will still hold that value if the function is called again. Oou can declare a variable as static simply by placing the keyword &TATI* in front of the variable name0 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "&
&TATI* _somevar3 *onsider an e+ample0 function keepGtrack'( &TATI* _count ] 73 _countXX3 echo _count3 echo L^br 5SL3 keepGtrack'(3 keepGtrack'(3 keepGtrack'(3 :utput00 9 6 @
O"tp"t Stateents PHP offers several methods that Web sites will output data to the browser. The print56 Stateent
The print'( statement outputs data passed to it to the browser. Its prototype looks like this0
i(t pri(t5ar+&'e(t6
All of the following are plausible print'( statements0 ^[php print'L^pSI love the summertime.^5pSL(3 [S ^[php _season ] LsummertimeL3 print L^pSI love the _season.^5pSL3 [S The echo56 stateent
We use the echo'( statement for the same purposes as print'(. echo'(%s prototype looks like this0 void echo'string argument9 " ...string argument1D( echo'( is capable of outputting multiple strings. ^[php _heavyweight ] L/enno+ /ewisL3 _lightweight ] L!loyd $ayweatherL3 echo _heavyweight" L and L" _lightweight" L are great fighters.L3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "'
[S The print#56 Stateent
The printf'( statement is ideal when you want to output a blend of static te+t and dynamic information stored within one or several variables. It%s ideal for two reasons. !irst" it neatly separates the static and dynamic data into two distinct sections" allowing for easy maintenance. &econd" printf'( allows you to wield considerable control over how the dynamic information is rendered to the screen in terms of its type" precision" alignment" and position. Its prototype looks like this0
;oolea( pri(tf5stri(+ for'at @, 'i)e$ ar+s6 !or e+ample" suppose you wanted to insert a single dynamic integer value into an otherwise static string0 printf'LBar inventory0 d bottles of tonic water.L" 977(3 In this e+ample" d is a placeholder known as a t*pe spe%ifier" and the $ indicates an integer value will be placed in that position. When the printf'( statement e+ecutes" the lone argument" 977" will be inserted into the placeholder. Table= Co''o(l* =se$ T*pe Spe%ifiers
The following printf'( statement passes in an integer and float value0 printf'Ld bottles of tonic water cost _fL" 977" [email protected](3 When working with decimal values" you can ad,ust the precision using a precision specifier. An e+ample follows0 printf'L_.6fL" [email protected](3 55 [email protected]
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page "(
.atat$pes
A $atat*pe is the generic name assigned to any data sharing a common set of characteristics. *ommon datatypes include Boolean" integer" float" string" and array. Scalar .atat$pes
S%alar datatypes are capable of containing a single item of information. We have scalar datatypes 0 Boolean" integer" float" and string. Boolean
A Boolea( variable represents truth" supporting only two values0 T-) and !A/&). Alternatively" you can use ero to represent !A/&)" and any nonero value to represent T-). A few e+amples follow0 _alive ] false3 55 _alive is false. _alive ] 93 55 _alive is true. _alive ] #93 55 _alive is true. _alive ] C3 55 _alive is true. _alive ] 73 55 _alive is false. Inte'er
An i(te+er is representative of any whole number or" in other words" a number that does not contain fractional parts. PHP supports integer values represented in base 97 'decimal(" base N 'octal(" and base 9? 'he+adecimal( numbering systems. )+0 J6 55 decimal #?KN877 55 decimal 7KCC 55 octal 7+*J) 55 he+adecimal The ma+imum supported integer sie is platform#dependent" although this is typically positive or negative 6 @9 for PHP version C and earlier. PHP ? introduced a ?J#bit integer value" meaning PHP will support integer values up to positive or negative 6 ?@ in sie. !loat !loating#point numbers" also referred to as floats" $o&;les" or real (&';ers" allow you to specify numbers that contain fractional parts. !loats are used to represent monetary values" weights" distances" and a whole host of other representations in which a simple integer value won%t suffice. PHP%s floats can be specified in a variety of ways" each of which is e+emplified here0
J.C?KN J.7 N.KeJ 9.6@)X99
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #)
Strin'
A stri(+ is a seuence of characters treated as a contiguous group. &trings are delimited by single or double uotes" LPHP is a great languageL Lwhoop#de#doL ER8subway\nE L96@_KN8L PHP treated strings in the same fashion as arrays" allowing for specific characters to be accessed via array offset notation. !or e+ample" consider the following string0 _color ] LmaroonL3 Oou could retrieve a particular character of the string by treating the string as an array" like this0 _parser ] _color6D3 55 Assigns ErE to _parser .o"ble 8"otes &trings enclosed in double uotes are the most commonly used in most PHP scripts because they offer the most fle+ibility. This is because both variables and escape seuences will be parsed accordingly. *onsider the following e+ample0
^[php _sport ] Lbo+ingL3 echo LasonEs favorite sport is _sport.L3 [S This e+ample returns the following0 asonEs favorite sport is bo+ing.
Es%ape se&e(%es are also parse$. Co(si$er this e)a'ple: ^[php _output ] LThis is one line.\nAnd this is another line.L3 echo _output3 [S
This ret&r(s the folloi(+ ithi( the ;roser so&r%e: This is one line. And this is another line.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #
Table= Re%o+(ie$ Es%ape Se&e(%es
Sin'le 8"otes )nclosing a string within single uotes is useful when the string should be interpreted e+actly as stated. This means that both variables and escape seuences will not be interpreted when the string is parsed. !or e+ample" consider the following single uoted string0
print EThis string will _print e+actly as it\Es \n declared.E3 This produces the following0 This string will _print e+actly as itEs \n declared.
PHP Strin' !"nctions
strchr56 2 This function returns the rest of the string 'from the matching point(" or !A/&)" if the string to search for is not found. S$nta,2 strchr'string"search(
%!a#ple ^[php echo strchr'LHello worldL"LworldL(3 [S The output of the code above will be0 world strcp562
The strcmp'( function compares two strings. • • •
This7function returns0 # if the two strings are eual ^7 # if string9 is less than string6 S7 # if string9 is greater than string6
Synta! strcmp'string9"string6( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #!
%!a#ple ^[php echo strcmp'LHello worldL"LHello worldL(3 [S The output of the code above will be0 7 strlen562
The strlen'( function returns the length of a string.
Synta! strlen'string(
%!a#ple ^[php echo strlen'LHello worldL(3 [S The output of the code above will be0 96 strpos56 2 The strpos'( function returns the position of the first occurrence of a string inside another string. If the string is not found" this function returns !A/&).
Synta! strpos'string"find"start(
%!a#ple ^[php echo strpos'LHello worldL"LwoL(3 [S The output of the code above will be0 ? strstr56
The strstr'( function searches for the first occurrence of a string inside another string. This function returns the rest of the string 'from the matching point(" or !A/&)" if the string to search for is not found.
Synta! strstr'string"search(
%!a#ple ^[php echo strstr'LHello worldL"LworldL(3 [S The output of the code above will be0 world P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #"
tri#&'( The trim'( function removes whitespaces and other predefined characters from both sides of a string.
Synta! trim'string"charlist(
%!a#ple ^htmlS ^bodyS ^[php _str ] L Hello World L3 echo LWithout trim0 L . _str3 echo L^br 5SL3 echo LWith trim0 L . trim'_str(3 [S ^bodyS ^htmlS The browser output of the code above will be0 Without trim0 Hello World With trim0 Hello World strrev562
The strrev'( function reverses a string.
Synta! strrev'string(
%!a#ple ^[php echo strrev'LHello WorldL(3 [S The output of the code above will be0 dlroW olleH stristr56 2 The stristr'( function searches for the first occurrence of a string inside another string. This function returns the rest of the string 'from the matching point(" or !A/&)" if the string to search for is not found.
Synta! stristr'string"search(
%!a#ple ^[php echo stristr'LHello worldL"LW:/
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ##
ltri56
The ltrim'( function will remove whitespaces or other predefined character from the left side of a string.
Synta! ltrim'string"charlist(
%!a#ple ^htmlS ^bodyS ^[php _str ] L Hello WorldL3 echo LWithout ltrim0 L . _str3 echo L^br 5SL3 echo LWith ltrim0 L . ltrim'_str(3 [S ^bodyS ^htmlS The browser output of the code above will be0 Without ltrim0 Hello World With ltrim0 Hello World
rtri56 The rtrim'( function will remove whitespaces or other predefined character from the right side of a string.
Synta! rtrim'string"charlist(
%!a#ple ) ^htmlS ^bodyS ^[php _str ] LHello World L3 echo LWithout rtrim0 L . _str3 echo L^br 5SL3 echo LWith rtrim0 L . rtrim'_str(3 [S ^bodyS ^htmlS The browser output of the code above will be0 Without rtrim0 Hello World With rtrim0 Hello World
Copo"n* .atat$pes
Co'po&($ $atat*pes allow for multiple items of the same type to be aggregated under a single representative entity. The array and the ob,ect are come into this category. P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #$
Arra$
Arra*" is defined as an inde+ed collection of data values. )ach member of the array inde+ 'alsoknown as the ?e*( references a corresponding value and can be a simple numerical reference to the value%s position in the series" or it could have some direct correlation to the value. _state7D ] LAlabamaL3 _state9D ] LAlaskaL3 _state6D ] LArionaL3 ... _stateJ8D ] LWyomingL3 Instead of having many similar variables" you can store the data as elements in an array. )ach element in the array has its own I< so that it can be easily accessed. There are three different kind of arrays0 N"eric arra$ # An array with a numeric I< key Associative arra$ # An array where each I< key is associated with a value M"lti*iensional arra$# An array containing one or more arrays • • •
N"eric Arra$s A numeric array stores each element with a numeric I< key. There are different ways to create a numeric array. E,aple <
In this e+ample the I< key is automatically assigned0 _names ] array'LPeterL"LFuagmireL"LoeL(3 E,aple >
In this e+ample we assign the I< key manually0 _names7D ] LPeterL3 _names9D ] LFuagmireL3 _names6D ] LoeL3 The I. ;e$s can be "se* in a script2
^[php _names7D ] LPeterL3 _names9D ] LFuagmireL3 _names6D ] LoeL3 echo _names9D . L and L . _names6D . L are L. _names7D . LEs neighborsL3 [S Associative Arra$s P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #%
An associative array" each I< key is associated with a value. When storing data about specific named values" a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them. E,aple <
In this e+ample we use an array to assign ages to the different persons _ages ] array'LPeterL]S@6" LFuagmireL]S@7" LoeL]S@J(3 E,aple >
This e+ample is the same as e+ample 9" but shows a different way of creating the array0 _agesEPeterED ] L@6L3 _agesEFuagmireED ] L@7L3 _agesEoeED ] L@JL3 The I< keys can be used in a script0 ^[php _agesEPeterED ] L@6L3 _agesEFuagmireED ] L@7L3 _agesEoeED ] L@JL3 echo LPeter is L . _agesEPeterED . L years old.L3 [S M"lti*iensional Arra$s
In a multidimensional array" each element in the main array can also be an array. And each element in the sub#array can be an array" and so on. E,aple In this e+ample we create a multidimensional array" with automatically assigned I< keys0 _families ] array ' L;riffinL]Sarray ' LPeterL" L/oisL" L$eganL (" LFuagmireL]Sarray ' L;lennL (" LBrownL]Sarray ' L*levelandL" L/orettaL" LuniorL ( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #&
(3
The array above would look like this if written to the output0 Array ' ;riffinD ]S Array ' 7D ]S Peter 9D ]S /ois 6D ]S $egan ( FuagmireD ]S Array ' 7D ]S ;lenn ( BrownD ]S Array ' 7D ]S *leveland 9D ]S /oretta 6D ]S unior ( ( E,aple > /ets try displaying a single value from the array above0
echo LIs L . _familiesE;riffinED6D . L a part of the ;riffin family[L3 PHP Arra$ !"nctions The array functions allow you to manipulate arrays. arra$56 array'( creates an array" with keys and values. If you skip the keys when you specify an array" an integer key is generated" starting at 7 and increases by 9 for each value.
Synta! array'key ]S value(
%!a#ple ^[php _a]array'LaL]SL
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #'
sort562
The sort'( function sorts an array by the values. This function assigns new keys for the elements in the array. )+isting keys will be removed. This function returns T-) on success" or !A/&) on failure.
Synta! sort'array"sorttype(
%!a#ple ^[php _myGarray ] array'LaL ]S L
The shuffle'( function randomies the order of the elements in the array. This function assigns new keys for the elements in the array. )+isting keys will be removed. This function returns T-) on success" or !A/&) on failure.
Synta! shuffle'array(
%!a#ple ^[php _myGarray ] array'LaL ]S L
pos56
The pos'( function returns the value of the current element in an array. This function is an alias of the current'( function. P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page #(
Synta! pos'array(
%!a#ple ^[php _people ] array'LPeterL" LoeL" L;lennL" L*levelandL(3 echo pos'_people( . L^br 5SL3 [S The output of the code above will be0 Peter arra$Dreverse56
The arrayGreverse'( function returns an array in the reverse order.
Synta! arrayGreverse'array"preserve(
%!a#ple ^[php _a]array'LaL]SL
The sieof'( function counts the elements of an array" or the properties of an ob,ect. This function is an alias of the count'( function.
Synta! sieof'array"mode(
%!a#ple ^[php _people ] array'LPeterL" LoeL" L;lennL" L*levelandL(3 _result ] sieof'_people(3 echo _result3 [S The output of the code above will be0 J
arra$D;e$De,ists56
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $)
The arrayGkeyGe+ists'( function checks an array for a specified key" and returns true if the key e+ists and false if the key does not e+ist.
Synta! arrayGkeyGe+ists'key"array(
%!a#ple ) ^[php _a]array'LaL]SL
The arrayGmerge'( function merges one ore more arrays into one array.
Synta! arrayGmerge'array9"array6"array@...( ^[php _a9]array'LaL]SLHorseL"LbL]SL
Ob3ect
The other compou nd datatype supported by PHP is the o;je%t. The ob,ect is a central concept of the ob,ect#oriented programming paradigm. -nlike the other datatypes" an ob,ect must be e+plicitly declared. This declaration of an ob,ect%s characteristics and behavior takes place within someth ing called a %lass. Here%s a general e+ample of a class definition and subseuent invocation0 class Appliance private _Gpower3 function setPower'_status( _this#SGpower ] _status3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $
... _blender ] new Appliance3
Convertin' Bet+een .atat$pes &sin' T$pe Castin'
*onverting values from one datatype to another is known as t*pe %asti(+. A variable can be evaluated once as a different type by casting it to another. This is accomplished by placing the intended type in front of the variable to be cast.
Table= T*pe Casti(+ perators
)+0 _score ] 'double( 9@3 55 _score ] [email protected] Type casting a double to an integer will result in the integer value being rounded down" regardless of the decimal value. Here%s an e+ample0 _score ] 'int( 9J.N3 55 _score ] 9J Constants A %o(sta(t is a value that cannot be modified throughout the e+ecution of a program. *onstants are particularly useful when working with values that definitely will not reuire modification" such as pi '@.9J9C86( or the number of feet in a mile 'C"6N7(. :nce a constant has been defined" it cannot be changed 'or redefined( at any other point of the program. *onstants are defined using the define'( function. .e#inin' a Constant The define'( function defines a constant by assigning a value to a name. Its prototype follows0 boolean define'string name" mi+ed value " bool caseGinsensitiveD(
)+0 define'LPIL" @.9J9C86(3 The constant is subseuently used in the following listing0 printf'LThe value of pi is fL" PI(3 _pi6 ] 6 R PI3 printf'LPi doubled euals fL" _pi6(3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $!
This code produces the following results0 The value of pi is @.9J9C86. Pi doubled euals ?.6N@9NJ. E,pressions An e)pressio( is a phrase representing a particular action in a program. All e+pressions consist of at least one operand and one or more operators. A few e+amples follow0
_a ] C3 55 assign integer value C to the variable _a _a ] LCL3 55 assign string value LCL to the variable _a _sum ] C7 X _someGint3 55 assign sum of C7 X _someGint to _sum _wine ] LQinfandelL3 55 assign LQinfandelL to the variable _wine _inventoryXX3 55 increment the variable _inventory by 9 Operan*s
pera($s are the inputs of an e+pression. _aXX3 55 _a is the operand _sum ] _val9 X val63 55 _sum" _val9 and _val6 are operands Operators An operator is a symbol that specifies a particular action in an e+pression. Arithetic Operators
The arith'eti% operators" listed in Table @#C" perform various mathematical operations and will probably be used freuently in many of your PHP programs. Table= Arith'eti% perators
Assi'nent Operators The assi+('e(t operators assign a data value to a variable. The simplest form of assignment operator ,ust assigns some value" while perform some other operation before making the assignment. Table= Assi+('e(t perators
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $"
Strin' Operators PHP%s stri(+ operators provide a convenient way in which to concatenate strings together. There are two such operators" including the concatenation operator '.( and the concatenation assignment operator '.](
Table= Stri(+ perators
Increent an* .ecreent Operators The i(%re'e(t 'XX( and $e%re'e(t '##( operators can add 9 to or subtract 9 from the current value of a variable. Table= I(%re'e(t a($ De%re'e(t perators
Lo'ical Operators $uch like the arithm etic operators" logical operators providing a way to make decisions based on the values of multiple variables. 7o+i%al operators make it possible to direct the flow of a program and are used freuently with control structures" such as the if conditional and the while and for loops.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $#
E)"alit$ Operators
E&alit* operators are used to compare two values" testing for euivalence.
Coparison Operators
Co'pariso( operators like logical operators" provide a method to ndirect program flow through an e+amination of the comparative values of two or more variables
Bit+ise Operators
Bitise operators e+amine and manipulate integer values on the level of individual bits that make up the integer value 'thus the name(.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $$
Con*itional Stateents The i# Stateent
The if statement is means for conditional code e+ecution. The following is the synta+0 if 'e+pression( state'e(t E,2 ^[php _d]date'L
The else Stateent
else statement is a way to handle those not meeting the if conditional reuirements" )+0 ^[php _d]date'L
&yn0 if '%o($itio(( %o$e to ;e e)e%&te$ if %o($itio( is tr&e elseif '%o($itio(( %o$e to ;e e)e%&te$ if %o($itio( is tr&e else %o$e to ;e e)e%&te$ if %o($itio( is false E,2 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page
%$ ^[php _d]date'L
The while State#ent The while statement will e+ecute a block of code i# an* as lon' as a condition is true. S$nta,
while '%o($itio(( %o$e to ;e e)e%&te$ 3 E,aple The following e+ample demonstrates a loop that will continue to run as long as the variable i is less than" or eual to C. i will increase by 9 each time the loop runs0
^htmlS P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $&
^bodyS ^[php _i]93 while'_i^]C( echo LThe number is L . _i . L^br 5SL3 _iXX3 [S ^5bodyS ^5htmlS
The do***while State#ent The do...while statement will e+ecute a block of code at least once # it then will repeat the loop as lon' as a condition is true.
S$nta,
do %o$e to ;e e)e%&te$ while '%o($itio((3 E,aple The following e+ample will increment the value of i at least once" and it will continue incrementing the variable i as long as it has a value of less than C0
^htmlS ^bodyS ^[php _i]73 do _iXX3 echo LThe number is L . _i . L^br 5SL3 while '_i^C(3 [S ^5bodyS ^5htmlS
The +or State#ent The for statement is used when you know how many times you want to e+ecute a statement or a list of statements. S$nta,
for 'i(itialiatio(3 %o($itio(3 i(%re'e(t( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $'
%o$e to ;e e)e%&te$ Note2 The for statement has three parameters. The first parameter initialies variables" the second parameter holds the condition" and the third parameter contains the increments reuired to implement the loop. If more than one variable is included in the initialiation or the increment parameter" they should be separated by commas. The condition must evaluate to true or false. E,aple The following e+ample prints the te+t LHello WorldL five times0
^htmlS ^bodyS ^[php for '_i]93 _i^]C3 _iXX( echo LHello World^br 5SL3 [S ^5bodyS ^5htmlS
The +oreach State#ent The foreach statement is used to loop through arrays. !or every loop" the value of the current array element is assigned to _value 'and the array pointer is moved by one( # so on the ne+t loop" youEll be looking at the ne+t element. S$nta,
foreach 'arra* as val&e( %o$e to ;e e)e%&te$
E,aple The following e+ample demonstrates a loop that will print the values of the given array0
^htmlS ^bodyS ^[php _arr]array'LoneL" LtwoL" LthreeL(3 foreach '_arr as _value( echo Lalue0 L . _value . L^br 5SL3 [S ^5bodyS ^5htmlS The contin"e Stateent The continue statement causes e+ecution of the current loop iteration to end and commence at the beginning of the ne+t iteration. !or P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page $(
^[php _usernames ] array'LgraceL"LdorisL"LgaryL"LnateL"LmissingL"LtomL(3 for '_+]73 _+ ^ count'_usernames(3 _+XX( if '_usernames_+D ]] LmissingL( continue3 printf'L&taff member0 s ^br 5SL" _usernames_+D(3 [S
PHP ,unctions reate a PHP ,unction A function is a block of code that can be e+ecuted whenever we need it. *reating PHP functions0 All functions start with the word Lfunction'(L 1ame the function # It should be possible to understand what the function does by its name. The name can start with a letter or underscore 'not a number( Add a LL # The function code starts after the opening curly brace Insert the function code Add a LL # The function is finished by a closing curly brace • •
• • •
E,aple A simple function that writes my name when it is called0
^htmlS ^[php function write$y1ame'( echo LVai im efsnesL3 write$y1ame'(3 [S ^5bodyS ^5htmlS
Use a PHP ,unction 1ow we will use the function in a PHP script0 ^htmlS ^[php function write$y1ame'( echo LVai im efsnesL3 echo LHello world^br 5SL3 echo L$y name is L3 write$y1ame'(3 echo L.^br 5SThatEs right" L3 write$y1ame'(3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %)
echo L is my name.L3[S ^5htmlS The output of the code above will be0 Hello world $y name is Vai im efsnes. ThatEs right" Vai im efsnes is my name.
PHP ,unctions - Adding para#eters :ur first function 'write$y1ame'(( is a very simple function. It only writes a static string. To more functionality a function"after we can parameters. A parameter is ,ust likeThe a variable. Oouadd may have noticed the to parentheses the add function name" like0 write$y1ame'(. parameters are specified inside the parentheses. E,aple < The following e+ample will write different first names" but the same last name0
^htmlS ^bodyS ^[php function write$y1ame'_fname( echo _fname . L efsnes.^br 5SL3 echo L$y name is L3 write$y1ame'LVai imL(3 echo L$y name is L3 write$y1ame'LHegeL(3 echo L$y name is L3 write$y1ame'L&taleL(3 [S ^5bodyS ^5htmlS The output of the code above will be0 $y name is Vai im efsnes. $y name is Hege efsnes. $y name is &tale efsnes. E,aple > The following function has two parameters0
^htmlS ^bodyS ^[php function write$y1ame'_fname"_punctuation( echo _fname . L efsnesL . _punctuation . L^br 5SL3 echo L$y name is L3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %
write$y1ame'LVai imL"L.L(3 echo L$y name is L3 write$y1ame'LHegeL"LL(3 echo L$y name is L3 write$y1ame'L&tleL"L...L(3 [S ^5bodyS ^5htmlS The output of the code above will be0 $y name is Vai im efsnes. $y name is Hege efsnes $y name is &tle efsnes...
PHP ,unctions - $eturn values !unctions can also be used to return values. E,aple
^htmlS ^[php function add'_+"_y( _total ] _+ X _y3 return _total3 echo L9 X 9? ] L . add'9"9?(3 [S ^5htmlS The output of the code above will be0 9 X 9? ] 9K
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %!
-1IT#I ::P%s concepts0 Encaps"lation The practice of separating the user from the true inner workings of an application through well#known interfaces is known as e(%aps&latio(. :b,ect#oriented programming promotes the same notion of hiding the inner workings of the application by publishing well#defined interfaces from which each application component can be accessed. Inheritance Inheritance is the mechanism where child class inherits features from parent class. This strategy promotes code reusability because it assumes that one will be able to use well#designed within numerous applications. Pol$orphis
Pol*'orphis', a term srcinating from the ;reek language that means =having multiple forms"> defines ::P%s ability to redefine" or 'orph" a class%s characteristic or behavior depending upon the conte+t in which it is used. Classes
The vocabulary of ::P" such an embodiment of an entity%s defining attributes and behaviors is known as a %lass. *lasses are intended to represent those real#life items that you%d like to manipulate within an application. *lass contain fiel$s and 'etho$s" class *lassG1ame 55 !ield declarations defined here P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %"
55 $ethod declarations defined here class )mployee private _name3 private _title3 protected _wage3 protected function clockIn'( echo L$ember _this#Sname clocked in at L.date'Lh0i0sL(3 protected function clock:ut'( echo L$ember _this#Sname clocked out at L.date'Lh0i0sL(3 Ob3ects A class provides a basis from which you can create specific instances of the entity the class models" better known as o;je%ts.
:b,ects are created using the new keyword" like this0 _employee ] new )mployee'(3 :nce the ob,ect is created" all of the characteristics and behaviors defined within the class are made available to the newly instantiated ob,ect.
!iel*s !ields are attributes that are intended to describe some aspect of a class. They are uite similar to standard PHP variables" e+cept for a few minor differences" .eclarin' !iel*s The rules regarding field declaration are uite similar to those in place for variable declaration3 essentially" there are none. Because PHP is a loosely typed language" fields don%t even necessarily need to be declared3 they can simply be created and assigned simultaneously by a class ob,ect.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %#
!ields are referred to using the #S operator and" unlike variables" are not prefaced with a dollar sign. !urthermore" because a field%s value typically is specific to a given ob,ect" it is correlated to that ob,ect like this0 _ob,ect#Sfield )+0 _employee#Sname _employee#Stitle _employee#Swage When you refer to a field from within the class in which it is defined" it is still prefaced with the #S operator" although instead of correlating it to the class name" you use the _this keyword. _this implies that you%re referring to the field residing in the same class in which the field is being accessed or manipulated. function set1ame'_name( _this#Sname ] _name3
!iel* Scopes
PHP supports five class field scopes0 p&;li%, private, prote%te$, fi(al, and stati%. P"blic Oou can declare fields in the public scope by prefacing the field with the keyword public.
class )mployee public _name3 55 :ther field and method declarations follow... Public fields can then be manipulated and accessed directly by a corresponding ob,ect" like so0 _employee ] new )mployee'(3 _employee#Sname ] L$ary &wansonL3 _name ] _employee#Sname3 echo L1ew employee0 _nameL3 Private
Private fields are only accessible from within the class in which they are defined. An e+ample follows0 class )mployee private _name3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %$
private _telephone3 !ields designated as private are not directly accessible by an instantiated ob,ect" nor are they available to subclasses. class )mployee private _name3 public function set1ame'_name( _this#Sname ] _name3 _staff ] new )mployee3 _staff#Sset1ame'L$aryL(3 Protecte* Protected variables intend ed for use only within the function" classes can include fields used for solely internal purposes.
class )mployee protected _wage3 Protected fields are also made available to inherited classes for access and manipulation" any attempt by an ob,ect to access a protected field will result in a fatal error !inal $arking a field as fi(al prevents it from being overridden by a subclass"
A finalied field is declared like so0 class )mployee final _ssn3 Properties
&etting Properties The '&tator" or setter method" is responsible for both hiding property assignment implementation and validating class data before assigning it to a class field. Its prototype follows0
;oolea( FFset5@stri(+ propert* (a'e,@'i)e$ val&eFtoFassi+(6 It takes as input a property name and a corresponding value" returning T-) if the method is successfully e+ecuted" and !A/&) otherwise. An e+ample follows0 class )mployee var _name3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %%
function GGset'_prop1ame" _propalue( echo L1one+istent variable0 \__prop1ameL3 _employee ] new )mployee '(3 _employee#Sname ] L$arioL3 _employee#Stitle ] L)+ecutive *hefL3 This results in the following output0 1one+istent variable0 _title Gettin' Properties The a%%essor" or '&tator method" is responsible for encapsulating the code reuired for retrieving a class variable. Its prototype follows0
;oolea( FF+et5@stri(+ propert* (a'e6
It takes as input one parameter" the name of the property whose value you%d like to retrieve. It should return the value T-) on successful e+ecution" and !A/&) otherwise. An e+ample follows0
class )mployee var _name3 var _city3 protected _wage3 function GGget'_prop1ame( echo LGGget called^br 5SL3 _vars ] array'LnameL"LcityL(3 if 'inGarray'_prop1ame" _vars(( return _this#S_prop1ame3 else return L1o such variableL3 _employee ] new )mployee'(3 _employee#Sname ] L$arioL3 echo _employee#Sname.L^br 5SL3 echo _employee#Sage3 This returns the following0 $ario GGget called 1o such variable P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %&
Creatin' C"sto Getters an* Setters
^[php class )mployee private _name3 55 ;etter public function get1ame'( return _this#Sname3 55 &etter public function set1ame'_name( _this#Sname ] _name3 [S Constants
Oou can define %o(sta(ts, or values that are not intended to change" within a class. These values will remain unchanged throughout the lifetime of any ob,ect instantiated from that class. *lass constants are created like so0
const 1A$) ] EA/-)E3 class mathGfunctions const PI ] [email protected]?CE3 const ) ] E6.K9N6N9N6NJE3 const )-/) ] E7.CKK69C??J8E3 55 define other constants and methods here... Metho*s
A 'etho$ is uite similar to a function" e+cept that it is intended to define the behavior of a particular class. /ike a function" a method can accept arguments as input and can return a value to the caller. $ethods are also invoked like functions" e+cept that the method is prefaced with the name of the ob,ect invoking the method" like this0 _ob,ect#SmethodGname'(3 .eclarin' Metho*s
$ethods are created in e+actly the same fashion as functions" using identical synta+. The only difference between methods and normal functions is that the method declaration is typically prefaced with a scope descriptor. The generalied synta+ follows0 scope function function1ame'( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %'
55 !unction body goes here )+0 public function calculate&alary'( return _this#Swage R _this#Shours3 Invo;in' Metho*s
_employee ] new )mployee'LanieL(3 _salary ] _employee#Scalculate&alary'(3 Metho* Scopes
PHP supports si+ method scopes0 p&;li%, private, prote%te$, a;stra%t, fi(al, and stati%.
P"blic
Public methods can be accessed from anywhere at any time. Oou declare a public method by prefacing it with the keyword public
^[php class isitors public function greetisitor'( echo LHello^br 5SL3 function say;oodbye'( echo L;oodbye^br 5SL3 isitors00greetisitor'(3 _visitor ] new isitors'(3 _visitor#Ssay;oodbye'(3 [S The following is the result0 Hello ;oodbye Private P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page %(
$ethods marked as private are available for use only within the srcinating class and cannot be called by the instantiated ob,ect" nor by any of the srcinating class%s subclasses private function validate*ard1umber'_number( if ''_a^_b( return !A/&)3 else return T-)3 Attempts to call this method from an instantiated ob,ect result in a fatal error. Protecte* *lass methods marked as prote%te$ are available only to the srcinating class and its subclasses. &uch methods might be used for helping the class or subclass perform internal computations.
^[php class )mployee private _ein3 function GGconstruct'_ein( if '_this#Sverify)I1'_ein(( echo L)I1 verified. !inishL3
protected function verify)I1'_ein( return T-)3 _employee ] new )mployee'L96@#JC#?KN8L(3 [S Abstract
A;stra%t methods are special in that they are declared only within a parent class but are implemented in child classes. :nly classes declared as a;stra%t can contain abstract methods. Abstract methods are declared like this0
a;stra%t f&(%tio( 'etho$Na'e56 E,2 abstract class )mployee abstract function hire'(3 abstract function fire'(3 abstract function promote'(3 abstract demote'(3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &)
!inal $arking a method as fi(al prevents it from being overridden by a subclass. A finalied method is declared like this0
class )mployee ... final function get1ame'( ...
T$pe Hintin'
T*pe hi(ti(+ ensures that the ob,ect being passed to the method is indeed a member of the e+pected class. !or e+ample" it makes sense that only ob,ects of class )mployee should be passed to the take/unchbreak'( method. private function take/unchbreak')mployee _employee( ...
Constr"ctors A constructor is defined as a block of code that automatically e+ecutes at the time of ob,ect instantiation. ::P constructors offer a number of advantages0
Z *onstructors can accept parameters" which are assigned to specific ob,ect fields at creation time. Z *onstructors can call class methods or other functions. Z *lass constructors can call on other constructors" including those from the class parent. PHP recognies constructors by the name GGconstruct. The general synta+ for constructor declaration follows0 function GGconstruct'argument9" argument6" ..." argument1D( 55 *lass initialiation code
^[php class Book private _title3 private _isbn3 private _copies3 public function Gconstruct'_isbn( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &
_this#SsetIsbn'_isbn(3 _this#SgetTitle'(3 _this#Sget1umber*opies'(3 public function setIsbn'_isbn( _this#Sisbn ] _isbn3 public function getTitle'( _this#Stitle ] LBeginning PythonL3 print LTitle0 L._this#Stitle.L^br 5SL3 public function get1umber*opies'( _this#Scopies ] LCL3 print L1umber copies available0 L._this#Scopies.L^br 5SL3 _book ] new book'L9C87C8C982L(3 [S This results in the following0 Title0 Beginning Python 1umber copies available0 C
Invo;in' Parent Constr"ctors
PHP does not automatically call the parent constructor3 you must call it e+plicitly using the parent keyword. An e+ample follows0 ^[php class )mployee protected _name3 protected _title3 function GGconstruct'( echo L^pS&taff constructor called^5pSL3 class $anager e+tends )mployee function GGconstruct'( parent00GGconstruct'(3 echo L^pS$anager constructor called^5pSL3 _employee ] new $anager'(3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &!
[S This results in the following0 )mployee constructor called $anager constructor called Invo;in' &nrelate* Constr"ctors Oou can invoke class constructors that don%t have any relation to the instantiated ob,ect simply by prefacing GGconstructor with the class name" like so0
classname00GGconstruct'( )+0 )mployee00GGconstruct'( .estr"ctors :b,ects were automatically destroyed upon script completion
An e+ample follows0 ^[php class Book private _title3 private _isbn3 private _copies3 function GGconstruct'_isbn( echo L^pSBook class instance created.^5pSL3 function GGdestruct'( echo L^pSBook class instance destroyed.^5pSL3 _book ] new Book'L9N8@99CNC6L(3 [S Here%s the result0 Book class instance created. Book class instance destroyed. When the script is complete" PHP will destroy any ob,ects that reside in memory. Therefore" if the instantiated class and any information created as a result of the instantiation reside in memory" you%re not reuired to e+plicitly declare a destructor. Static Class Mebers !ields are declared as static" any changes made to its value are reflected across all instantiated ob,ects.
^[php class isitor P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &"
private static _visitors ] 73 function GGconstruct'( self00_visitorsXX3 static function getisitors'( return self00_visitors3 5R Instantiate the isitor class. R5 _visits ] new isitor'(3 echo isitor00getisitors'(.L^br 5SL3 5R Instantiate another isitor class. R5 _visits6 ] new isitor'(3 echo isitor00getisitors'(.L^br 5SL3 [S The results are as follows0 9 6
The instanceo# e$+or* The instanceof keyword was introduced with PHP C. With it you can determine whether an ob,ect is an instance of a class" is a subclass of a class" or implements a particular interface" and do something accordingly.
!or e+ample" suppose you want to learn whether an ob,ect called manager is derived from the class )mployee0 _manager ] new )mployee'(3 ... if '_manager instanceof )mployee( echo LOesL3
Class Inheritance class inheritance is accomplished by using the e+tends keyword.
)+0 first creating an )mployee class and then creating an )+ecutive class that inherits from )mployee. ^[php class )mployee private _name3 function set1ame'_name( if '_name ]] LL( echo L1ame cannot be blankL3 else _this#Sname ] _name3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page
function get1ame'( return L$y name is L._this#Sname.L^br 5SL3 class )+ecutive e+tends )mployee function pillage*ompany'( echo LIEm selling company assets to finance my yachtL3 _e+ec ] new )+ecutive'(3 _e+ec#Sset1ame'LichardL(3 echo _e+ec#Sget1ame'(3 _e+ec#Spillage*ompany'(3 [S This returns the following0 $y name is ichard. IEm selling company assets to finance my yacht Inheritance an* Constr"ctors If a parent class offers a constructor" it does e+ecute when the child class is instantiated" provided that the child class does not also have a constructor.
function GGconstruct'_name( _this#Sset1ame'_name(3 Then you instantiate the *): class and retrieve the name member0 _ceo ] new *):'L
It will yield the following0 $y name is
Email:[email protected] Page &$
When it comes time to retrieve the name member" you find that it%s blank because the set1ame'( method" which e+ecutes in the )mployee constructor" never fires.
you%re uite likely going to want those parent constructors to also fire function GGconstruct'_name( parent00GGconstruct'_name(3 echo L^pS*): ob,ect created^5pSL3 Again instantiating the *): class and e+ecuting get1ame'( in the same fashion as before" this time you%ll see a different outcome0 *): ob,ect created $y name is
Inter#aces An i(terfa%e defines a general specification for implementing a particular service" declaring the reuired functions and constants without specifying e+actly how it must be implemented. Implementation details aren%t provided because different entities might need to implement the published method definitions in different ways.
interface Iinterface1ame *:1&T 93 ... *:1&T 13 function method1ame9'(3 ... function method1ame1'(3
The contract is completed when a class i'ple'e(ts the interface via the implements keyword. All methods must be implemented" or the implementing class must be declared a;stra%t 'a concept introduced in the ne+t section(3 otherwise" an error similar to the following will occur0 class *lassG1ame implements interface1ame function method1ame9'( 55 method1ame9'( implementation function method1ame1'( 55 method1ame9'( implementation P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &%
Ipleentin' a Sin'le Inter#ace interface IPillage function emptyBankAccount'(3 function burn
This interface is then implemented for use by the )+ecutive class0 class )+ecutive e+tends )mployee implements IPillage private _total&tock:ptions3 function emptyBankAccount'( echo L*all *!: and ask to transfer funds to &wiss bank account.L3 function burn
Ipleentin' M"ltiple Inter#aces
^[php interface I)mployee ... interface I
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &&
Abstract classes ensure conformity because any classes derived from them must implement all abstract methods derived within the class. Attempting to forgo implementation of any abstract method defined in the class results in a fatal error.
Coo;ies
&NIT-%
*ookies are files that get written to a temporary file on a user%s computer by a web application. *ookies store information that can be read by the online application" thus authenticating a user as uniue. By allowing a web application to identify whether a user is uniue" the application can then perform login scripts and other functionality. The problem with cookies is that because they are stored on a user%s computer" they have developed a bad rap as being highly insecure. And because of possible insecurities with cookies" users have begun to turn them off in their browser security settings3 in fact" users often do not accept cookies. *ookies themselves are not bad or insecure if used correctly by a developer. However" since users have the ability to turn them off 'and since the actual cookie must be stored on the user%s computer(" most good developers have migrated their code to sessions.
Settin' Coo;ies To be able to use cookies and store values in them" we must first set a cookie on a user%s computer. By using the different parameters" we can customie the way the cookie works for us. The way to set a cookie is by using the function setcookie'(" which has the following prototype0 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &'
;ool se!coo"ie 5 stri(+ (a'e @, stri(+ val&e @, i(t e)pire @, stri(+ path @, stri(+ $o'ai( @, ;ool se%&re 6
setcookie'( Para'eters
E,aple 2
^[php _;/:BA/&EusernameED ] LtestL3 _;/:BA/&EpasswordED ] LtestL3 function validatelogin '_username" _password( if 'strcmp '_username" _;/:BA/&EusernameED( ]] 7 strcmp '_password" _;/:BA/&EpasswordED( ]] 7( setcookie 'LcookieGuserL" _username" time'(X?7R?7R6JR@7(3 setcookie 'LcookieGpassL" mdC '_password(" time'(X?7R?7R6JR@7(3 return true3 else return false3 if 'validatelogin 'LtestL"LtestL(( echo L&uccessfully logged in.L3 else echo L&orry" invalid login.L3 [S
Rea*in' Coo;ies The PHP _G*::VI) variable is used to retrieve a cookie value. The following script allows we to determine if we are properly logged inusing a function that returns a true value upon proper validation of login. E,aple2
^[php _;/:BA/&EusernameED ] LtestL3 _;/:BA/&EpasswordED ] LtestL3 setcookie 'LcookieGuserL" LtestL" time'(X?7R?7R6JR@7(3 setcookie 'LcookieGpassL" mdC 'LtestL(" time'(X?7R?7R6JR@7(3 function validatelogin '( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page &(
if 'strcmp '_G*::VI)EcookieGuserED" _;/:BA/&EusernameED( ]] 7 strcmp '_G*::VI)EcookieGpassED" mdC '_;/:BA/&EpasswordED(( ]] 7( return true3 else return false3 if 'validatelogin '(( echo L&uccessfully logged in.L3 else echo L&orry" invalid login.L3 [S
.eletin' Coo;ies We should note that cookies will disappear by themselves if we have set them up to do so. *ookies that have not been assigned a time to die will simply be removed when the browser window closes. &ometimes" however" a user will want to be able to clear the cookies on a site. &uch functionality typically goes by the name of =logout> and is a staple of a well#programmed user interface. ^[php setcookie 'LcookieGuserL" LtestL" time'(X?7R?7R6JR@7(3 setcookie 'LcookieGpassL" mdC 'LtestL(" time'(X?7R?7R6JR@7(3 function logout '( 55To remove a cookie" we simply set the value of the cookie to blank. setcookie 'LcookieGuserL" LL" time'(X?7R?7R6JR@7(3 setcookie 'LcookieGpassL" LL" time'(X?7R?7R6JR@7(3 55We call the logout script. logout'(3 55We can no longer access the cookies. echo _G*::VI)EcookieGuserED . L^br 5SL3 echo LWe have successfully logged out.L3 [S Another e+ample0 When deleting a cookie we should assure that the e+piration date is in the past.
HTTP Hea*ers HTTP headers have powerful sets of functionality. The most important aspect to remember about headers is that they can be called only before any output has been written to the web page. If we attempt to call a header after output has been sent to the page" we will generate an error3 hence" our script will fail on us. We can use them to control everything" including setting the current page location" finding out what file format is being displayed" and managing all aspects of the browser cache. P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ')
The header '( function%s prototype is as follows0 void hea*er ' string string " bool replace " int httpGresponseGcodeDD (
Re*irectin' to a .i##erent Location :ne of the more common uses for HTTP headers is redirecting a script. By using headers inside processing scripts" we can force the browser to return to any page we want. We prefer to use headers to control e+ception handling within process scripts. The E, Co*e2 ^html ^titleS&le ^5titleS ^5headS ^bodyS ^form action]Lsample.phpL method]LpostLS 1ame0 ^input type]Lte+tL name]LwernameL ma+length]L9C7L 5S^br 5S ^input type]LsubmitL value]L&ubmitL style]Lmargin#top0 97p+3L 5S ^5formS ^5bodyS ^5htmlS
The form in the previous block of code will then call the processing statement as follows0
&le.php0 ^[php if 'trim '_GP:&TEwernameED( ]] LL( header 'L/ocation0 sample96GC.htmlL(3 e+it3 echo _GP:&TEwernameED3 [S
Sen*in' Content T$pes Other Than HTML We will want to use the header '( function to output a type of file format that may not be an actual web page. To make the most out of this function" we can effectively output other file types by simply declaring the content type we want to output. This functionality can be handy in circumstances where we want to deploy a document to a user or perhaps even output a dynamic image. )+ample 0 ^html S ^titleS&le ^5titleS ^5headS ^bodyS ^div align]LcenterLS ^img src]Lsample9.phpL alt]LL title]LL style]Lborder0 none3L 5S ^5divS P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '
^5bodyS ^5htmlS &le9.php ^[php _path ] Limages5winter.,pgL3 try if 'isGfile '_path(( if '_file ] fopen'_path" ErbE(( while'feof'_file( and 'connectionGstatus'(]]7(( _f .] fread'_file" 976JRN(3 fclose'_file(3 header 'L*ontent#type0 image5,pegL(3 print _f3 else throw new e+ception 'L&orry" file path is not valid.L(3 catch 'e+ception _e( echo =e+ception>._e3 [S
Co''o( >ile >or'at Co(te(t T*pes
!orcin' !ile Save As .o+nloa*s We can use the header '( function to force a &ave As dialog bo+ to appear for the user to accept a download. Web browsers can output many different file types directly onto the screen" the default when we use headers to output a wide variety of file types is to make them automatically appear on the screen. The *ode ^[php 55The location of the image. _path ] Limages5winter.,pgL3 try if 'isGfile '_path(( if '_file ] fopen'_path" ErbE(( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '!
while'feof'_file( and 'connectionGstatus'(]]7(( _f .] fread'_file" 976JRN(3 fclose'_file(3 55-se the header function to output an image of .,pg. _outputname ] LmyimageL3 header 'L*ontent#type0 image5,pegL(3 55This will force a download. header'L*ontent#disposition0 attachment3 filename]L._outputname.L.,pgL(3 print _f3 else throw new e+ception 'L&orry" file path is not valid.L(3 catch 'e+ception _e( echo _e#Sgetmessage'(3 [S By making content#disposition an attachment value" the browser will force a download rather than display the file inline. By using this" we can force the download to appear with any particular filename we prefer and also with pretty much any file e+tension. By using content#type" we force the browser to output a file of the reuested type.
Sessions *ookies are getting less and less trusted as a solution" sessio(s created. &essions are handled much like cookies but with a ma,or difference. While cookies are declared as global members of the site" a session state must be enabled to use them effectively. While in the session state" sessions can be accessed ,ust like cookies" in a global sense" and can be manipulated" added to" or removed with relative ease. Sessions "ses2 When we are working with an application" we open it" do some changes and then we close it. This is much like a &ession. The computer knows who we are. It knows when we start the application and when we end. But on the internet there is one problem0 the web server does not know who we are and what we do because the HTTP address doesnEt maintain state. A PHP session solves this problem by allowing us to store user information on the server for later use 'i.e. username" shopping items" etc(. However" session information is temporary and will be deleted after the user has left the website. If we need a permanent storage we may want to store the data in a database. &essions work by creating a uniue id '-I<( for each visitor and store variables based on this -I<. The -I< is either stored in a cookie or is propagated in the -/ Creatin' Sessions2 We create a session state using the sessionGstart'( function and then use and access these session values using the _G&)&&I:1 superglobal. -sing the superglobal" we can then add to"
remove" or modify the session values. We can use the sessions anywhere the session state is enabled" which means the sessionGstart'( function needs to be called at the beginning of every page where we want session access. When we have finished with the sessions"we can simply use the unset'( function on the session values and finish off the session state using the sessionGdestroy'( function. The prototypes for these session#related functions are as follows0 bool sessionDstart ' void ( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '"
bool sessionGdestroy ' void ( The Co*e2 ^[php 55!irst" create a session states. sessionGstart'(3 _;/:BA/&EuserED ] LtestL3 _;/:BA/&EpassED ] LtestL3 551ow" here is a function that will log we in. function login '_username" _password( if 'strcmp '_username" _;/:BA/&EuserED( ]] 7 strcmp '_password" _;/:BA/&EpassED( ]] 7( _G&)&&I:1EuserED ] _username3 _G&)&&I:1EpassED ] mdC '_password(3 return true3 else return false3 55!unction to logout. function logout '( unset '_G&)&&I:1EuserED(3 unset '_G&)&&I:1EpassED(3 sessionGdestroy'(3 551ow" we can login. if 'login'LtestL"LtestL(( echo L&uccessfully logged in with user0 L . _G&)&&I:1EuserED. L and pass0 L . _G&)&&I:1EpassED3 else echo L*ould not login.L3 551ow" we logout. logout'(3 if 'isset '_G&)&&I:1EuserED(( echo _G&)&&I:1EuserED3 55:utputs nothing. [S Storin' Siple .ata T$pes in Sessions &essions handle simple data types" and they handle them well. /ike any PHP variable" however" the data type of a current session is based upon what was last assigned to it and can be changed uite easily. The following e+ample passes three values by session0 an integer" a string" and a floating#point value. &essions that have been set can be called and accessed from anywhere within the scope of the session state. The Co*e ^[php 55!irst" create a session states. sessionGstart'(3 'int( _G&)&&I:1EintegerGvalueED ] L99CL3 'string( _G&)&&I:1EstringGvalueED ] LHello WorldL3 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '#
'float( _G&)&&I:1EfloatGvalueED ] L9.7KL3 function outputsessions '( echo _G&)&&I:1EintegerGvalueED . L^br 5SL3 55:utputs 99C. echo _G&)&&I:1EstringGvalueED . L^br 5SL3 55:utputs Hello World. echo _G&)&&I:1EfloatGvalueED . L^br 5SL3 55:utputs 9.7K. 55Then we can call the function from here0 outputsessions'(3 [S
Storin' Cople, .ata T$pes in Sessions :ne of the ma,or improvements to PHP C is the ability to store comple+ data types within a session .-sing this techniue"we can easily store large uantities of data within a single ob,ect 'such as a shopping cart ob,ect(" use the functionality within the session for these purposes" and then pass the data along to other pages. The Co*e ^[php 55!irst" create a session states. sessionGstart'(3 class myclass protected _myvalue3 public function setmyvalue '_newvalue( _this#Smyvalue ] _newvalue3 public function getmyvalue '( return _this#Smyvalue3 _G&)&&I:1EmyclassGvalueED ] new myclass '(3 function outputsessions '( _G&)&&I:1EmyclassGvalueED#Ssetmyvalue 'LHello WorldL(3 echo _G&)&&I:1EmyclassGvalueED#Sgetmyvalue '(3 55Then we can call the function from here0 outputsessions'(3 [S
A"thenticatin' O"r &sers We need to create a way of authenticating our users so that we know we have a valid user accessing the site. We can handle authentication in a variety of ways" but the two most common methods for securing a file or set of files is through HTTPbased authentication and through cookie authentication.
Coo;ie A"thentication $anaging user authentication through cookies or sessions is a little harder than using HTTPbased Authentication. The nice features of cookie#based authentication are being able to set our own error messages" being able to control what happens upon login" and being allowed to make our login form P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '$
blend seamlessly into our application. By comparing *ookies vs &essions" the advantages of sessions being kept on the server side and working on any platform and by using sessions we will know that our script should work on pretty much any platform and will be a reliable" secure way of handling authentication. The Co*e ^[php sessionGstart'(3 [S ^html S ^titleS&le ^5titleS
^[php 551ormally wer username and pass would be stored in a database. 55!or this e+ample we will assume that we have already retrieved them. _;/:BA/&EuserED ] LtestL3 _;/:BA/&EpassED ] LtestL3 if 'isset '_GP:&TEuserED( isset '_GP:&TEpassED(( if 'strcmp '_GP:&TEuserED" _;/:BA/&EuserED( ]] 7 strcmp '_GP:&TEpassED" _;/:BA/&EpassED( ]] 7( _G&)&&I:1EuserED ] _GP:&TEuserED3 _G&)&&I:1EpassED ] _GP:&TEpassED3 else [S^div align]LcenterLS^p style]Lcolor0 Y!!77773LS &orry" we have entered an incorrect login.^5pS^5divS^[php 55*heck if we need to logout. if '_GP:&TElogoutED ]] LyesL( unset '_G&)&&I:1EuserED(3 unset '_G&)&&I:1EpassED(3 sessionGdestroy'(3 55We then use this function on every page to check for a valid login at all times. function checkcookies '( if 'strcmp '_G&)&&I:1EuserED" _;/:BA/&EuserED( ]] 7 ➥ strcmp '_G&)&&I:1EpassED" _;/:BA/&EpassED( ]] 7( return true3 else return false3 [S P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '%
^5headS ^bodyS ^div align]LcenterLS ^[php 55*heck if we have a valid login. if 'checkcookies'(( [S ^pS*ongratulations" we are logged in^5pS ^form action]Lsample96G9K.htmlL method]LpostL style]Lmargin0 7p+3LS ^input type]LhiddenL name]LlogoutL value]LyesL 5S ^input type]LsubmitL value]L/ogoutL 5S ^5formS ^[php 55:r else present a login form. else [S ^form action]Lsample96G9K.htmlL method]LpostL style]Lmargin0 7p+3LS ^div style]Lwidth0 C77p+3 margin#bottom0 97p+3LS ^div style]Lwidth0 @C3 float0 left3 te+t#align0 left3LS -sername0 ^5divS ^div style]Lwidth0 ?J3 float0 right3 te+t#align0 left3LS ^input type]Lte+tL name]LuserL ma+length]L6CL 5S ^5divS ^br style]Lclear0 both3L 5S ^5divS ^div style]Lwidth0 C77p+3 margin#bottom0 97p+3LS ^div style]Lwidth0 @C3 float0 left3 te+t#align0 left3LS Password0 ^5divS ^div style]Lwidth0 ?J3 float0 right3 te+t#align0 left3LS ^input type]LpasswordL name]LpassL ma+length]L6CL 5S ^5divS ^br style]Lclear0 both3L 5S ^5divS ^div style]Lwidth0 C77p+3 te+t#align0 left3LS ^input type]LsubmitL value]L/oginL 5S^5divS ^5formS ^[php [S ^5divS ^5bodyS ^5htmlS If the script detects that we have submitted a username and password" it will then check for a valid match and set proper sessions upon the match. If the system detects that the sessions are already in place and are proper 'as handled by the checkcookies'( function(" it does not display the login form and instead displays a means to log out. The logout algorithm is handled in mostly the same way. If the script detects a logout field is in place" it then goes through the algorithm to kill off the session variables. P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '&
&sin' Environent an* Con#i'"ration %ariables PHP provides a means to use and verify the configuration settings and environment variables relative to the server space the script is occupying. By having access to environment variables" we can customie our scripts to work optimally on the platform that is available. By having access to the configuration variables of PHP" we can customie the PHP environment our script is working in for special occurrences. A common use of the environment variables in PHP is for dynamic imaging. While Windows systems commonly store their fonts in one folder" /inu+#based systems keep theirs in another. By using PHP%s environment variables to determine the current operating system" we can make our code slightly more portable. -sing configuration variables can also come in uite handy" particularly with file upload scripts. The base PHP installation leaves only enough processing time to upload files that are generally 6$B or smaller in sie. By manipulating the PHP configuration files temporarily" we can increase the limit enough to allow a script to process much larger files.
Rea*in' Environent an* Con#i'"ration %ariables The _G)1 superglobal is PHP%s method for reading a system%s environment variables and has an argument set that is based upon the current environment that is available to it. Because of its relative fle+ibility" there is no real set argument list" as it is generated based on the current server environment. We can use the phpinfo'( function to determine the current environment variables" and we can retrieve them using the getenv'( function" which needs to be supplied a valid environment variable name. eading configuration variables" takes place through two functions" iniGget'( and iniGgetGall'(. The function iniGget'( will retrieve the value of a specified configuration variable" and the function iniGgetGall'( will retrieve an array filled with the entire selection of configuration variables that are available. The Co*e ^[php 55Here is an e+ample of retrieving an environmental variable or two. echo _G)1EProgram!ilesED . L^br 5SL3 55:utputs *0\Program !iles. echo _G)1E*:$P-T)1A$)ED . L^br 5SL3 55:utputs AI T)A. echo getenv'L*:$P-T)1A$)L( . L^br 5SL3 55Also :utputs AI T)A.
551ow" letEs look at reading configuration variables. echo iniGget 'LpostGma+GsieL( . L^br 5SL3 55:utputs N$B. 55And we can output the entire listing with this function. printGr 'iniGgetGall'((3 [S
Settin' Environent an* Con#i'"ration %ariables To set )nvironment ariables While working with environment variables" we need to assign a new value to the _G)1 superglobal to process a temporary change. The change will be in effect for the script%s duration. P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ''
The same applies for configuration variables but with a different approach. To set a configuration variable" we have to use the PHP function iniGset'(" which will allow us to set a configuration variable for the script%s duration. :nce the script finishes e+ecuting" the configuration variable will return to its srcinal state. The prototype for iniGset'( is as follows0 string iniDset ' string varname" string newvalue ( The code ^[php 55&etting an environment variable in php is as easy as assigning it. echo _G)1E*:$P-T)1A$)ED . L^br 5SL3 55 )choes BABI1Q#*:<)Q. _G)1E*:$P-T)1A$)ED ] LHello WorldL3 echo _G)1E*:$P-T)1A$)ED . L^br 5SL3 55)choes the new *:$P-T)1A$). echo iniGget 'EpostGma+GsieE(3 55)choes N$B. 55Then we set it to 677$ for the duration of the script. iniGset'EpostGma+GsieE"E677$E(3 55Any files that are to be uploaded in this script will be :V up to 677$. [S
.ate an* Tie !"nctions
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page '(
*ate56 2 eturns a string formatted according to the given format string using the given integer ti'esta'p or the current time if no timestamp is given. In other words" ti'esta'p is optional and defaults to the value of time'(. S$n2 string *ate ' string _format " int _timestampD (
#orma!
character
.escription
Da*
###
E,apleret"rne*val"es
###
$
0! to !
D
A te+tual representation of a day" three letters
4o( through S&(
j
! to !
l 'lowercase E/E(
A full te+tual representation of the day of the week
S&($a* through Sat&r$a*
N
I&:#N?79 numeric representation of the day of the week 'added in PHP C.9.7(
! 'for $onday( through # 'for &unday(
S
)nglish ordinal suffi+ for the day of the month" 6 characters
st" ($" r$ or th. Works well with j
1umeric representation of the day of the week
0 'for &unday( through 'for &aturday( 0 through 2
The day of the year 'starting from 7(
ee?
###
###
I&:#N?79 week number of year" weeks starting on $onday 'added in PHP J.9.7(
)+ample0 "/ 'the J6nd week in the year(
4o(th
###
###
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ()
#orma!
.escription
E,apleret"rne*val"es
>
A full te+tual representation of a month" such as anuary or $arch
3a(&ar* through De%e';er
'
1umeric representation of a month" with leading eros
0! through !/
4
A short te+tual representation of a month" three letters
3a( through De%
(
1umeric representation of a month" without leading eros
! through !/
t
1umber of days in the given month
/8 through !
Hear
###
###
7
Whether itEs a leap year
! if it is a leap year" 0 otherwise.
o
I&:#N?79 year number. This has the same value as H" e+cept that if the I&: week number '( belongs to the previous or ne+t year" that year is used instead. 'added in PHP C.9.7(
)+amples0 !999 or /00
H
A full numeric representation of a year" J digits
)+amples0 !999 or /00
character
*
A two digit representation of a year
99 or 0
)+amples0
Ti'e
###
###
a
/owercase Ante meridiem and Post meridiem
a' or p'
A
-ppercase Ante meridiem and Post meridiem
A4 or P4
B
&watch Internet time 96#hour format of an hour without leading eros
000 through 999
+
! through !/
G
6J#hour format of an hour without leading eros
0 through /
h
96#hour format of an hour with leading eros
0! through !/
6J#hour format of an hour with leading eros
00 through /
i
$inutes with leading eros
00 to 29
s
&econds" with leading eros
00 through 29
& Ti'eo(e
$illiseconds 'added in PHP C.6.6(
)+ample0
2"/!
###
###
e
Timeone identifier 'added in PHP C.9.7(
)+amples0 =TC" G4T" Atla(ti%Aores
I 'capital i(
Whether or not the date is in daylight saving time
! if
)+ample0 0/00
P
)+ample0 0/:00
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page (
#orma!
.escription
E,apleret"rne*val"es
T
Timeoneabbreviation
)+amples0 EST" 4DT ...
J
Timeone offset in seconds. The offset for timeones west of -T* is always negative" and for those east of -T* is always positive.
-"/00 through 20"00
>&ll DateTi'e
###
###
character
%
I&: N?79 date 'added in PHP C(
677J#76#96T9C098069X77077
r
!* 6N66 formatted date
)+ample0 Th&, /! De% /000 !:0!:0# 0/00
=
&econds since the -ni+ )poch 'anuary 9 98K7 77077077 ;$T(
&ee also time'(
# # # # #
date$%& ', (, g:i a%)* date$%m.d.y%)* date$%', n, (%)* date$%(md%)* date$h-i-s, '-m-y, it is ay )*
// // // // //
March 10, 2012, 5:1 pm 0+.10.01 10, +, 2012 20120+10 05-1-1, 10-0+-01, 1+1 11! &
# # # #
date$it is the '3 day.)* date$% M ' :i:s 6 (%)* date$7:m:s m is month)* date$%7:i:s%)*
// // // //
4t is the 10th day. 3at Mar 10 15:1:0! M36 2012 1:0+:1 m is month 1:1:1
;tie56 2This method mainly used to work with specific date eturns the -ni+ timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the -ni+ )poch 'anuary 9 98K7 77077077 ;$T( and the time specified. Arguments may be left out in order from right to left3 any arguments thus omitted will be set to the current value according to the local date and time.
date$%M-d-(%, date$%M-d-(%, date$%M-d-(%, date$%M-d-(%,
m9time$0, m9time$0, m9time$0, m9time$0,
0, 0, 0, 0,
0, 0, 0, 0,
12, +2, 2012))* 1+, 1, 201))* 1, 1, 201!))* 1, 1, 1;;0))*
strtotie56 2 convert dates in the form of )nglish#language strings into -ni+ timestamps using the strtotime'( function. Z We can use two#digit years '77M?8 ] 6777s" K7M88 ] 9877s( and four#digit years. An unformatted four# digit number in isolation will be treated as a time3 that is" 677J used by itself will be interpreted as 6707J 'N07J p.m.(.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page (!
Z 1umeric days and months are accepted in either one# or two#digit formats. 1ote that numbers cannot be spelled out. Z We can use names of months in full or the standard three# and four#letter abbreviations for months. !or instance" both 6J &ep 9887 and 6J &eptember 9887 will be interpreted correctly. Z
The output of this loop in a browser is as follows 'for the time" date" and time one shown in the first line(0 now0
Wed" 6N $ar 6796 9K07C0C? X7677
today0
Wed" 6N $ar 6796 77077077 X7677
tomorrow0
Thu" 68 $ar 6796 77077077 X7677
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ("
yesterday0
Tue" 6K $ar 6796 77077077 X7677
Thursday0
Thu" 68 $ar 6796 77077077 X7677
this Thursday0
Thu" 68 $ar 6796 77077077 X7677
last Thursday0
Thu" 66 $ar 6796 77077077 X7977
X6 hours0
Wed" 6N $ar 6796 9807C0C? X7677
#9 month0
Tue" 6N !eb 6796 9K07C0C? X7977
X97 minutes0
Wed" 6N $ar 6796 9K09C0C? X7677
@7 seconds0
Wed" 6N $ar 6796 9K07?06? X7677
X6 years #9 month0 !ri" 6N !eb 679J 9K07C0C? X7977 ne+t week0 last month0
$on" 76 Apr 6796 9K07C0C? X7677 Tue" 6N !eb 6796 9K07C0C? X7977
last year0
$on" 6N $ar 6799 9K07C0C? X7677
6 weeks ago0
Wed" 9J $ar 6796 9K07C0C? X7977
!in*in' the .ate #or a Wee;*a$ By combining date'( and strtotime'(" it is possible get the day for any desired weekday in a given month. The following e+ample shows how you can determine the date of the first Tuesday in the month following the current one. The Co*e ^[php _ne+tmonth ] date'EO#E . 'date'EnE( X 9( . E#79E(3 _ne+tmonthGts ] strtotime'_ne+tmonth(3 _firsttueGts ] strtotime'LTuesdayL" _ne+tmonthGts(3 echo EToday is E . date'Ed $ OE( . E.^br 5S\nE3 echo EThe first Tuesday of ne+t month is E . date'Ed $ OE" _firsttueGts( . E.E3 [S :utput0 Today is 6N $ar 6796. The first Tuesday of ne+t month is 7@ Apr 6796. !or all onths2 ^[php echo EToday is E . date'Ed $ OE( . E.E3 for'_i ] 93 _i ^] 963 _iXX( _ne+tmonth ] date'EO#E . 'date'EnE( X _i( . E#79E(3 _ne+tmonthGts ] strtotime'_ne+tmonth(3 _firsttueGts ] strtotime'LTuesdayL" _ne+tmonthGts(3 echo E\n^br 5SThe first Tuesday in E . date'E!E" _firsttueGts( P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page (#
. E is E . date'Ed $ OE" _firsttueGts( . E.E3 [S Gettin' the .a$ an* Wee; o# the ear :btaining the day of the year is fairly simple3 you need use only a lowercase in the first argument to the date'( function. The Co*e ^[php _mydates ] array'E677C#79#79E" E677C#7?#@7E" E677C#96#@9E(3 foreach'_mydates as _mydate( _ts ] strtotime'_mydate(3 echo E
.eterinin' Whether a Given ear Is a Leap ear The date'( function employs another one#letter argument3 it uses 7 to determine if a given year is a le year. When this is used" date'( returns 9 if the year in uestion is a leap year and 7 if it is not. ather than make repeated calls to date'( and strtotime'(" you can wrap this in a simple function that takes the year to be tested as an argument" as shown in the following e+ample. The Co*e ^[php 55 takes a 6# or J#digit year" 55 returns 9 or 7 function isGleapGyear'_year( _ts ] strtotime'L_year#79#79L(3 return date'E/E" _ts(3 55 test the function for a set of 99 consecutive years for'_i ] 67973 _i ^] 67673 _iXX( _output ] L_i is L3 if' isGleapGyear'_i( ( _output .] Lnot L3 _output .] La leap year.^br 5S\nL3 echo _output3 [S O"tp"t2 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ($
6797 is not a leap year. 6799 is not a leap year. 6796 is a leap year. 679@ is not a leap year. 679J is not a leap year. 679C is not a leap year. 679? is a leap year. 679K is not a leap year. 679N is not a leap year. 6798 is not a leap year. 6767 is a leap year.
chech*ate562 *hecks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined S$n2 bool chec;*ate ' int _month" int _day" int _year (
chec;*ate56 e,aple
^[php varGdump'checkdate'96" @9" 6777((3 varGdump'checkdate'6" 68" 6779((3 [S The above e+ample will output0 bool'true( bool'false(
*ateDs"nrise56 2 returns the sunrise time for a given day 'specified as a
ti'esta'p( and location.
mi+ed *ateDs"nrise ' int _timestamp " int _format " float _latitude " float _longitude " float _enith " float _gmtGoffsetDDDDD (
Paraeters timestamp
The timestamp of the day from which the sunrise time is taken. format
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page (%
constant
*escription
e,aple
&-1!-1*&G)TG&TI1;
returns the result as string
9?0J?
&-1!-1*&G)TG<:-B/)
returns the result as float
9?.KN6J@9@6
&-1!-1*&G)TGTI$)&TA$P
returns the result as integer 'timestamp(
978C7@J?7?
latitude
&pecified in hours ^[php 5R calculate the sunrise time for /isbon" Portugal /atitude0 @N.J 1orth /ongitude0 8 West Qenith U] 87 offset0 X9 ;$T R5 echo date'L< $ d OL(. E" sunrise time 0 E .dateGsunrise'time'(" &-1!-1*&G)TG&TI1;" @N.J" #8" 87" 9(3 echo date$% M d (%). , sunset time : .date_sunset$time$), 3=&=>3_@6_364=, + !., -;, ;0, 1)*
[S
The above e+ample will output something similar to0 $on
'et*ate56 2 array 'et*ate ' int _timestampD ( eturns an associative array containing the date information of the ti'esta'p" or the current local time if no ti'esta'p is given. E,aple2
^[php _today ] getdate'(3 printGr'_today(3 [S The above e+ample will output something similar to0 Array P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page (&
' secondsD ]S J7 minutesD ]S CN hoursD ]S 69 mdayD ]S 9K wdayD ]S 6 monD ]S ? yearD ]S 677@ ydayD ]S 9?K weekdayD ]S Tuesday monthD ]S une 7D ]S 97CC879C67 ( Tie562 int tie ' void (
eturns the current time measured in the number of seconds since the -ni+ )poch 'anuary 9 98K7 77077077 ;$T(. E,aple2
^[php _ne+tWeek ] time'( X 'K R 6J R ?7 R ?7(3 55 K days3 6J hours3 ?7 mins3 ?7secs echo E1ow0 E. date'EO#m#dE( .L\nL3 echo E1e+t Week0 E. date'EO#m#dE" _ne+tWeek( .L\nL3 55 or using strtotime'(0 echo E1e+t Week0 E. date'EO#m#dE" strtotime'EX9 weekE(( .L\nL3 [S The above e+ample will output something similar to0 1ow0 6796#7@#@7 1e+t Week0 6796#7J#7? 1e+t Week0 6796#7J#7? .eterinin' the N"ber o# .a$s in the C"rrent Month To determine the number of days in the current month" use the date'( function%s t parameter. *onsider the following code0
printf'LThere are d days in s.L" date'LtL(" date'L!L((3 If this is e+ecuted in April" the following result will be output0 There are @7 days in April
Deter#ining the Nu#ber o+ Days in Any .iven /onth _lastday ] mktime'7" 7" 7" @" 7" 677K(3 printf'LThere are d days in !ebruary 677K.L" date'LtL"_lastday((3 )+ecuting this snippet produces the following output0 P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ('
There are 6N days in !ebruary 677K.. Calc"latin' the .ate ( .a$s #ro the Present .ate It%s often useful to determine the precise date of some specific number of days into the future or past. -sing the strtotime'( function and ;1- date synta+" such reuests are trivial. &uppose you want to know what the date will be JC days into the future" based on today%s date of !ebruary 6C" 677K0
_futuredate ] strtotime'LJC daysL(3 echo date'L! d" OL" _futuredate(3 This returns the following0 April 96" 677K By prepending a negative sign" you can determine the date JC days into the past 'today being !ebruary 6C" 677K(0 _pastdate ] strtotime'L#JC daysL(3 echo date'L! d" OL" _pastdate(3 This returns the following0 anuary 99" 677K
&NIT-%I !ors
Creatin' an* &sin' !ors
When dealing with forms" the most important aspect to remember is that we are limited to a certain variety of fields that can be applied to a form. The fields that have been created are non#negotiable and work in only the way they were created to work. $%&' Form (lemen!s
GET vs= POST
When dealing with forms" we must specify the way that the information entered into the form is transmitted to its destination 'method]LL(. P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page ((
The two ways available to a web developer are ;)T and P:&T.
When sending data using the ;)T method" all fields are appended to the -niform esource /ocator '-/( of the browser and sent along with the address as data.
&ending data using the ;)T method means that fields are generally capped at 9C7 characters" which is certainly not the most effective means of passing information.
It is also not a secure means of passing data" because many people know how to send information to a script using an address bar.
With the P:&T method" values are sent as standard input. &ending data using the P:&T method is uite a bit more secure 'because the method cannot be altered by appending information to the address bar( and can contain as much information as we choose to send.
Therefore" whenever possible" use the P:&T method for sending information and then ad,ust our script to handle it.
PHP C%s current methods for dealing with ;)T and P:&T variables are the _G;)T and _GP:&T superglobals" respectively. By using these two superglobals" we can designate e+actly where the information should be coming from and subseuently handle the data in the way we want.
The 01.%T "ariable The _G;)T variable is an array of variable names and values sent by the HTTP ;)T method. The _G;)T variable is used to collect values from a form with method]LgetL. Information sent from a form with the ;)T method is visible to everyone 'it will be displayed in the browserEs address bar( and it has limits on the amount of information to send 'ma+. 9C7 characters(. E,aple
^form action]Lwelcome.phpL method]LgetLS 1ame0 ^input type]Lte+tL name]LnameL 5S Age0 ^input type]Lte+tL name]LageL 5S ^input type]LsubmitL 5S ^5formS When the user clicks the L&ubmitL button" the -/ sent could look something like this0 http055localhost5te,a5welcome.php[name]ravite,aage]6C The Lwelcome.phpL file can now use the _G;)T variable to catch the form data 'notice that the names of the form fields will automatically be the I< keys in the _G;)T array(0 Welcome ^[php echo _G;)TLnameLD3 [S.^br 5S We are ^[php echo _G;)TLageLD3 [S years old
Note2 When using the _G;)T variabl e all variable names and values are display ed in the -/. &o this method should not be used when sending passwords or other sensitive information However" because the variables are displayed in the -/" it is possible to bookmark the page. This can be useful in some cases. Note2 The HTTP ;)T method is not suitable on large variable values3 the value cannot e+ceed 9C7 characters. P.Ravi Theja,Asst.Professor,GIST,Nellore ))
Email:[email protected]
Page
The 01P2ST "ariable The _GP:&T variable is an array of variable names and values sent by the HTTP P:&T method. The _GP:&T variable is used to collect values from a form with method]LpostL. Information sent from a form with the P:&T method is invisible to others and has no limits on the amount of information to send. E,aple
^form action]Lwelcome.phpL method]LpostLS )nter our name0 ^input type]Lte+tL name]LnameL 5S )nter our age0 ^input type]Lte+tL name]LageL 5S ^input type]LsubmitL 5S ^5formS When the user clicks the L&ubmitL button" the -/ will not contain any form data" and will look something like this0 http055localhost5te,a5welcome.php The Lwelcome.phpL file can now use the _GP:&T variable to catch the form data 'notice that the names of the form fields will automatically be the I< keys in the _GP:&T array(0 Welcome ^[php echo _GP:&TLnameLD3 [S.^br 5S We are ^[php echo _GP:&TLageLD3 [S years old
Why use 01P2ST3 • •
ariables sent with HTTP P:&T are not shown in the -/ ariables have no length limit
However" because the variables are not displayed in the -/" it is not possible to bookmark the page.
The 01$%4U%ST "ariable The PHP _G)F-)&T variable contains the contents of both _G;)T" _GP:&T" and _G*::VI). The PHP _G)F-)&T variable can be used to get the result from form data sent with both the ;)T and P:&T methods. E,aple
Welcome ^[php echo _G)F-)&TLnameLD3 [S.^br 5S We are ^[php echo _G)F-)&TLageLD3 [S years old
S"per'lobals vs=Globals
P.Ravi Theja,Asst.Professor,GIST,Nellore )
Email:[email protected]
Page
submit values using globals or superglobals. 1ote that for this e+ample to work properly" we must temporarily switch our registerGglobals value to on ^html ^titleS&le titleS ^5headS ^bodyS ^div style]Lwidth0 C77p+3 te+t#align0 left3LS ^[php 55Handle the incoming data. 55Here is how we could handle it with registerGglobals turned on. if '_submitted ]] LyesL( if 'trim '_ourname( ] LL( echo L:ur 1ame0 _ourname.L3 else echo LWe must submit a value.L3 [S^br 5S^a href]Lsample.phpLSTry Again^5aS^br 5S^[php 551ow" here is how it &H:-/< be handled with registerGglobals turned off. if '_GP:&TEsubmittedED ]] LyesL( if 'trim '_GP:&TEournameED( ] LL( echo L:ur 1ame0 L . _GP:&TEournameED . L.L3 else echo LWe must submit a value.L3 [S^br 5S^a href]Lsample.phpLSTry Again^5aS^br 5S^[php [S ^[php 55&how the forms only if we donEt already have a submittal. if '_GP:&TEsubmittedED ] LyesL( [S ^form action][email protected] method]LpostLS ^pS)+ample0^5pS ^input type]LhiddenL name]LsubmittedL value]LyesL 5S :ur 1ame0 ^input type]Lte+tL name]LournameL ma+length]L9C7L 5S^br 5S ^input type]LsubmitL value]L&ubmitL style]Lmargin#top0 97p+3L 5S ^5formS ^[php [S ^5divS ^5bodyS ^5htmlS
%ali*atin' !or Inp"t In attacks on websites" one of the biggest issues is attacking forms directly. To ensure a suitable submission of form data" validation is key. We have many ways to validate a form and many form elements to consider. ;enerally" we need to determine what ualities we want a piece of data to adhere to and then ensure that the submitted data comes in the correct form. If the data comes in a format that is not P.Ravi Theja,Asst.Professor,GIST,Nellore )!
Email:[email protected]
Page
to our liking" we must be ready to take care of this. The following e+ample shows a few e+amples of form validation using PHP. The Co*e ^html S ^titleS&le ^5titleS ^5headS ^bodyS ^div style]Lwidth0 C77p+3 te+t#align0 left3LS ^[php 55!unction to determine a valid e#mail address. function validemail'_email( return pregGmatch'L5'a#A#Q7#8D(X'.a#A#Q7#8G#D(R`'a#A#Q7#8G#D( X'.a#A#Q7#8G#DX(Xa#A#Q7#8G#D_5L"_email(3
55Handle the incoming data. if '_GP:&TEsubmittedED ]] LyesL( _goodtogo ] true3 55alidate the name. try if 'trim '_GP:&TEournameED( ]] LL( _goodtogo ] false3 throw new e+ception 'L&orry" we must enter our name.^br 5SL(3 catch 'e+ception _e( echo _e#Sgetmessage'(3 55alidate the select bo+. try if '_GP:&TEmyselectionED ]] LnogoL( _goodtogo ] false3 throw new e+ception 'LPlease make a selection.^br 5SL(3 catch 'e+ception _e( echo _e#Sgetmessage'(3 55And lastly" validate for a proper e#mail addy. try if 'validemail 'trim '_GP:&TEouremailED((( _goodtogo ] false3 throw new e+ception 'LPlease enter a valid email address.^br 5SL(3 catch 'e+ception _e( echo _e#Sgetmessage'(3 551ow" if there were no errors" we can output the results. P.Ravi Theja,Asst.Professor,GIST,Nellore )"
Email:[email protected]
Page
if '_goodtogo( echo L:ur 1ame0 L . _GP:&TEournameED . L^br 5SL3 echo L:ur &election0 L . _GP:&TEmyselectionED . L^br 5SL3 echo L:ur )mail Address0 L . _GP:&TEouremailED . L^br 5SL3 [S^br 5S^a href]Lsample9@[email protected] Again^5aS^br 5S^[php [S ^[php 55&how the forms only if we donEt already have a submittal. if '_GP:&TEsubmittedED ] LyesL( [S ^form action]Lsample.phpL method]LpostLS ^pS)+ample 0^5pS ^input type]LhiddenL name]LsubmittedL value]LyesL 5S :ur 1ame0 ^input type]Lte+tL name]LournameL ma+length]L9C7L 5S^br 5S^br 5S &election0 ^select name]LmyselectionLS ^option value]LnogoLSmake a selection...^5optionS ^option value]L9LS*hoice 9^5optionS ^option value]L6LS*hoice 6^5optionS ^option value]L@LS*hoice @^5optionS ^5selectS^br 5S^br 5S :ur )mail0 ^input type]Lte+tL name]LouremailL ma+length]L9C7L 5S^br 5S ^input type]LsubmitL value]L&ubmitL style]Lmargin#top0 97p+3L 5S ^5formS ^[php [S ^5divS ^5bodyS ^5htmlS
Wor;in' +ith M"ltipa'e !ors &ometimes we will need to collect values from more than one page. We do this by providing forms on more than one page" we can separate blocks of information and thus create an ergonomic e+perience for the user. The problem" therefore" is how to get values from each page onto the ne+t page and finally to the processing script. We can solve this problem and use the hidden input form type. When each page loads" we merely load the values from the previous pages into hidden form elements and submit them. Pa'e<=php ^html S ^titleSpage9^5titleS
^meta http#euiv]L*ontent#TypeL content]Lte+t5html3 charset]iso#NNC8#9L 5S ^5headS ^bodyS ^div style]Lwidth0 C77p+3 te+t#align0 left3LS ^form action]L page6.phpL method]LpostLS ^pSPage 9
Email:[email protected]
Page
:ur 1ame0 ^input type]Lte+tL name]LunameL ma+length]L9C7L 5S^br 5S^br 5S ^input type]LsubmitL value]L&ubmitL style]Lmargin#top0 97p+3L 5S ^5formS ^5divS ^5bodyS ^5htmlS Pa'e>=php ^html S ^titleS Page 6^5titleS ^meta http#euiv]L*ontent#TypeL content]Lte+t5html3 charset]iso#NNC8#9L 5S ^5headS ^bodyS ^div style]Lwidth0 C77p+3 te+t#align0 left3LS ^form action]L [email protected] method]LpostLS ^pSPage 6
Pa'e?=php ^html S ^titleS Page @^5titleS ^5headS ^bodyS ^div style]Lwidth0 C77p+3 te+t#align0 left3LS ^form action]L pageJ.phpL method]LpostLS ^pSPage @ value]L^[php echo GP:&TEourselectionED3 [SL 5S ^input type]LsubmitL value]L&ubmitL style]Lmargin#top0 97p+3L 5S ^5formS ^5divS ^5bodyS ^5htmlS Pa'e1=php ^html S ^titleS Page J^5titleS ^5headS ^bodyS ^div style]Lwidth0 C77p+3 te+t#align0 left3LS ^[php 55
Email:[email protected]
Page
echo L:ur 1ame0 L . _GP:&TEunameED . L^br 5SL3 echo L:ur &election0 L . _GP:&TEphnoED . L^br 5SL3 echo L:ur )mail0 L . _GP:&TEemailED . L^br 5SL3 [S ^a href]L page9.phpLSTry Again^5aS ^5divS ^5bodyS^5htmlS
Preventin' M"ltiple S"bissions o# a !or :ne possible occurrence that happens often is that users become impatient when waiting for our script to do what it is doing" and hence they click the submit button on a form repeatedly. This can wreak havoc on our script because" while the user may not see anything happening" our script is probably going ahead with whatever it has been programmed to do. :f particular danger are credit card number submittals. If a user continually hits the submit button on a credit card submittal form" their card may be charged multiple times if the developer has not taken the time to validate against such an eventuality. Preventin' M"ltiple S"bissions on the Server Si*e
We can deal with multiple submittal validation in two ways. The first occurs on the server. Server si$e refers to a script located on the server that is receiving the data3 %lie(t si$e is more browsers related. Because the server has no actual access to the browser" validating multiple submissions can be a bit trickier. While we can accomplish this goal in a number of ways from a server#side perspective" we prefer to use a session#based method. Basically" once the submit button has been clicked3 the server logs the reuest from the individual user. If the user attempts to resubmit a reuest" the script notes a reuest is already in motion from this user and denies the subseuent reues t. :nce the script has finis hed processing" the session is unset" and we have no more worries M"lti=php ^[php 5RRR begin the session RRR5 sessionGstart'(3
5RRR create the form token RRR5 _formGtoken ] uniid'(3 5RRR add the form token to the session RRR5 _G&)&&I:1EformGtokenED ] _formGtoken3 S
[S ^html ^headS ^titleS$y !orm^5titleS ^5headS ^bodyS ^form action]Lsubmit.phpL method]LpostLS ^dlS ^dtS1ame^5dtS ^ddS ^input type]LhiddenL name]LformGtokenL value]L^[php echo _formGtoken3 [SL 5S ^input type]Lte+tL name]LfirstGnameL 5S P.Ravi Theja,Asst.Professor,GIST,Nellore )%
Email:[email protected]
Page
^5ddS ^5dlS ^pS^input type]LsubmitL value]LAdd 1ameL 5S^5pS ^5formS ^5bodyS ^5htmlS
S"bit=php ^[php 5RRR begin the session RRR5 sessionGstart'(3
5RRR check all e+pected variables are set RRR5 if'isset'_GP:&TEfirstGnameED" _GP:&TEformGtokenED" _G&)&&I:1EformGtokenED(( _message ] EInvalid &ubmissionE3 5RRR check the form tokens match RRR5 elseif'_GP:&TEformGtokenED ] _G&)&&I:1EformGtokenED( _message ] EAccess deniedE3
5RRR check the input name is a string between 9 and C7 characters RRR5 elseif'strlen'trim'_GP:&TEfirstGnameED(( ]] 7 strlen'trim'_GP:&TEfirstGnameED(( S C7( _message ] EInvalid !irst 1ameE3 else 5RRR assign the input RRR5 _message ] EThank you E . _firstGname3 5RRR unset the form token in the session RRR5 unset' _G&)&&I:1EformGtokenED(3 [S ^html S ^headS ^titleS$y !orm^5titleS ^5headS ^bodyS ^h9S&ubmit Page^5h9S ^pS^[php echo _message3 [S^5pS ^5bodyS ^5htmlS P.Ravi Theja,Asst.Professor,GIST,Nellore )&
Email:[email protected]
Page
Preventin' M"ltiple S"bissions on the Client Si*e Handling multiple submittals from a client#side perspective is actually much simpler than doing it on the server side. With well#placed ava&cript" we can ensure that the browser will not let the submittal go through more than once. The problem with this method" of course" is that ava&cript is not always foolproof because of the user%s ability to turn it off. That being said" however" most users will have ava&cript enabled" so this script will likely work for 87 percent of web users. The following e+ample uses ava&cript to cut off multiple submittals from a client#side 'browser( level. ^html S ^titleS&le ^5titleS ^script language]L,avascriptL type]Lte+t5,avascriptLS function checkandsubmit'( 55
reate an Upload-,ile ,or# To allow users to upload files from a form can be very useful. /ook at the following HT$/ form for uploading files0 ^htmlS ^bodyS ^form action]LuploadGfile.phpL method]LpostL enctype]Lmultipart5form#dataLS ^label for]LfileLS!ilename0^5labelS ^input type]LfileL name]LfileL id]LfileL 5S ^br 5S ^input type]LsubmitL name]LsubmitL value]L&ubmitL 5S ^5formS ^5bodyS ^5htmlS 1otice the following about the HT$/ form above0
P.Ravi Theja,Asst.Professor,GIST,Nellore )'
Email:[email protected]
Page
•
•
The enctype attribute of the ^formS tag specifies which content#type to use when submitting the form. Lmultipart5form#dataL is used when a form reuires binary data" like the contents of a file" to be uploaded The type]LfileL attribute of the ^inputS tag specifies that the input should be processed as a file. !or e+ample" when viewed in a browser" there will be a browse#button ne+t to the input field
Note2 Allowing users to upload files is a big security risk. :nly permit trusted users to perform file uploads.
reate The Upload Script The LuploadGfile.phpL file contains the code for uploading a file0 ^[php if '_G!I/)&LfileLDLerrorLD S 7( echo L)rror0 L . _G!I/)&LfileLDLerrorLD . L^br 5SL3 else echo L-pload0 L . _G!I/)&LfileLDLnameLD . L^br 5SL3 echo LType0 L . _G!I/)&LfileLDLtypeLD . L^br 5SL3 echo L&ie0 L . '_G!I/)&LfileLDLsieLD 5 976J( . L Vb^br 5SL3 echo L&tored in0 L . _G!I/)&LfileLDLtmpGnameLD3 [S By using the global PHP _G!I/)& array we can upload files from a client computer to the remote server. The first parameter is the formEs input name and the second inde+ can be either LnameL" LtypeL" LsieL" LtmpGnameL or LerrorL. /ike this0 _G!I/)&LfileLDLnameLD # the name of the uploaded file _G!I/)&LfileLDLtypeLD # the type of the uploaded file _G!I/)&LfileLDLsieLD # the sie in bytes of the uploaded file _G!I/)&LfileLDLtmpGnameLD # the name of the temporary copy of the file stored on the server _G!I/)&LfileLDLerrorLD # the error code resulting from the file upload • • • • •
This is a very simple way of uploading files. !or security reasons" we should add restrictions on what the user is allowed to upload.
$estrictions on Upload In this script we add some restrictions to the file upload. The user may only upload .gif or .,peg files and the file sie must be under 67 kb0 ^[php if '''_G!I/)&LfileLDLtypeLD ]] Limage5gifL( '_G!I/)&LfileLDLtypeLD ]] Limage5,pegL( '_G!I/)&LfileLDLtypeLD ]] Limage5p,pegL(( '_G!I/)&LfileLDLsieLD ^ 67777(( P.Ravi Theja,Asst.Professor,GIST,Nellore )(
Email:[email protected]
Page
if '_G!I/)&LfileLDLerrorLD S 7( echo L)rror0 L . _G!I/)&LfileLDLerrorLD . L^br 5SL3 else echo L-pload0 L . _G!I/)&LfileLDLnameLD . L^br 5SL3 echo LType0 L . _G!I/)&LfileLDLtypeLD . L^br 5SL3 echo L&ie0 L . '_G!I/)&LfileLDLsieLD 5 976J( . L Vb^br 5SL3 echo L&tored in0 L . _G!I/)&LfileLDLtmpGnameLD3 else echo LInvalid fileL3 [S Note2 !or I) to recognie ,pg files the type must be p,peg" for !ire!o+ it must be ,peg.
Saving the Uploaded ,ile The e+amples above create a temporary copy of the uploaded files in the PHP temp folder on the server. The temporary copied files disappear when the script ends. To store the uploaded file we need to copy it to a different location0 ^[php if '''_G!I/)&LfileLDLtypeLD ]] Limage5gifL( '_G!I/)&LfileLDLtypeLD ]] Limage5,pegL( '_G!I/)&LfileLDLtypeLD ]] Limage5p,pegL(( '_G!I/)&LfileLDLsieLD ^ 67777(( if '_G!I/)&LfileLDLerrorLD S 7( echo Leturn *ode0 L . _G!I/)&LfileLDLerrorLD . L^br 5SL3 else echo L-pload0 L . _G!I/)&LfileLDLnameLD . L^br 5SL3 echo LType0 L . _G!I/)&LfileLDLtypeLD . L^br 5SL3 echo L&ie0 L . '_G!I/)&LfileLDLsieLD 5 976J( . L Vb^br 5SL3 echo LTemp file0 L . _G!I/)&LfileLDLtmpGnameLD . L^br 5SL3 if 'fileGe+ists'Lupload5L . _G!I/)&LfileLDLnameLD(( echo _G!I/)&LfileLDLnameLD . L already e+ists. L3 else moveGuploadedGfile'_G!I/)&LfileLDLtmpGnameLD" Lupload5L . _G!I/)&LfileLDLnameLD(3 echo L&tored in0 L . Lupload5L . _G!I/)&LfileLDLnameLD3 P.Ravi Theja,Asst.Professor,GIST,Nellore )
Email:[email protected]
Page
else echo LInvalid fileL3 [S The script above checks if the file already e+ists" if it does not" it copies the file to the specified folder. Note2 This e+ample saves the file to a new folder called LuploadL
&NIT-%II
&sin' M$S8L .atabases /yS4 Database :ne great thing about $y&F/ is that it can be scaled down to support embedded database applications. Perhaps it is because of this reputation that many people believe that $y&F/ can only handle small to medium#sied systems. The truth is that $y&F/ is the de#facto standard database for web sites that support huge volumes of both data and end users 'like !riendster" Oahoo" and ;oogle(.
onnecting to a /yS4 Database Before you can access and work with data in a database" you must create a connection to the database. In PHP" this is done with the myslGconnect '( function. S$nta,
myslGconnect'servername"username"password(3 Paraeter
.escription
server name
:ptional. &pecifies the server to connect to.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected]
Page
username
:ptional. &pecifies the username to log in with.
password
:ptional. &pecifies the password to log in with.
Note2 There are more available parameters" but the ones listed above are the most important. E,aple In the following e+ample we store the connection in a variable '_con( for later use in the script. The LdieL part will be e+ecuted if the connection fails0
^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 [S else echo =unable to connect to the database>3
The myslGconnect'( method and pass it the connection information. This gives you access to any databases that are assigned to the root user. If you were to supply an invalid login set" we would generate an error.
losing a onnection The connection will be closed as soon as the script ends. To close the connection before" use the myslGclose'( function. ^[php _con ] myslGconnect'LlocalhostL"LpeterL"Labc96@L(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 55 some code myslGclose'_con(3 [S
8"er$in' the .atabase &F/ allows you to perform common functionality such as insert" which allows us to enter data into a row3 alter" which allows us to change the format of a table3 select" which allows us to return a row set from a table in the database3 and delete" which allows us to remove a row in the database. We do our &F/ueries in $y&F/ environment. To perform a uery in PHP" you can use the function myslGuery'(. It allows us to perform a myriad of &F/ functions and is uite simple to use. The prototype for myslGuery'( is as follows0 resource $s)lD)"er$ ' string uery " resource linkGidentifierD (
P.Ravi Theja,Asst.Professor,GIST,Nellore !
Email:[email protected]
Page
reate a Database The *)AT)
*)AT)
^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 if 'myslGuery'L*)AT)
reate a Table
The *)AT) TAB/) statement is used to create a database table in $y&F/. S$nta,
*)AT) TAB/) tableGname ' columnGname9 dataGtype" columnGname6 dataGtype" columnGname@ dataGtype" ....... We must add the *)AT) TAB/) statement to the myslGuery'( function to e+ecute the command. E,aple The following e+ample shows how you can create a table named LpersonL" with three columns. The column names will be L!irst1ameL" L/ast1ameL and LAgeL0
The following e+ample shows how you can create a table named LpersonL" with three columns. The column names will be L!irst1ameL" L/ast1ameL and LAgeL0 ^[php _con ] myslGconnect'LlocalhostL"LpeterL"Labc96@L(3 if '_con( P.Ravi Theja,Asst.Professor,GIST,Nellore "
Email:[email protected]
Page
die'E*ould not connect0 E . myslGerror'((3 55 *reate table in T)A database myslGselectGdb'LT)AL" _con(3 _sl ] L*)AT) TAB/) person ' !irst1ame varchar'9C(" /ast1ame varchar'9C(" Age int (L3 myslGuery'_sl"_con(3 [S
myslGclose'_con(3
Iportant2 A database must be selected before a table can be created. The database is selected with the myslGselectGdb'( function. Note2 When you create a database field of type varchar" you must specify the ma+imum length of the field" e.g. varchar'9C(.
/yS4 Data Types Below are the different $y&F/ data types that can be used0 N"eric .ata T$pes
int'sie( smallint'sie( tinyint'sie( mediumint'sie( bigint'sie( decimal'sie"d( double'sie"d( float'sie"d( Te,t"al .ata T$pes
.escription
Hold integers only. The ma+imum number of digits can be specified in the sie parameter
Hold numbers with fractions. The ma+imum number of digits can be specified in the sie parameter. The ma+imum number of digits to the right of the decimal is specified in the d parameter .escription
char'sie(
Holds a fi+ed length string 'can contain letters" numbers" and special characters(. The fi+ed sie is specified in parenthesis
varchar'sie(
Holds a variable length string 'can contain letters" numbers" and special characters(. The ma+imum sie is specified in parenthesis
Tinyte+t
Holds a variable string with a ma+imum length of 6CC characters
te+t blob
Holds a variable string with a ma+imum length of ?CC@C characters
mediumte+t mediumblob
Holds a variable string with a ma+imum length of 9?KKK69C characters
longte+t longblob
Holds a variable string with a ma+imum length of J68J8?K68C characters
.ate.ataT$pes
.escription
P.Ravi Theja,Asst.Professor,GIST,Nellore #
Email:[email protected]
Page
date'yyyy#mm#dd( datetime'yyyy#mm#ddhh0mm0ss( timestamp'yyyymmddhhmmss( time'hh0mm0ss( Misc= .ataT$pes
Holds date and5or time
.escription
enum'value9"value6"ect(
)1-$ is short for )1-$)AT)< list. *an store one of up to ?CC@C values listed within the ' ( brackets. If a value is inserted that is not in the list" a blank value will be inserted
&et
&)Tissimilarto)1-$.However"&)Tcanhaveupto?Jlist items and can store more than one choice
Pri#ary 5eys and Auto Incre#ent ,ields )ach table should have a primary key field.A primary key is used to uniuely identify the rows in a table. )ach primary key value must be uniue within the table. !urthermore" the primary key field cannot be null because the database engine reuires a value to locate the record. The primary key field is always inde+ed. There is no e+ception to this rule Oou must inde+ the primary key field so the database engine can uickly locate rows based on the keyEs value. The following e+ample sets the personI< field as the primary key field. The primary key field is often an I< number" and is often used with the A-T:GI1*)$)1T setting. A-T:GI1*)$)1T automatically increases the value of the field by 9 each time a new record is added. To ensure that the primary key field cannot be null" we must add the 1:T 1-// setting to the field. E,aple
_sl ] L*)AT) TAB/) person ' personI< int 1:T 1-// A-T:GI1*)$)1T" PI$AO V)O'personI<(" !irst1ame varchar'9C(" /ast1ame varchar'9C(" Age int (L3 myslGuery'_sl"_con(3
Insert Data into a Database Table The I1&)T I1T: statement is used to add new records to a database table. S$nta,
I1&)T I1T: tableGname A/-)& 'value9" value6"....( Oou can also specify the columns where you want to insert the data0 I1&)T I1T: tableGname 'column9" column6"...( P.Ravi Theja,Asst.Professor,GIST,Nellore $
Email:[email protected]
Page
A/-)& 'value9"value6"....( Note2 &F/ statements are not case sensitive. I1&)T I1T: is the same as insert into. To get PHP to e+ecute the statements above we must use the myslGuery'( function. This function is used to send a uery or command to a $y&F/ connection. E,aple In the previous chapter we created a table named LPersonL" with three columns3 L!irstnameL" L/astnameL and LAgeL. We will use the same table in this e+ample. The following e+ample adds two new records to the LPersonL table0
^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 myslGselectGdb'LT)AL" _con(3 myslGuery'LI1&)T I1T: person '!irst1ame" /ast1ame" Age( A/-)& 'EPeterE" E;riffinE" E@CE(L(3 myslGuery'LI1&)T I1T: person A/-)& 'E;lennE" EFuagmireE" E@@E(L(3 myslGclose'_con(3 [S
Insert Data +ro# a ,or# into a Database 1ow we will create an HT$/ form that can be used to add new records to the LPersonL table. Here is the HT$/ form0 ^htmlS ^bodyS ^form action]Linsert.phpL method]LpostLS !irstname0 ^input type]Lte+tL name]LfirstnameL 5S /astname0 ^input type]Lte+tL name]LlastnameL 5S Age0 ^input type]Lte+tL name]LageL 5S ^input type]LsubmitL 5S ^5formS ^5bodyS ^5htmlS When a user clicks the submit button in the HT$/ form in the e+ample above" the form data is sent to Linsert.phpL. The Linsert.phpL file connects to a database" and retrieves the values from the form with the PHP _GP:&T variables. Then" the myslGuery'( function e+ecutes the I1&)T I1T: statement" and a new record will be added to the database table. Below is the code in the Linsert.phpL page0 ^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 P.Ravi Theja,Asst.Professor,GIST,Nellore %
Email:[email protected]
Page
myslGselectGdb'LT)AL" _con(3 _sl]LI1&)T I1T: person '!irst1ame" /ast1ame" Age( A/-)& 'E_GP:&TfirstnameDE"E_GP:&TlastnameDE"E_GP:&TageDE(L3 if 'myslGuery'_sl"_con(( die'E)rror0 E . myslGerror'((3 echo L9 record addedL3 myslGclose'_con( [S
Select Data +ro# a Database Table The &)/)*T statement is used to select data from a database. S$nta,
&)/)*T columnGname's( !:$ tableGname Note2 &F/ statements are not case sensitive. &)/)*T is the same as select. To get PHP to e+ecute the statement above we must use the myslGuery'( function. This function is used to send a uery or command to a $y&F/ connection. E,aple The following e+ample selects all the data stored in the LPersonL table 'The R character selects all of the data in the table(0
^[php _con ] myslGconnect'LlocalhostL"LpeterL"Labc96@L(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 myslGselectGdb'LT)AL" _con(3 _result ] myslGuery'L&)/)*T R !:$ personL(3 while'_row ] myslGfetchGarray'_result(( echo _rowE!irst1ameED . L L . _rowE/ast1ameED3 echo L^br 5SL3 myslGclose'_con(3 [S The e+ample above stores the data returned by the myslGuery'( function in the _result variable. 1e+t" we use the myslGfetchGarray'( function to return the first row from the recordset as an array. )ach subseuent call to myslGfetchGarray'( returns the ne+t row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row" we use the PHP _row variable '_rowE!irst1ameED and _rowE/ast1ameED(. The output of the code above will be0 P.Ravi Theja,Asst.Professor,GIST,Nellore &
Email:[email protected]
Page
avi Te,a ;lenn Hams
Display the $esult in an HT/ Table The following e+ample selects the same data as the e+ample above" but will display the data in an HT$/ table0 ^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 myslGselectGdb'LT)AL" _con(3 _result ] myslGuery'L&)/)*T R !:$ personL(3 echo ^table border]E9ES trS ^thS!irstname^5thS ^thS/astname^5thS ^5trSL3 while'_row ] myslGfetchGarray'_result(( echo L^trSL3 echo L^tdSL . _rowE!irst1ameED . L^5tdSL3 echo L^tdSL . _rowE/ast1ameED . L^5tdSL3 echo L^5trSL3 echo L^5tableSL3 myslGclose'_con(3 [S The output of the code above will be0 !irstnae
Lastnae
avi
Te,a
;lenn
Hams
The WH%$% clause To select only data that matches a specific criteria" add a WH)) clause to the &)/)*T statement. S$nta,
&)/)*T column !:$ table WH)) column operator value The following operators can be used with the WH)) clause0 Operator P.Ravi Theja,Asst.Professor,GIST,Nellore '
.escription Email:[email protected]
Page
]
)ual
]
eual 1ot
S
;reater than
^
than /ess
S]
;reater than or eual
^] B)TW))1
/ess than or eual Betweenaninclusiverange
/IV)
&earch for pattern a
Note2 &F/ statements are not case sensitive. WH)) is the same as where. To get PHP to e+ecute the statement above we must use the myslGuery'( function. This function is used to send a uery or command to a $y&F/ connection. E,aple The following e+ample will select all rows from the LPersonL table" where !irst1ame]EaviE0
^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 myslGselectGdb'LT)AL" _con(3 _result ] myslGuery'L&)/)*T R !:$ person WH)) !irst1ame]EPeterEL(3 while'_row ] myslGfetchGarray'_result(( echo _rowE!irst1ameED . L L . _rowE/ast1ameED3 echo L^br 5SL3 [S The output of the code above will be0 avi Te,a
The 2$D%$ 67 5eyword The :<) BO keyword is used to sort the data in a record set. S$nta, &)/)*T columnGname's( !:$ tableGname :<) BO columnGname Note2 &F/ statements are not case sensitive. :<) BO is the same as order by. P.Ravi Theja,Asst.Professor,GIST,Nellore (
Email:[email protected]
Page
E,aple The following e+ample selects all the data stored in the LPersonL table" and sorts the result by the LAgeL column0
^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 myslGselectGdb'LT)AL" _con(3 _result ] myslGuery'L&)/)*T R !:$ person :<) BO ageL(3 while'_row ] myslGfetchGarray'_result(( echo _rowE!irst1ameED3 echo L L . _rowE/ast1ameED3 echo L L . _rowEAgeED3 echo L^br 5SL3 myslGclose'_con(3 [S The output of the code above will be0 avi Te,a 6C ;lenn Hams 66
Sort Ascending If you use the :<)or BODescending keyword" the sort#order of the recordset is ascending by default '9 before 8 and LaL before LpL(. -se the <)&* keyword to specify a descending sort#order '8 before 9 and LpL before LaL(0 &)/)*T columnGname's( !:$ tableGname :<) BO columnGname <)&*
2rder by Two olu#ns It is possible to order by more than one column. When ordering by more than one column" the second column is only used if the values in the first column are identical0 &)/)*T columnGname's( !:$ tableGname :<) BO columnGname9" columnGname6
Update Data In a is Database The -P
-P
Email:[email protected]
Page
WH)) columnGname ] someGvalue Note2 &F/ statements are not case sensitive. -P
LastNae
A'e
avi
Te,a
6C
;lenn
Hams
66
!irstNae
LastNae
A'e
avi
Te,a
6?
;lenn
Hams
66
The following e+ample updates some data in the LPersonL table0 ^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 myslGselectGdb'LT)AL" _con(3 myslGuery'L-P
Delete Data in a Database The <)/)T) !:$ statement is used to delete records from a database table. S$nta,
<)/)T) !:$ tableGname WH)) columnGname ] someGvalue Note2 &F/ statements are not case sensitive. <)/)T) !:$ is the same as delete from. To get PHP to e+ecute the statement above we must use the myslGuery'( function. This function is used to send a uery or command to a $y&F/ connection. E,aple
)arlier in the tutorial we created a table named LPersonL. Here is how it looks0 !irstNae
LastNae
A'e
avi
Te,a
6?
;lenn
Hams
66
P.Ravi Theja,Asst.Professor,GIST,Nellore !
Email:[email protected]
Page
The following e+ample deletes all the records in the LPersonL table where /ast1ame]Te,aE0 ^[php _con ] myslGconnect'LlocalhostL"LrootL"LL(3 if '_con( die'E*ould not connect0 E . myslGerror'((3 myslGselectGdb'LT)AL" _con(3 myslGuery'L<)/)T) !:$ Person WH)) /ast1ame]ETe,aEL(3 myslGclose'_con(3 [S After the deletion" the table will look like this0 !irstNae LastNae ;lenn
Hams
P.Ravi Theja,Asst.Professor,GIST,Nellore !!
A'e
66
Email:[email protected]
Page