<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Firstbloodpart3's Weblog</title>
	<atom:link href="http://firstbloodpart3.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://firstbloodpart3.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Wed, 18 Jun 2008 16:45:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='firstbloodpart3.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Firstbloodpart3's Weblog</title>
		<link>http://firstbloodpart3.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://firstbloodpart3.wordpress.com/osd.xml" title="Firstbloodpart3&#039;s Weblog" />
	<atom:link rel='hub' href='http://firstbloodpart3.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Motor Bakar 4 Langkah</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/motor-bakar-4-langkah/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/motor-bakar-4-langkah/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 16:45:36 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/?p=11</guid>
		<description><![CDATA[Pada motor bakar 4 langkah, setiap satu siklus kerja memerlukan 4 kali langkah torak atau dua kali putaran poros engkol, yaitu : a. Langkah Isap (suction stroke) Torak bergerak dari posisi TMA (Titik Mati Atas) ke TMB (Titik Mati Bawah), dengan katup KI (katup isap) terbuka dan KB (katup buang) tertutup. Karena gerakan torak tersebut [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=11&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal" style="text-align:justify;text-indent:0.5in;line-height:150%;"><span lang="IN">Pada motor bakar 4 langkah, setiap satu siklus kerja memerlukan 4 kali langkah torak atau dua kali putaran poros engkol, yaitu :</span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;text-indent:-0.25in;line-height:150%;"><!--[if !supportLists]--><span lang="IN"><span>a.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span lang="IN">Langkah Isap (suction stroke)</span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;line-height:150%;"><span lang="IN">Torak bergerak dari posisi TMA (Titik Mati Atas) ke TMB (Titik Mati Bawah), dengan katup KI (katup isap) terbuka dan KB (katup buang) tertutup. Karena gerakan torak tersebut maka campuran udara dengan bahan bakar atau udara saja pada motor diesel akan terisap ke dalam ruang bakar. </span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;text-indent:-0.25in;line-height:150%;"><!--[if !supportLists]--><span lang="IN"><span>b.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span lang="IN">Langkah Kompresi (compression stroke)</span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;line-height:150%;"><span lang="IN">Torak bergerak dari posisi TMB ke TMA, dengan KI dan KB tertutup, sehingga terjadi proses kompresi yang mengakibatkan tekanan dan temperatur di dalam silinder naik.</span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;text-indent:-0.25in;line-height:150%;"><!--[if !supportLists]--><span lang="IN"><span>c.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span lang="IN">Langkah ekspansi (Expansion stroke)</span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;line-height:150%;"><span lang="IN">Sebelum torak mencapai TMA pada langkah kompresi, pada motor bensin busi dinyalakan, atau pada motor diesel bahan bakar disemprotkan ke dalam ruang bakar sehingga terjadi proses pembakaran. Akibatnya tekanan dan temperatur di ruang bakar naik lebih tinggi, sehinga torak mampu melakukan langkah kerja</span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;text-indent:-0.25in;line-height:150%;"><!--[if !supportLists]--><span lang="IN"><span>d.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span lang="IN">Langkah Buang<span> </span></span></p>
<p class="MsoNormal" style="margin-left:45pt;text-align:justify;line-height:150%;"><span lang="IN">Torak bergerak dari TMB ke TMA, KI tertutup dan KB terbuka, sehingga gas hasil pembakaran terbuang ke atmosfer.</span></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=11&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/motor-bakar-4-langkah/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>Introduction Wi-Fi—wireless networking</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/introduction-wi-fi%e2%80%94wireless-networking/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/introduction-wi-fi%e2%80%94wireless-networking/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 16:43:38 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/?p=10</guid>
		<description><![CDATA[If you are new to Wi-Fi—wireless networking—I&#8217;d like to be your guide to this wonderful technology. I am no industry flak or starry-eyed gadget freak (although I do appreciate technology that makes life easier for people, like Wi-Fi). I want to be your guide to Wi-Fi, so it is fair for you to ask (and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=10&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="docText">If you are new to Wi-Fi—wireless networking—I&#8217;d like to be your  guide to this wonderful technology. I am no industry flak or starry-eyed gadget  freak (although I do appreciate technology that makes life easier for people,  like Wi-Fi).</p>
<p class="docText">I want to be your guide to Wi-Fi, so it is fair for you to ask  (and me to answer) some questions:</p>
<ul>
<li>
<p class="docList">What are my qualifications?</p>
</li>
<li>
<p class="docList">What is my approach?</p>
</li>
<li>
<p class="docList">Who is this book for, and why an &#8220;Absolute Beginner&#8217;s  Guide?&#8221;</p>
</li>
</ul>
<p class="docText">I&#8217;d like to start with my qualifications. I take qualifications  in this context to be a pretty broad issue, meaning (in part) who am I?</p>
<p class="docText">I am a normal human being, whatever that means, who is  interested in technology (among other things). I have a wife, two kids, another  one on the way, and a house with a mortgage. Besides my interest in technology,  I like to read, write, garden, take photographs, and hike.</p>
<p class="docText">I&#8217;ve been involved in technology as a professional for more  than 20 years. (Because technology years actually compare with dog years, that  probably is the equivalent of hundreds of experiential years!) I&#8217;ve seen  technologies come on strong, grow up, mature, and burst like a star that has  gone nova too soon. I like to think I know what is important, and what is not,  and what technologies matter.</p>
<p class="docText">I&#8217;ve been involved with Wi-Fi since its infancy, and have  lectured about Wi-Fi and taught people how to construct Wi-Fi networks. I  maintain a Wi-Fi network in my home for the convenience of myself and my family.  I&#8217;ve been a road warrior and a stay-at-home. I enjoy sharing my knowledge with  people and helping them get up to speed as quickly as possible.</p>
<p class="docText">Well, enough about me! Perhaps you are completely new to Wi-Fi  and want to quickly get up to speed so you can surf at local hotspots, or while  you&#8217;re on the road. This book will give you the practical information you need  to buy the right equipment, get your equipment working perfectly, find Wi-Fi  hotspots, and get the best deal with Wi-Fi providers.</p>
<p class="docText">Perhaps you already use Wi-Fi in your local coffee shop, at the  airport, or in hotel lobbies, and you want to set up a small office or home  network. You already know how great Wi-Fi is, so you want to enjoy the benefits  where you live and work. It is truly transformational to one&#8217;s lifestyle to  decouple computing from the wires!</p>
<p class="docText">If you are looking to set up a Wi-Fi network, you&#8217;ve come to  the right place. I&#8217;ll show you the best way to buy the equipment you need at the  best prices, and how to set it up easily. I won&#8217;t gloss over potential pitfalls,  and I will save you time and money. I&#8217;ll also show you some of the  considerations you might want to think about if you are building a more complex  network involving Wi-Fi.</p>
<p class="docText">Many people are looking to find out how to use Wi-Fi on the  road, or in networks at home. An <span class="docEmphasis">Absolute Beginner&#8217;s  Guide</span> provides the perfect format for easily learning what you need to  know to get up to speed with Wi-Fi, without wasting a lot of time. The  organization of the book, and the special elements that I&#8217;ve described in the  section &#8220;<a class="docLink" href="fm01lev1sec2.html#fm01lev1sec2">Conventions Used  in This Book</a>,&#8221; will help you get the information you need quickly,  accurately, and with clarity.</p>
<p class="docText">In this book you&#8217;ll find inspiration as well as practical  information. I believe that Wi-Fi is a modest technology that has the power to  have a huge and positive impact. Some of the items I&#8217;ve included in this book  speak to that transformational power. For example, you&#8217;ll learn how villages in  southeast Asia use Wi-Fi on the fly to connect to the world, and how Wi-Fi was  used to bring wireless networking to Pitcairn Island, a romantic flyspeck in the  South Pacific Ocean (remember <span class="docEmphasis">Mutiny on the  Bounty?</span>). You&#8217;ll also learn about war chalking, and find out how to  locate free Wi-Fi hotspots.</p>
<p class="docText">This is wonderful material, and it&#8217;s lots of fun! So what are  you waiting for? It&#8217;s time to Wi-Fi!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=10&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/introduction-wi-fi%e2%80%94wireless-networking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>For Dummies For Dummies</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/for-dummies-for-dummies/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/for-dummies-for-dummies/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 16:42:14 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/2008/06/18/for-dummies-for-dummies/</guid>
		<description><![CDATA[Foolish AssumptionsFirst, I assume that you know enough about computers to understand termslike files, directories, path names, and other basic operating system concepts.I assume that when I tell you to put a file in a specific directory, you know howto do that.Next, I assume that you know how to create files. You need to know [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=9&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Foolish Assumptions<br />First, I assume that you know enough about computers to understand terms<br />like files, directories, path names, and other basic operating system concepts.<br />I assume that when I tell you to put a file in a specific directory, you know how<br />to do that.<br />Next, I assume that you know how to create files. You need to know how to<br />create a file and edit it by using a basic editor, such as Notepad in Windows.<br />You need to know how to save the file, copy it, and move it around.<br />I assume that you are using an operating system that PHP runs on, which<br />included almost every operating system. Your operating system needs to be<br />reasonably current. For example, Windows 95 is too old, as is Mac OS 9. Even<br />Windows 98 is a little old, although some people do run PHP on it.<br />If you’re using PHP for the Web, you need to use HTML (HyperText Markup<br />Language) statements. I assume that you know HTML. Consequently, although<br />I use HTML in many examples, I do not explain the HTML. If you need to use<br />PHP for a Web site and you do not have an HTML background, I suggest that<br />you first read a book on HTML — such as HTML 4 For Dummies, 4th Edition,<br />by Ed Tittel and Natanya Pitts, or HTML 4 For Dummies, Quick Reference, 2nd<br />Edition, by Deborah S. Ray and Eric J. Ray (both by Wiley Publishing, Inc.)<br />Then build some practice Web pages before you start this book. However, if<br />you’re the impatient type, I won’t tell you that it’s impossible to proceed without<br />knowing HTML. You may be able to glean enough HTML from this book<br />to build your particular Web site. If you choose to proceed without knowing<br />HTML, I would suggest that you have an HTML book by your side to assist<br />you when you need to figure out some HTML that isn’t explained in this book.<br />Also for PHP for the Web users, I assume that you have created at least a static<br />Web page, probably one or more static Web sites. I assume that you know<br />where you need to put files so that your Web pages are available to your Web<br />site users and that you know how to put the files in the appropriate place by<br />using copy, ftp, and so on.<br />I do not assume that you know anything at all about writing computer programs<br />in any language. This introductory book provides the needed instructions<br />for anyone to write PHP scripts. So, if this is your first programming<br />language, you should be fine. If you have a background in another programming<br />language, particularly C, you may find this book to be a quick reference<br />to learning how to do things in PHP. However, those who have no background<br />in programming will find all the information that they need.<br />3 Introduction<br />How This Book Is Organized<br />This book is divided into six parts. The content ranges from an introduction<br />to PHP basics to common applications for PHP.<br />Part I: Say Hello to the PHP<br />Scripting Language<br />This part provides an overview of PHP, including how it works and its many<br />uses. You discover how to set up your environment for using PHP. Finally, this<br />part shows you how to create your first PHP program.<br />Part II: Variables and Data<br />Variables are the fundamental feature of PHP. This section shows you how to<br />create variables and use them. It also describes the kind of data that you can<br />store in a variable as well as how to handle the various types of data. Then,<br />you find out how to create and use complex variables called arrays.<br />Part III: Basic PHP Programming<br />This part shows you how to program PHP scripts. You find out about the basic<br />features of PHP and the details of how to use them to create your scripts. This<br />part also introduces you to object-oriented programming.<br />Part IV: Common PHP Applications<br />Part IV provides the techniques needed to write scripts for the most common<br />PHP applications. You find out how to write scripts for use in your Web site,<br />such as how to display HTML forms and how to process information that users<br />type into forms. You find out how to use PHP to interact with databases. Using<br />PHP to perform system tasks, such as writing files on your hard disk and executing<br />operating system commands, is also described.<br />4 PHP 5 For Dummies<br />Part V: The Part of Tens<br />This part provides some useful lists of things to do and not do when writing<br />PHP scripts, as well as a listing of PHP resources.<br />Part VI: Appendixes<br />This part provides detailed instructions for installing PHP for those who need<br />to install it themselves. Appendix B is a list of functions available in PHP,<br />intended to be a useful reference while you write your scripts.<br />Icons Used in This Book<br />Icons are provided to help you identify information in this book. The following<br />icons point out types of information for your notice.<br />Tips provide extra information for a specific purpose. Tips can save you time<br />and effort, so they’re worth checking out.<br />This icon is a Post-It note of sorts, highlighting information that’s worth committing<br />to memory.<br />You should always read and pay attention to warnings. Warnings emphasize<br />actions that you must take or must avoid to prevent dire consequences.<br />This icon flags information and techniques that are more technical than other<br />sections of the book. The information here can be interesting and helpful, but<br />you don’t need to understand it to use the information in the book.<br />5 Introduction<br />6 PHP 5 For Dummies<br />Part I<br />Say Hello to the<br />PHP Scripting<br />Language<br />In this part . . .<br />Iprovide an overview of PHP. I describe PHP, how it<br />works, and what it is useful for. After describing your<br />tools, I show you how to set up your working environment.<br />I also present options for accessing PHP and point<br />out what to look for in each environment.<br />After describing the tools and options for the development<br />environment, I provide an overview of the development<br />process. I show you how to write your first script<br />and discuss a few simple output statements.<br />Chapter 1<br />Getting to Know PHP<br />In This Chapter<br /> Taking a look at PHP<br /> Understanding how PHP works<br /> Understanding PHP as open source software<br />So, you want to get to know PHP. Perhaps this is your first adventure in<br />programming, and you chose PHP because your techie friend told you<br />it’s easy to understand. Well, your friend is right. PHP is one of the easiest<br />programming languages to understand. The developers of PHP strive constantly<br />to keep it easy to use.<br />Perhaps you already know how to program in another language. You’ve<br />decided to study PHP because it’s the best language for your new Web application<br />project. It’s a good decision because PHP is well suited for writing<br />dynamic Web applications. PHP is easy to get started with, but it also has<br />many advanced features for seasoned programmers. If you know C, you<br />have a great head start because PHP syntax is similar to C syntax.<br />In this chapter, I discuss what PHP is, what it can do, and how it does it.<br />Getting Familiar with PHP<br />PHP is a widely used open source, general-purpose scripting language. It was<br />originally designed for use in Web site development. In fact, PHP started life<br />as Personal Home Page tools, developed by Rasmus Lerdorf to assist users<br />with Web page tasks. PHP proved so useful and popular, it rapidly grew to<br />become the full-featured language that it is today, acquiring the name PHP<br />Hypertext Preprocessor along the way to represent its expanded abilities —<br />processing Web pages before they’re displayed.<br />The popularity of PHP continues to grow rapidly because of its many<br />advantages:<br /> It’s fast: On Web sites, because it is embedded in HTML code, the time to<br />process and load a Web page is short.<br /> It’s free: PHP is proof that free lunches do exist and that you can get<br />more than you paid for.<br /> It’s easy to use: The syntax is simple and easy to understand and use,<br />even for non-programmers. For use in Web sites, PHP code is designed<br />to be included easily in an HTML file.<br /> It’s versatile: PHP runs on a wide variety of operating systems —<br />Windows, Linux, Mac OS, and most varieties of Unix.<br /> Technical support is widely available: You can join one of several<br />e-mail discussion lists offered on the PHP Web site (www.php.net),<br />which cover topics such as general PHP, PHP on Windows, or databases<br />and PHP. In addition, a Web interface to the discussion lists is available<br />at news.php.net, where you can browse or search the messages.<br /> It’s secure: As long as your scripts are designed correctly, the user does<br />not see the PHP code.<br /> It’s customizable: The open source license allows programmers to<br />modify the PHP software, adding or modifying features as needed to fit<br />their own environments. PHP provides significant control over the environment,<br />reducing chances of failure.<br />Considering the Various Uses for PHP<br />PHP is a general-purpose language that can be used to write general-purpose<br />scripts. Scripts are computer files containing instructions in the PHP language<br />that tell the computer to do things, such as display Hello on the screen or<br />store some specified data in a database. Most scripts contain a series of<br />instructions that can accomplish tasks from designing Web pages to navigating<br />your file system. Because PHP began life on the Web, it has many features<br />that are particularly well suited for use in scripts that create dynamic Web<br />pages. Currently, you find PHP most often hard at work in Web pages, but its<br />use for other purposes is growing.<br />PHP is very popular for Web sites. According to the PHP Web site (www.php.<br />net/usage.php), over 11 million domains are using PHP. Yahoo!, which is<br />probably the world’s most visited site, recently decided to change from its<br />own proprietary language to PHP.<br />10 Part I: Say Hello to the PHP Scripting Language<br />Using PHP for Web applications<br />In the beginning, Web pages were static — they just presented documents.<br />Users went to Web sites to read information. Documents were linked together<br />so that users could easily find the information they sought, but the Web pages<br />didn’t change. Every user who arrived at a Web page saw the same thing.<br />Soon Web page developers wanted to do more. They wanted to interact with<br />visitors, collect information from users, and provide Web pages that were<br />customized for individuals. Several languages have developed that can be<br />used to make Web sites dynamic. PHP is one of the most successful of these<br />languages, evolving quickly to become more and more useful and rapidly<br />growing in popularity.<br />PHP is a server-side scripting language, which means that the scripts are executed<br />on the server (the computer where the Web site is located). This is different<br />than JavaScript, another popular language for dynamic Web sites. JavaScript<br />is executed by the browser, on the user’s computer. Thus, JavaScript is a clientside<br />language. Web servers and the interaction between servers and clients are<br />discussed in the section “PHP for the Web,” later in this chapter.<br />Because PHP scripts execute on the server, PHP can dynamically create the<br />HTML code that generates the Web page, which allows individual users to<br />see customized Web pages. Web page visitors see the output from scripts,<br />but not the scripts themselves.<br />PHP has many features designed specifically for use in Web sites, including<br />the following:<br /> Interact with HTML forms: PHP can display an HTML form and process<br />the information that the user types in.<br /> Communicate with databases: PHP can interact with databases to store<br />information from the user or retrieve information that is displayed to<br />the user.<br /> Generate secure Web pages: PHP allows the developer to create secure<br />Web pages that require users to enter a valid username and password<br />before seeing the Web page content.<br />PHP features make these and many other Web page tasks easy.<br />PHP is only server-side, meaning it can’t interact directly with the user’s computer.<br />That means PHP can’t initiate actions based on the status of the user’s<br />computer, such as mouse actions or screen size. Therefore, PHP alone can’t<br />produce some popular effects, such as navigation menus that drop down or<br />change color. On the other hand, JavaScript, a client-side scripting language,<br />11 Chapter 1: Getting to Know PHP<br />can’t access the server, limiting its possibilities. For example, you can’t use<br />JavaScript to store data on the server or retrieve data from the server. But<br />wait! You don’t have to choose. You can use JavaScript and PHP together to<br />produce Web pages that neither can produce alone. See Chapter 11 for details<br />on using JavaScript and PHP together.<br />Using PHP for database applications<br />PHP is particularly strong in its ability to interact with databases. PHP supports<br />pretty much every database you’ve ever heard of and some you haven’t.<br />PHP handles connecting to the database and communicating with it, so you<br />don’t need to know the technical details for connecting to a database or for<br />exchanging messages with it. You tell PHP the name of the database and<br />where it is, and PHP handles the details. It connects to the database, passes<br />your instructions to the database, and returns the database response to you.<br />Major databases currently supported by PHP include the following:<br /> dBASE<br /> Informix<br /> Ingres<br /> Microsoft SQL Server<br /> mSQL<br /> MySQL<br /> Oracle<br /> PostgreSQL<br /> Sybase<br />PHP supports other databases as well, such as filePro, FrontBase, and<br />InterBase. In addition, PHP supports ODBC (Open Database Connectivity),<br />a standard that allows you to communicate with even more databases, such<br />as Access and IBM DB2.<br />PHP works well for a database-driven Web site. PHP scripts in the Web site<br />can store data in and retrieve data from any supported database. PHP also<br />can interact with supported databases outside a Web environment. Database<br />use is one of PHP’s best features.<br />12 Part I: Say Hello to the PHP Scripting Language<br />Using PHP with your file system<br />PHP can interact with your file system — the directories and files that are on<br />your local hard disk or on other computers accessible over a network. PHP can<br />write into a file on your file system, creating the file if it doesn’t exist, and can<br />read the contents from files. It can also create directories, copy files, rename<br />files, delete files, change file attributes, and perform many other file system<br />tasks. PHP allows you to perform almost any task related to your file system.<br />Many Web sites need to interact directly with the file system. For example,<br />a Web application may save information temporarily in a file rather than in a<br />database, or may need to read information from a file.<br />System administrative and maintenance scripts frequently need to interact<br />with the file system. For example, you may want to use a PHP script to back<br />up files, to clean out directories, or to process text files by reformatting their<br />contents. PHP can perform these tasks quite well.<br />Using PHP for system commands<br />PHP can interact with your operating system to perform any task the operating<br />system can perform. You can execute an operating system command and<br />receive the output. For example, you can execute a dir or ls command (to<br />list the files in your directory) from PHP and receive the list of filenames that<br />the dir/ls command produces.<br />The ability to execute system commands is often useful for system administrative<br />and maintenance tasks. For example, you may want to clean up a<br />directory by deleting files with a particular extension. You can use a system<br />command to get a list of files in a directory and then identify and delete the<br />files with the unwanted extension.<br />The ability to execute system commands includes the ability to run any other<br />program on the system. Thus, you can run programs in other languages from<br />PHP and make use of the output. Aren’t you relieved that you don’t have to<br />rewrite all those programs you’re using now? You can run Perl, C, shell scripts,<br />or any other language programs from PHP. New PHP programs can add functionality<br />to your system tools, without requiring you to spend time rewriting<br />existing tools.<br />13 Chapter 1: Getting to Know PHP<br />Understanding How PHP Works<br />PHP is a high-level language, which means that it’s human-friendly, similar to<br />English. Because your computer doesn’t understand English, you use PHP<br />to communicate, and the PHP interpreter converts the language in your PHP<br />script to language the computer can understand. The computer then follows<br />your instructions, passed to it by the interpreter.<br />The PHP interpreter comes in two flavors, one for use with Web sites and one<br />that you run from the command line, independent of the Web. You can install<br />either or both.<br />PHP as a general-purpose language<br />When you use PHP as a general-purpose scripting language, you install PHP<br />CLI, the version of PHP developed for this purpose. You access the PHP interpreter<br />from the command line to run your PHP script. The process is similar<br />to other languages, such as Perl or C. For the lowdown on running scripts<br />using PHP CLI, check out Chapter 3.<br />14 Part I: Say Hello to the PHP Scripting Language<br />How the World Wide Web works<br />It’s helpful to understand a little about how the<br />World Wide Web (WWW) works. The Web is a<br />network of computers that offer Web pages.<br />Millions of Web sites are on the Web. To enable<br />Web surfers to find the Web sites they want to<br />visit, each Web page has an address, called a<br />URL. This includes the Web site’s domain name<br />and the filename, such as www.mycompany.<br />com/welcome.html. When Web surfers want<br />to visit a Web page, they type the URL into their<br />Web browsers. The following process is set in<br />motion:<br />1. The Web browser sends a message out<br />onto the Web, requesting the Web page.<br />2. The message is sent to the computer at the<br />address specified in the URL.<br />3. The Web server software on the addressed<br />computer receives the message.<br />4. The Web server searches for the requested<br />HTML file.<br />5. The Web server finds the requested file and<br />sends the file to the Web browser that<br />requested it. (If it can’t find the file, it sends<br />a message to the browser saying that it<br />couldn’t find the file.)<br />6. The Web browser displays the Web page<br />based on the HTML code it received.<br />PHP for the Web<br />When used on your Web site, PHP works in partnership with your Web server.<br />Every Web site requires a Web server. The Web sever is the software that delivers<br />your Web pages to the world. The PHP software works in conjunction with<br />the Web server.<br />When used on the Web, PHP is an embedded scripting language. This means<br />that PHP code is embedded in HTML code. You use HTML tags to enclose the<br />PHP language that you embed in your HTML file. You create and edit Web<br />pages containing PHP the same way you create and edit regular HTML pages.<br />When PHP is installed, the Web server is configured to look for PHP code<br />embedded in files with specified extensions. It’s common to specify the<br />extensions .php or .phtml, but you can configure the Web server to look<br />for any extension. When the Web server gets a request for a file with the designated<br />extension, it sends the HTML statements as is, but PHP statements<br />are processed by the PHP software before they’re sent to the requester.<br />When PHP language statements are processed, the output consists of HTML<br />statements. The PHP language statements are not included in the HTML sent<br />to the browser, so the PHP code is secure and transparent to the user. For<br />example, consider this simple PHP statement:<br />&lt;?php echo “&lt;p&gt;Hello World”; ?&gt;<br />In this statement, &lt;?php is the PHP opening tag, ?&gt; is the closing tag, and<br />echo is a PHP instruction that tells PHP to output the text that follows it as<br />plain HTML code. The PHP software processes the PHP statement and outputs<br />the following:<br />&lt;p&gt;Hello World<br />This is a regular HTML statement that is delivered to the user’s browser. The<br />PHP statement itself is not delivered to the browser, so the user never sees<br />any PHP statements.<br />PHP and the Web server must work closely together. PHP is not integrated<br />with all Web servers but works with many of the most popular ones. PHP is<br />developed as a project under the Apache Software Foundation and, consequently,<br />works best with Apache. PHP also works with Microsoft IIS/PWS,<br />iPlanet (formerly Netscape Enterprise Server), and others.<br />15 Chapter 1: Getting to Know PHP<br />Keeping Up with Changes in PHP<br />PHP is open source software. If you have only used software from major software<br />publishers — such as Microsoft, Macromedia, or Adobe — you will find<br />that open source software is an entirely different species. It’s developed by a<br />group of programmers who write the code in their spare time, for fun and for<br />free. There’s no corporate office to call with questions. There’s no salesperson<br />to convince you of the wonders of the software. There’s no technical support<br />phone number where you can be put on hold.<br />Sounds like there’s no support for PHP, doesn’t it? Actually, quite the opposite<br />is true: An incredible amount of support is available. PHP is supported by the<br />developers and by the many PHP users. But you need to look for the support.<br />It’s part of your job as a PHP user and developer to search out the information<br />you need.<br />Open source software changes frequently, rather than once every year or two<br />as commercial software does. It changes when the developers feel it’s ready.<br />It also changes quickly in response to problems. When a serious problem,<br />such as a security hole, is found, a new version that fixes the problem may be<br />released in days. You don’t receive glossy brochures or see splashy magazine<br />ads for a year before a new version is released. If you don’t make the effort to<br />stay informed, you may miss the release of a new version or be unaware of a<br />serious problem with your current version.<br />16 Part I: Say Hello to the PHP Scripting Language<br />Serving up Web servers<br />The software that delivers Web pages to<br />the world is called a Web server. Several Web<br />servers are available, but the most popular one<br />is Apache. Approximately 60 percent of Web<br />sites on the World Wide Web use Apache,<br />according to surveys at www.netcraft.com<br />and www.securityspace.com/s_survey/<br />data/. Apache is open source software, which<br />means it’s free. It’s available for all major operating<br />systems. It’s automatically installed with<br />most Linux distributions and is preinstalled on<br />Mac OS X. You can find information about<br />Apache at httpd.apache.org. PHP is a project<br />of the Apache Software Foundation, so PHP<br />runs best with Apache.<br />Other Web servers are available. Internet Information<br />Server (IIS) is the second most popular<br />Web server with about 30 percent of the Web<br />sites. IIS is developed by Microsoft and runs<br />only on Windows. IIS is installed by default with<br />Windows server software. Other Web servers<br />include Zeus, NCSA, and Sun ONE. No other<br />Web server is used on more than 2.5 percent of<br />the Web sites.<br />Visit the PHP Web site often. You need to know the information that’s published<br />there. Join the mailing lists, which often are very high in traffic. When<br />you first start using PHP, the large number of mail messages on the discussion<br />lists brings valuable information into your e-mail box; you can pick up a lot by<br />reading those messages. And soon, you may be able to help others based on<br />your own experience. At the very least, subscribe to the announcement mailing<br />list, which only delivers e-mail occasionally. Any important problems or new<br />versions are announced here. The e-mail you receive from the announcement<br />list contains information you need to know.<br />So, right now, before you forget, hop over to the PHP Web site and sign up for<br />a list or two at www.php.net/mailing-lists.php.<br />PHP 5<br />Most of the important changes in PHP version 5 don’t affect the coding or the<br />use of PHP. They affect the performance of PHP. The Zend engine (the magic,<br />invisible engine that powers PHP) has been significantly improved, and as a<br />result, scripts run faster and more efficiently.<br />The object-oriented programming features of PHP are a major focus of PHP 5.<br />Object-oriented programming is greatly improved over PHP 4. The creation<br />and use of objects runs much faster, many object-oriented features have been<br />added, and exceptions are introduced. Programmers who prefer objectoriented<br />programming will be much happier with PHP 5. (Object-oriented<br />programming is described in Chapter 9.)<br />With PHP 5, the names of the PHP programs changed. PHP for the Web is<br />called php-cgi; PHP CLI is called just php, as in php.exe on Windows. Both<br />are stored in the directory where PHP is installed. Prior to PHP 5, both programs<br />were named php.exe, but stored in different subdirectories.<br />PHP 5 adds support for MySQL 4.1 and later. However, support for MySQL<br />is not included with PHP 5 by default. Support for MySQL 4.0 or MySQL 4.1<br />must be specified when PHP is installed. Prior to PHP 5, support for MySQL<br />4.0 and earlier was included automatically.<br />PHP 5 includes support for SQLite by default. SQLite provides quick and easy<br />methods for storing and retrieving data in flat files.<br />17 Chapter 1: Getting to Know PHP<br />Previous versions of PHP<br />You should be aware of some significant changes in previous PHP versions<br />because existing scripts that work fine on earlier versions may have problems<br />when they’re run on a later version, and vice versa. The following are some<br />changes you should be aware of:<br /> Version 4.3.1: Fixed a security problem in 4.3.0. It’s not wise to continue<br />to run a Web site using versions 4.3.0 or earlier.<br /> Version 4.3.0: Included significant improvements to the CLI version of<br />PHP, which is now built by default when you compile PHP from source<br />code (described in Appendix A). You must disable its build with installation<br />options if you don’t want it to be built.<br /> Version 4.2.0: Changed the default setting for register_globals to Off.<br />Scripts running under previous versions may depend on register_<br />globals being set to On and may stop running with the new setting. It’s<br />best to change the coding of the script so that it runs with<br />register_globals set to Off.<br /> Version 4.1.0: Introduced the superglobal arrays. Scripts written using<br />the superglobals (described in Chapter 6) won’t run in earlier versions.<br />Prior to 4.1.0, you must use the old style arrays, such as<br />$HTTP_POST_VARS.<br />By the time you read this, it’s possible that everyone has updated to PHP 5.<br />However, some IT departments and Web hosting companies may not update<br />immediately. Keep the previous changes in mind when using older versions.<br />18 Part I: Say Hello to the PHP Scripting Language<br />Chapter 2<br />Setting Up the Environment<br />In This Chapter<br /> Getting access to PHP through Web hosting companies<br /> Building your own Web site from scratch<br /> Testing PHP<br />Now that you’ve decided to use PHP, your first task is to set up an environment<br />for PHP development. As I discuss in Chapter 1, PHP is used<br />most often to develop dynamic Web sites, so the majority of this chapter discusses<br />setting up PHP for use with a Web site. If you plan to use PHP only as a<br />general-purpose scripting language, independent of the Web, setting up your<br />environment is much simpler. You can skip the sections about setting up a<br />Web environment and go directly to the section, “Setting Up PHP for General-<br />Purpose Scripting.”<br />Establishing Your Web Environment<br />PHP for Web development runs in partnership with a Web server, as described<br />in Chapter 1. Thus, a Web site requires a Web server. To use PHP in your Web<br />site, the Web server must be able to exchange information with the PHP software,<br />and, thus, PHP must be installed where the Web server can access it.<br />The Web site environment involves more than just a Web server and PHP on<br />a computer. Here are a few other requirements:<br /> The computer must be connected to the Internet.<br /> The computer must have enough resources, such as disk space and<br />memory, to handle the expected Web traffic.<br /> Other software, such as a database, may be required in the environment.<br />You may or may not be interested in setting up your own Web environment.<br />You may think that installing software is fun, or you may think it’s similar to<br />having the flu. If you want to install your own Web environment from scratch,<br />you can. You may even already have a Web site running on your own computer<br />and are just looking to add to its functionality by using PHP. If you don’t want<br />to install your own Web environment, you can use a Web environment installed<br />and maintained by someone else, such as the IT department at work or a<br />commercial Web hosting company. Perhaps you have an existing Web site at<br />a hosting company that you want to make more dynamic. You can use PHP in<br />either a Web environment of your own or one provided by someone else.<br />Another common development environment includes both your own Web<br />environment and one maintained by someone else. That is, it’s common for<br />developers to set up testing Web environments on their own computers where<br />they write and debug Web pages. Then, when everything is working correctly,<br />the Web pages are transferred to their Web site at work, maintained by the IT<br />department, or to a Web hosting company.<br />The following are some advantages of using someone else’s Web environment:<br /> It’s easier than setting up your own: You just copy your Web pages onto<br />the other party’s computer, and that’s it. You don’t need to install any<br />software or hardware or resolve any computer problems. Someone else<br />handles that for you.<br /> Less technical skill is required: You need to understand only Web languages,<br />such as HTML and PHP. You don’t need to know about Internet<br />connections, Web servers, computer administration, and other technical<br />things. Some people are very interested in these things, but some are not.<br />The advantages of running your own Web environment are as follows:<br /> Control: You get to make all the decisions. You can set up the Web environment<br />the way that works best for you.<br /> Access: You can access the computer whenever you want to work on<br />your Web site.<br /> Stability: You know the Web site will be there as long as you need it. You<br />won’t wake up one morning to discover that your Web hosting company<br />has gone out of business and you have two days to move your site.<br /> Security: Because you control the Web environment, you are the only<br />person who needs to access the computer. You can keep it under lock<br />and key. When you use a Web hosting company, other people have<br />access to the computer, and one of them may be a bad guy who’s after<br />your secrets.<br />20 Part I: Say Hello to the PHP Scripting Language<br />Using an existing Web environment<br />When you use a Web environment set up by someone else, you don’t need<br />to understand the installation and administration of the Web site software.<br />Someone else — your company’s IT department, a commercial Web hosting<br />company, your next-door neighbor — is responsible for the operation of the<br />Web site. It’s their job to provide you with a working Web site, including PHP<br />if it’s required. Your job is only to write and install the Web site files.<br />To use an existing Web environment, you need the following information from<br />the Web site administrator:<br /> The location of Web pages: For the world to see your Web site, the files<br />containing the Web pages must be in a specific location on the computer.<br />The Web server that delivers the Web pages to the world expects to find<br />the files in a specific directory. You need to know where that directory is<br />and have access to the directory.<br /> The Web page installation process: You need to know how to install the<br />files. In most cases, you send the files via FTP to the proper location. FTP<br />(File Transfer Protocol) is a method of copying a file from one computer<br />to another on a network. In some cases, you may copy the files directly<br />or use other methods to install the Web pages. You may need a user ID<br />and password to install the files.<br /> The name of the default file: When users point their browsers at a URL, a<br />file is sent to them. The Web server is set up to send a specific default file<br />when the URL points to a directory. Very often the default file is named<br />index.htm or index.html, but sometimes other names are used, such as<br />default.htm. You need to know what you should name your default file.<br /> The PHP file extension: When PHP is installed, the Web server is<br />instructed to expect PHP statements in files with specific extensions.<br />Frequently, the extensions used are .php or .phtml, but other extensions<br />can be used. PHP statements in files that do not have the correct extensions<br />won’t be processed. You need to know what extension to use for<br />your PHP scripts.<br />One of the disadvantages of hosting your site in an existing Web environment<br />is that you have no control over your development environment. The administrators<br />of the Web environment provide the environment that works best<br />for them. For instance, PHP has a myriad of options that can be set, unset, or<br />given various values. The administrators decide the option settings based on<br />their needs, which may or may not be ideal for your purposes. They probably<br />set up the environment for ease of maintenance, low cost, and minimal customer<br />defections. You can’t change certain parts of your environment; you<br />can only beg the administrators to change it. They will be reluctant to change<br />a working setup because a change may cause problems for their system or<br />for other customers.<br />21 Chapter 2: Setting Up the Environment<br />Choosing a Web hosting company<br />A Web hosting company provides everything you need to put up a Web site,<br />including the computer space and all the Web site software. You just create<br />the files for your Web pages and move them to a location specified by the<br />Web hosting company.<br />About a gazillion companies offer Web hosting services. Most charge a monthly<br />fee, which is often quite small, and some are even free. Most of the free ones<br />require you to display advertising. Usually, the monthly fee varies, depending<br />on the resources provided for your Web site. For instance, a Web site with<br />2MB (megabytes) of disk space for your Web page files costs less than a Web<br />site with 10MB of disk space.<br />When looking for a place to host your Web site, make sure that the Web hosting<br />company offers PHP. Some do not. Also, make sure the company offers a<br />recent version of PHP. Web hosting companies may not offer a version that<br />has just been released, but they should upgrade their PHP fairly soon after a<br />new version is released.<br />Don’t consider a Web hosting company that offers only PHP 3. PHP 4.3.1 was<br />released in February 2003, so no Web hosting company should still be providing<br />PHP older than 4.3.1, especially because a security issue was discovered<br />in earlier versions and was fixed in PHP 4.3.1. Ideally, by the time you read<br />this, most Web hosting companies will be offering PHP 5.<br />Other considerations when choosing a Web hosting company include the<br />following:<br /> Reliability: You need a Web hosting company that you can depend on —<br />one that won’t go broke and disappear tomorrow. And you want one<br />that has enough computer power and other resources to keep your Web<br />site up. A Web site with more down time than up time is pretty useless.<br />Hopefully, some research on the Web or among colleagues will identify<br />Web hosting companies whose reliability is not up to snuff.<br /> Speed: Web pages that download slowly are a problem because users<br />will get impatient and go elsewhere. Slow pages may be a result of a Web<br />hosting company that started its business on a shoestring and has a<br />shortage of good equipment, or the problem may be a Web hosting company<br />that is so successful that its equipment is overwhelmed by new<br />customers. Either way, Web hosting companies that deliver Web pages<br />too slowly are unacceptable. In some cases, you can find sites that are<br />hosted at the Web hosting company and see the download speed for<br />these sites. Sometimes the Web hosting company’s Web site provides<br />some customer links, or the company’s salespeople may provide you<br />with this information.<br /> Technical support: Some Web hosting companies have no one available<br />to answer questions or troubleshoot problems. Technical support is<br />22 Part I: Say Hello to the PHP Scripting Language<br />often provided through e-mail only, which can be acceptable if the<br />response time is short. Sometimes you can test the quality of the company’s<br />support by calling the tech support number, or test the e-mail<br />response time by sending an e-mail.<br /> Domain name: Each Web site has a domain name that Web browsers use<br />to find the site on the Web. Each domain name is registered, for a small<br />yearly fee, so that only one Web site can use it. Some Web hosting companies<br />allow you to use a domain name that you have registered independently<br />of the Web hosting company, some assist you in registering<br />and using a new domain name, and some require you to use their domain<br />name. For instance, suppose your company’s name is Good Stuff and you<br />want your Web site to be named JanetsGoodStuff. Some companies allow<br />your Web site to be JanetsGoodStuff.com, but some require that your<br />Web site be named JanetsGoodStuff.webhostingcompanyname.com,<br />or webhostingcompanyname.com/~GoodStuff, or something similar. In<br />general, your Web site will look more professional if you can use your<br />own domain name.<br /> Features: You should select features based on the purpose of your Web<br />site. Usually a hosting company bundles its features into plans — more<br />features generally means higher cost. Some features to consider include<br />the following:<br />• Disk space: How many MB/GB (gigabytes) of disk space will your<br />Web site require? Media files, such as graphics or music files, can<br />be quite large.<br />• Data transfer: Some hosting companies charge you for sending<br />Web pages to users. If you expect to have a lot of traffic on your<br />Web site, this cost should be a consideration.<br />• E-mail addresses: Many hosting companies provide you with a<br />number of e-mail addresses for your Web site. For instance, if your<br />Web site is JanetsGoodStuff.com, you could allow users to send<br />you e-mail at me@JanetsGoodStuff.com.<br />• Software: Hosting companies offer access to a variety of software<br />for Web development. In addition to the PHP required for this<br />book, some hosting companies offer databases, such as MySQL or<br />PostgreSQL, and other development tools such as FrontPage extensions,<br />shopping cart software, credit card validation, and other tools.<br />• Statistics: Often hosting companies can help you gather statistics<br />regarding your Web traffic, such as the number of users, time of<br />access, access by Web page, and so on.<br /> Backups: Backups are copies of your Web page files and your database<br />that are stored in case your files or database are lost or damaged. You<br />want to be sure that the company makes regular, frequent backup copies<br />of your application. You also want to know how long it would take for<br />backups to be put in place to restore your Web site to working order<br />after a problem.<br />23 Chapter 2: Setting Up the Environment<br />It’s difficult to research Web hosting companies from a standing start — a<br />search at Google for Web hosting results in over 4 million hits. The best way<br />to research Web hosting companies is to ask for recommendations from<br />people who have experience with those companies. People who have used a<br />hosting company can warn you that the service is slow or that the computers<br />are frequently down. After you have gathered a few names of Web hosting<br />companies from satisfied customers, you can narrow the list to the one that<br />is best suited and most cost-effective for your purposes.<br />24 Part I: Say Hello to the PHP Scripting Language<br />The domain name game<br />Every Web site needs a unique address on the<br />Web. The unique address used by computers to<br />locate a Web site is the IP address. It is a series<br />of four numbers between 0 and 255, separated<br />by dots — for example, 172.17.204.2 or<br />192.163.2.33.<br />Because IP addresses are made up of numbers<br />and dots, they’re not easy to remember.<br />Fortunately, most IP addresses have associated<br />names that are much easier to remember. Some<br />examples include amazon.com, www.irs.<br />gov, or mycompany.com. A name that is an<br />address for a Web site is called a domain name.<br />A domain can be one computer or many connected<br />computers. When a domain refers to several<br />computers, each computer in the domain<br />may have its own name. A name that includes<br />an individual computer name, such as thor.<br />mycompany.com, names a subdomain of<br />mycompany.com.<br />The domain or subdomain name is a required<br />component of the URL — the address that a<br />Web surfer types into the browser window to<br />identify the Web site he wants to visit. The URL<br />can contain more elements than just the domain<br />name, but often, the domain name (amazon.<br />com, for example) is all that is required. Or the<br />subdomain name (janet.valade.com, for<br />example) may be sufficient. When only the<br />domain name is used in the URL, the Web server<br />sends the file with the default filename, such<br />as index.htm or index.html. Or you can<br />include a filename in the URL, in addition to the<br />domain name, such as janet.valade.com/<br />links.html.<br />Each domain name must be unique to serve as<br />an address. Consequently, a system for registering<br />domain names ensures that no two locations<br />use the same domain name. Anyone can register<br />any domain name, as long as the name is not<br />already taken. You can register a domain name<br />on the Web. First, you test your potential domain<br />name to find out whether it is available. If it’s<br />available, you register it in your name or a company<br />name and pay the fee. The name is then<br />yours to use, and no one else can use it. The<br />standard fee for domain name registration is<br />$35.00 per year. You should never pay more, but<br />bargains are often available.<br />Many Web sites, including those of many Web<br />hosting companies, enable you to register a<br />domain name. A search at Google (google.<br />com) for “domain name register” results in over<br />2 million hits. Shop around to be sure you find<br />the lowest price. Also, many Web sites allow<br />you to enter a domain name and see who it is<br />registered to. These Web sites do a domain<br />name database search by using a tool called<br />whois. A search at Google for “domain name<br />whois” results in over half a million hits. A<br />couple places where you can do a whois<br />search are Allwhois (Allwhois.com) and<br />Better-Whois (betterwhois.com).<br />You can ask for names from colleagues and friends. Also, people often ask for<br />recommendations for hosting companies on the PHP discussion lists. Many<br />people on the lists have experience using PHP with Web hosting companies<br />and are glad to provide recommendations or warnings. Because people often<br />ask this question, you may get all the information you need from the list<br />archives, which you can search at marc.theaimsgroup.com/.<br />Setting up your own Web environment<br />If you’re starting a Web site from scratch, you need to understand the Web<br />site software fairly well. You have to make several decisions regarding hardware<br />and software. You also need to install a Web server and PHP, as well as<br />maintain, administer, and update the system yourself. Taking this route<br />requires more work and more knowledge. The advantage is that you have<br />total control over the Web development environment.<br />The following are the general steps for setting up the Web environment<br />needed for the activities described in this book:<br />1. Set up the computer.<br />2. Install the Web server.<br />3. Install PHP.<br />The first step is outside the scope of this book. You probably have a computer<br />but may be planning to install a new one for your Web site. For more<br />information on buying and setting up computers, pick up a copy of Buying a<br />Computer For Dummies or PCs For Dummies, 9th Edition, both by Dan Gookin<br />and published by Wiley Publishing, Inc. Web servers and PHP exist for almost<br />all hardware and operating systems, including many flavors of Unix and Linux,<br />Windows, and Mac OS X.<br />Installing the Web server<br />When your computer is set up and ready, you need to decide which Web server<br />to install. Apache is generally your best bet because it offers the following<br />advantages:<br /> It’s free: What else do I need to say?<br /> It runs on a wide variety of operating systems: Apache runs on<br />Windows, Linux, Mac OS, FreeBSD, and most varieties of Unix.<br /> It’s popular: Approximately 60 percent of Web sites on the Internet use<br />Apache, according to surveys at www.netcraft.com/survey and at www.<br />securityspace.com/s_survey/data/. This wouldn’t be true if it didn’t<br />work well. Also, this means that a large group of users can provide help.<br /> It’s reliable: After Apache is up and running, it should run as long as your<br />computer runs. Emergency problems with Apache are extremely rare.<br />25 Chapter 2: Setting Up the Environment<br /> It’s customizable: The open source license allows programmers to modify<br />the Apache software, adding or modifying modules as needed to fit their<br />own environments.<br /> It’s secure: Free software is available that runs with Apache to make it<br />into a secure SSL server. SSL is used to provide extra security for Web<br />sites that need to protect important information. It means that the information<br />passed between the Web server and the browser is encrypted so<br />that no one can intercept and read it. Security is an essential issue if<br />you’re using the site for e-commerce.<br />Apache is automatically installed when you install most Linux distributions.<br />Apache is also usually preinstalled on Mac. For most Unix flavors, you want<br />to download the Apache source and compile it yourself, although some<br />binaries (programs that are already compiled for specific operating systems)<br />are available. For Windows, you need to install a binary file, preferably on<br />Windows NT/2000/XP, although Apache also runs on Windows 98/Me.<br />As of this writing, Apache 1.3.27 is the current stable release. Apache 2 is also a<br />stable release, but it is still considered experimental to use PHP and Apache 2.<br />Check the PHP Web site (www.php.net) to find out the current status of PHP<br />and Apache 2 together. Apache information, software downloads, documentation,<br />and installation instructions for various operating systems are available<br />at the Apache Web site (httpd.apache.org). The Web site provides extensive<br />documentation.<br />Other Web servers are available. Microsoft offers Internet Information Server<br />(IIS), which is the second most-popular Web server on the Internet with<br />approximately 27 percent of Web sites. Sun offers iPlanet (formerly Netscape<br />Enterprise Server), which serves less than 5 percent of the Internet. Other<br />Web servers are available, but they have even smaller user bases.<br />Installing PHP<br />Many computer systems come with PHP already installed. Most Linux distributions<br />include PHP. Some newer versions of Mac OS X also come with PHP<br />installed. Before you install PHP, check whether it’s already installed by<br />searching your disk for any PHP files in the following manner:<br /> Linux/Unix/Mac: At the command line, type the following:<br />find / -name “php*”<br /> Windows: Use the Find feature (choose Start➪Find) to search for php*.<br />If you don’t find any PHP files, PHP is not installed. To install PHP, you need<br />access to the Web server for your site. For instance, when you install PHP<br />with Apache, you need to edit the Apache configuration file. All the information<br />and software you need is provided on the PHP Web site (www.php.net).<br />Detailed installation instructions are provided in Appendix A.<br />26 Part I: Say Hello to the PHP Scripting Language<br />If you do find PHP files, PHP is already installed, and you may not need to reinstall<br />it. Use the following considerations to decide whether to reinstall PHP:<br /> Installation options: PHP may not have been installed with the options<br />you require. For instance, PHP may not have been installed with support<br />for the database that you’re planning to use. Support for ODBC is always<br />included, but support for MySQL, Oracle, MS SQL, and other databases<br />must be specified when PHP is installed. Support is also always included<br />for SQLite, XML, COM, FTP, and others, but other support is not automatically<br />included. If you’re planning to use another database or other<br />software or features, you may need to reinstall PHP with added support.<br />You can check which options were used when PHP was installed. Follow<br />the directions for testing PHP in the following section. If the test script<br />runs correctly, the table displayed by the phpinfo() statement shows<br />all the support that is included in your PHP installation. Check whether<br />the support you need is included. If it’s not, you need to reinstall. Detailed<br />instructions for installing PHP are provided in Appendix A.<br /> Version: The installed version may not be the most recent. You need to<br />check the version of PHP that’s installed. You can check the version with<br />the following command:<br />php-cgi –v<br />For versions prior to PHP 5, the command to check the version is:<br />php –v<br />You may need to be in the same directory with the file php-cgi.exe (or<br />php.exe)to execute the preceding command. You see output similar to<br />the following that shows the version of PHP that is installed:<br />PHP 5.0.0 (cgi-fcgi), Copyright (c) 1997-2003 The PHP<br />Group<br />Zend Engine v2.0.0, Copyright (c) 1998-2003 Zend<br />Technologies<br />If the version is not the most recent, you should reinstall it. To see what<br />the latest stable version is, check www.php.net/downloads.php.<br />Testing PHP<br />After you have the information you need to use PHP on your Web site at the<br />Web hosting company or you have PHP installed on your own computer, you<br />need to test to make sure PHP is working correctly. To test whether PHP is<br />installed and working, follow these steps:<br />1. Locate the directory in which your PHP scripts need to be located.<br />27 Chapter 2: Setting Up the Environment<br />This directory and the subdirectories under it are called your Web space.<br />The default Web space for Apache is htdocs in the directory where<br />Apache is installed. For IIS, it is Inetpub\wwwroot. In Linux, it may be<br />/var/www/html. Different directories may be configured for your Web<br />space when the Web server is installed, so if someone other than you<br />installed the Web server, you may need to ask what the directory is. If<br />you’re using a Web hosting company, it will supply the directory name.<br />2. Create a file somewhere in your Web space with the name test.php<br />that contains the following code:<br />&lt;html&gt;<br />&lt;head&gt;<br />&lt;title&gt;PHP Test&lt;/title&gt;<br />&lt;/head&gt;<br />&lt;body&gt;<br />&lt;p&gt;This is an HTML line<br />&lt;?php<br />echo “&lt;p&gt;This is a PHP line&lt;/p&gt;”;<br />phpinfo();<br />?&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />3. Point your browser at the file test.php created in Step 2 by typing<br />the URL to the file.<br />The URL will be in the format http://www.mycompany.com/test.php.<br />If your Web server, PHP, and the test.php file are on the same computer<br />you are testing from, you can type localhost/test.php.<br />In order for the file to be processed by PHP, you need to access the file<br />through the Web server, not by choosing File➪Open in your Web browser.<br />If your Web server, PHP, and test.php file are on the same machine you<br />are testing from, you can type localhost/test.php.<br />You should see the following in the Web browser:<br />This is an HTML line<br />This is a PHP line<br />Below these lines, you should see a large table, which shows all the information<br />associated with PHP on your system. It shows PHP information,<br />path names and filenames, variable values, what software is supported,<br />and the status of various options. For instance, if you scroll down<br />the table, you see a block of options for FTP that says: FTP support<br />enabled.<br />The table is produced by the line phpinfo() in the test script. Any time<br />you have a question about the settings for PHP, you can use the statement<br />phpinfo() to display this table and check settings. The phpinfo()<br />statement is used often throughout this book.<br />28 Part I: Say Hello to the PHP Scripting Language<br />If there are problems with the PHP installation, you might get one of the following<br />results from the test file:<br /> You see only This is an HTML line. The PHP lines and the table of<br />information are not displayed.<br /> You see a blank page.<br /> The browser displays a download window rather than the Web page.<br />If you get a problem result from the test file and you are not the system<br />administrator, you need to talk to the person who installs and maintains the<br />software, such as an IT staff member at work or a technical support person at<br />your Web hosting company. It’s their responsibility to diagnose your problem.<br />If you get a problem result from the test file and you installed the software<br />yourself, first check to see that PHP is installed. At the command line, change<br />to the directory where PHP is installed and type the following:<br />php-cgi –v<br />or<br />php -v<br />If PHP returns information about its version, PHP is installed. Be sure that<br />you accessed the test file as instructed in Step 3 in the preceding list. Notice<br />the warning for that step.<br />Be sure that the file test is in a directory in your Web space, as described in<br />Step 1 of the preceding steps. In Apache, you can check the httpd.conf file<br />for a line similar to the following line:<br />DocumentRoot “C:/Program Files/Apache Group/Apache/htdocs”<br />This line tells Apache where to look for Web page files.<br />Double-check the script to make sure you typed it correctly. The script is also<br />available for download from my Web site: janet.valade.com.<br />If you are accessing the test file correctly and it seems to be entered correctly,<br />the problem is probably in your configuration. Reread the instructions for<br />configuring PHP at the end of Appendix A and make sure that you followed all<br />the instructions. In particular, check the following:<br /> The Web server is configured to know which file extensions to check for<br />PHP code. In Apache, check that the following line is included in the<br />httpd.conf file:<br />AddType application/x-httpd-php .php<br />29 Chapter 2: Setting Up the Environment<br />This line tells Apache to look for PHP code in files with the extension<br />.php. For IIS, access the console, as described in Appendix A, and check<br />the extension tab to be sure the correct extension is set.<br /> Check to be sure the other lines were correctly added to the httpd file<br />for Apache, as described in the configuration sections for the appropriate<br />operating system in Appendix A. Check for any possible misspellings.<br />Also check that the lines were added in the correct location.<br /> If you’re using IIS, check for the following line in php.ini:<br />cgi.force_redirect = 0<br />If your php.ini doesn’t contain this line, add it. If you have the line with<br />a semicolon at its beginning, remove the semicolon. If you find a line<br />with a setting of 1 rather than 0 (zero), change it to 0.<br />If you check everything carefully and are still having problems, it’s possible<br />that you have something unusual in your computer setup or your Web server<br />that is causing the problem. Read all the online documentation related to<br />installation at the PHP Web site. Search the Web site for information on installation<br />problems. You can find a wealth of information there.<br />If you still can’t find the answer, take your question to the PHP discussion<br />lists. First, search the archives at marc.theaimsgroup.com/. It’s possible<br />that someone has previously asked the same question and you can find the<br />answer quickly in the archives. If not, post your question to the discussion<br />list. Include the following information in your question:<br /> Indicate the name and version of the operating system you’re using.<br /> Identify the PHP version you’re trying to install.<br /> Copy the content of the test file into your message.<br /> Describe the exact output that you see in your Web page.<br />People on the list are very knowledgeable and will help you solve your<br />problem.<br />Setting Up PHP for General-<br />Purpose Scripting<br />PHP runs by itself when used as a general-purpose programming language.<br />You don’t need to have a Web server installed if you’re not using PHP with a<br />Web site. The command line version of PHP — PHP CLI — is a separate program,<br />different than the PHP program you use for Web sites. It needs to be<br />installed separately.<br />30 Part I: Say Hello to the PHP Scripting Language<br />Even if your machine came with PHP installed, PHP CLI may not be there. You<br />can check to see if PHP is on your computer and which version is there. By<br />default, you should find the file in the directory where PHP is installed. The<br />PHP CLI file is named php.exe and the PHP CGI file is named php-cgi.exe.<br />(Prior to PHP 5, the files were both named php.exe, but stored in different<br />subdirectories. PHP CLI was stored in a subdirectory named /cli.)Or PHP<br />CLI may have been installed in another location. You can search your disk for<br />all PHP files as follows:<br /> Linux/Unix/Mac: Type the following at the command line:<br />find / -name “php*”<br /> Windows: Use the Find feature (choose Start➪Find) to search for php*.<br />If you find any PHP files that you think might be PHP CLI, you can check<br />by changing to the directory where the PHP program file is and typing the<br />following:<br />php –v<br />The output will include either cgi or cli, similar to the following:<br />PHP 5.0.0 (cli) (built: Jun 15, 2003 23:07:34)<br />Notice that the output includes (cli). If it’s not the CLI version, it shows<br />(cgi). The previous command also serves to test whether PHP CLI is working.<br />If it responds with the version number rather than an error message, it’s<br />working.<br />If you don’t find PHP CLI, you need to install it before you can use PHP for<br />tasks that are unrelated to the Web. Appendix A provides detailed PHP installation<br />instructions, including instructions for PHP CLI.<br />If you’re going to use PHP for both Web sites and general-purpose programming,<br />you need to install two different PHP programs, the version for the Web<br />and PHP CLI. Both need to be the same version of PHP. That is, if you install<br />PHP 5.0.0 for the Web, be sure that you’re using PHP CLI 5.0.0 as well. In<br />Windows, PHP requires a file called php5ts.dll, which is in your main PHP<br />directory. You need to use the same version of PHP so that both PHP programs<br />use the same version of php5ts.dll. (See Appendix A for details.)<br />31 Chapter 2: Setting Up the Environment<br />Configuring PHP<br />PHP is very flexible. Configuration settings determine some of PHP’s behavior,<br />such as whether it displays error messages, A file called php.ini stores the<br />configuration settings. You can change the setting by editing php.ini.<br />When PHP is installed, php.ini is created, as described in Appendix A. If<br />you install PHP yourself, remember where you put php.ini. You may need<br />to change it. If you’re using PHP, but someone else is the PHP administrator<br />(for instance, if you’re using a Web hosting company), you are unlikely to<br />have access to php.ini. If you need to make a change to the PHP settings,<br />you will have to ask the administrator. For some settings, you can add statements<br />to your script to change the settings temporarily, for that script only.<br />Specific statements that change settings temporarily are discussed in context<br />throughout this book.<br />Using Tools to Build PHP Scripts<br />PHP scripts are just text files. You can use your favorite tool for writing text<br />files to write PHP scripts. Many scripts have been written with vi, Notepad, or<br />WordPad. However, you can find tools that make script writing much easier.<br />It’s worthwhile to check out programming editors and Integrated Development<br />Environments (IDEs) before creating your PHP scripts. These tools offer features<br />that can save you enormous amounts of time during development. So<br />download some demos, try out the software, and select the one that suits<br />you best. You can take a vacation on the time you save later.<br />Programming editors<br />Programming editors offer many features specifically for writing programs.<br />The following features are offered by most programming editors:<br /> Color highlighting: Highlight parts of the script — such as HTML tags,<br />text strings, keywords, and comments — in different colors so they’re<br />easy to identify.<br /> Indentation: Automatically indent inside parentheses and curly braces<br />to make scripts easier to read.<br /> Line numbers: Add temporary line numbers. This is important because<br />PHP error messages specify the line where the error was encountered. It<br />would be cumbersome to have to count 872 lines from the top of the file<br />to the line that PHP says is a problem.<br />32 Part I: Say Hello to the PHP Scripting Language<br /> Multiple files: Can have more than one file open at once.<br /> Easy code inserting: Buttons for inserting code, such as HTML tags or<br />PHP statements or functions.<br /> Code library: Save snippets of your own code that can be inserted by<br />clicking a button.<br />Many programming editors are available on the Internet for free or for a low<br />price. Some of the more popular editors include the following:<br /> Arachnophilia: (www.arachnoid.com/arachnophilia/) This multiplatform<br />editor is written in Java. It’s CareWare, which means it doesn’t<br />cost any money.<br /> BBEdit: (www.barebones.com/products/bbedit/index.shtml) This<br />editor is designed for use on a Mac. BBEdit sells for $179.00. Development<br />and support have been discontinued for BBEdit Lite, which is free, but it<br />can still be found and legally used. TextWrangler is offered for $49 as a<br />replacement for BBEdit Lite.<br /> EditPlus: (www.editplus.com) This editor is designed for use on a<br />Windows machine. EditPlus is shareware, and the license is $30.<br /> Emacs: (www.gnu.org/software/emacs/emacs.html) Emacs works<br />with Windows, Linux, and Unix, and it’s free.<br /> HomeSite: (www.macromedia.com/software/homesite/) HomeSite is<br />designed for use with Windows and will run you $99.00.<br /> HTML-Kit: (www.chami.com/html-kit/) This is another Windows<br />editor that you can pick up for free.<br /> vim and gvim: (www.vim.org/) These free, enhanced versions of vi can<br />be used with Windows, Linux, Unix, and Mac OS. The gvim editor has a<br />GUI that makes Windows users feel more at home.<br />Integrated Development<br />Environment (IDE)<br />An Integrated Development Environment (IDE) is an entire workspace for<br />developing applications. It includes a programming editor as well as other<br />features. Some features included by most IDEs are the following:<br /> Debugging: Has built-in debugging features.<br /> Previewing: Displays the Web page output by the script.<br /> Testing: Has built-in testing features for your scripts.<br />33 Chapter 2: Setting Up the Environment<br /> FTP: Has built-in ability to connect and upload/download via FTP. Keeps<br />track of which files belong in which Web site and keeps the Web site upto-<br />date.<br /> Project management: Organizes scripts into projects; manages the files<br />in the project; includes file checkout and check-in features.<br /> Backups: Makes automatic backups of your Web site at periodic intervals.<br />IDEs are more difficult to learn than programming editors. Some are fairly<br />expensive, but their wealth of features can be worth it. IDEs are particularly<br />useful when several people will be writing scripts for the same application.<br />An IDE can make project coordination much simpler and make the code more<br />compatible.<br />The following are popular IDEs:<br /> Dreamweaver MX: (www.macromedia.com/dreamweaver) This IDE is<br />available for the Windows and Mac platforms. It provides visual layout<br />tools so you can create a Web page by dragging elements around and<br />clicking buttons to insert elements. Dreamweaver can write the HTML<br />code for you. It includes the HomeSite editor so you can write your own<br />code. It also supports PHP. Dreamweaver will set you back $399.00.<br /> Komodo: (www.activestate.com/Products/Komodo/) Komodo is<br />offered for the Linux and Windows platforms. It’s an IDE for open source<br />languages, including Perl and Python, as well as PHP. It’s offered for<br />$29.95 for personal or educational use, and $295.00 for commercial use.<br /> Maguma: (www.maguma.com) Maguma is available for Windows only. It’s<br />an IDE for Apache, PHP, and MySQL on Windows and comes in two versions<br />at different costs: Maguma Studio Desktop and Maguma Studio<br />Enterprise, which offers features for huge sites with multiple servers.<br />Maguma Studio for PHP is a free version with support for PHP only.<br /> PHPEdit: (www.phpedit.net/products/PHPEdit/) This free IDE is<br />available only for Windows.<br /> Zend Studio: (www.zend.com/store/products/zend-studio.php)<br />Zend Studio is offered for the Linux and Windows platforms. This IDE<br />was developed by the people who developed the Zend engine, which is<br />the engine under the hood of PHP. These people know PHP extremely<br />well. Zend Studio will run you $195.00.<br />A Web page describing editors and IDEs useful with PHP is available at<br />phpeditors.linuxbackup.co.uk. Currently 111 editors are listed.<br />34 Part I: Say Hello to the PHP Scripting Language<br />Chapter 3<br />Creating Your First PHP Script<br />In This Chapter<br />Writing PHP statements<br /> Adding PHP sections to HTML files<br />Writing PHP output statements<br /> Documenting your scripts<br />APHP statement is an instruction that tells PHP to perform an action. A<br />PHP script is a series of PHP statements. Theoretically, a script can contain<br />as few as one statement, but it’s unlikely that any practical script would<br />consist of a single statement. In most cases, you write scripts that contain<br />several statements in a row. PHP executes the statements one at a time until<br />it reaches the end of the script.<br />As discussed in Chapter 1, PHP can do many things, and scripts are the<br />method you use to tell PHP what you want it to do. You can tell it to display<br />some text on a Web page or to store data that a user entered into a form on<br />your Web page. PHP can also do things that are unrelated to Web sites, such<br />as back up all the files in a directory on your hard disk. You can write simple<br />scripts that just display hello in a Web browser. Or you can write complicated<br />scripts that display different things in the Web browser for different people,<br />or request passwords from Web site visitors and refuse access to visitors who<br />don’t enter valid passwords. Applications often consist of two or more scripts<br />that work together to accomplish the job required. A large, complicated application,<br />such as an e-commerce application, can consist of many scripts.<br />In this chapter, I explain how to write your first script. I also discuss output<br />statements, which are the most common PHP statements. Finally, I illustrate<br />the importance of documenting your script.<br />Writing PHP Statements<br />A PHP statement tells PHP to perform an action. One of the most common<br />PHP statements is the echo statement. Its purpose is to display output. For<br />instance, take a look at the following echo statement:<br />echo “Hi”;<br />An echo statement says to output everything that is between the double<br />quotes (“). So, this statement tells PHP to output the word Hi.<br />The echo statement is a simple statement. PHP simple statements end with a<br />semicolon (;). PHP reads a simple statement until it encounters a semicolon<br />(or the PHP closing tag, discussed later in this chapter). PHP ignores white<br />space. It doesn’t care how many lines it reads. It doesn’t consider the content<br />or the syntax of the statement. It just reads until it finds a semicolon and then<br />interprets the entire content as a single statement.<br />Leaving out the semicolon is a common error, resulting in an error message<br />that looks something like this:<br />Parse error: expecting `’,’’ or `’;’’ in file.php on line 6<br />Notice that the error message gives you the line number where it encountered<br />problems. Usually, the error is that the semicolon was left off in the line before<br />the indicated line. In this case, the semicolon is probably missing on line 5.<br />You may prefer to use an editor that displays line numbers. Debugging your<br />PHP scripts is much easier this way. Otherwise, you need to count the lines<br />from the top of the script to find the line containing the error. If your script<br />contains six lines, counting them is no big deal. If your script contains 553<br />lines, however, this is less than fun. Some editors allow you to indicate a line<br />number, and the editor takes you directly there.<br />As far as PHP is concerned, an entire script full of simple statements can be<br />written in one long line, as long as the statements are separated by semicolons.<br />However, a human would have a tough time reading such a script. Therefore,<br />you should put simple statements on separate lines.<br />Sometimes several statements are combined into a block, which is enclosed<br />by curly braces ({}). Statements in a block execute together. A common use<br />of a block is in a conditional statement where statements are executed only if<br />certain conditions are met. For instance, you may want to include the following<br />instructions:<br />36 Part I: Say Hello to the PHP Scripting Language<br />if (time = midnight)<br />{<br />put on pajamas;<br />brush teeth;<br />go to bed;<br />}<br />The statements are enclosed in curly braces to ensure they execute as a block.<br />If it’s midnight, then all three actions within the block are performed. If the<br />time is not midnight, none of the statements execute (no pajamas, no clean<br />teeth; no going to bed).<br />PHP statements that use blocks, such as if statements, are called complex<br />statements. PHP reads the entire complex statement, not stopping at the first<br />semicolon it encounters. PHP knows to expect one or more blocks and looks<br />for the ending curly brace of the last block in complex statements. Notice that<br />there is a semicolon before the ending brace. This semicolon is required, but<br />no semicolon is required after the ending curly brace.<br />Notice that the statements inside the block are indented. Indenting is not<br />necessary for PHP. Indenting is strictly for readability. You should indent the<br />statements in a block so that people reading the script can tell more easily<br />where a block begins and ends. One of the more common mistakes when<br />writing scripts is to leave out a closing curly brace, particularly when writing<br />blocks inside blocks inside blocks. Tracking down a missing brace is much<br />easier when the blocks are indented.<br />Building Scripts<br />To build a script, you add PHP statements one after another to a file that you<br />name with a .php extension. Actually, if you are wise, you write the script<br />on paper first, unless the script is very simple or you are quite experienced.<br />Planning makes programming much less prone to errors.<br />If you’re writing a PHP script for your Web site, you insert the PHP statements<br />into the file that contains the HTML for your Web page. If you’re writing a script<br />that will run independent of the Web, you type the PHP statements into a file<br />and then you run the script by calling PHP directly. The following sections<br />describe how to do this.<br />37 Chapter 3: Creating Your First PHP Script<br />Adding PHP statements to HTML pages<br />If you’re using PHP for your Web site, you do so by adding PHP code to your<br />HTML Web pages. HTML files that have PHP code in them should be named<br />with a .php extension so that the Web server knows to check the file for PHP<br />code. (Actually, the Web server administrator may have specified other<br />extensions, such as .php4 or .phtml, to indicate files that can contain PHP<br />code, but .php is the most common extension. In this book, I assume that the<br />appropriate extension is .php.)<br />You add PHP code to your Web page by using tags, similar, but not identical,<br />to other tags in the HTML file. The PHP code section is enclosed in PHP tags<br />with the following form:<br />&lt;?php<br />. . .<br />PHP statements<br />. . .<br />?&gt;<br />38 Part I: Say Hello to the PHP Scripting Language<br />How the server processes PHP files<br />When a browser is pointed to a regular HTML file<br />(a file with an .html or .htm extension), the<br />Web server sends the file, as is, to the browser.<br />The browser processes the file and displays the<br />Web page that is described by the HTML tags in<br />the file. When a browser is pointed to a PHP file<br />(a file with a .php extension), the Web server<br />looks for PHP sections in the file and processes<br />them, rather than just sending them as is to<br />the browser. The steps the Web server uses to<br />process a PHP file are as follows:<br />1. The Web server starts scanning the file in<br />HTML mode.<br />It assumes that the statements are HTML<br />and sends them to the browser without any<br />processing.<br />2. The Web server continues in HTML mode<br />until it encounters a PHP opening tag<br />(&lt;?php).<br />3. When the Web server encounters a PHP<br />opening tag, it switches into PHP mode.<br />This is sometimes called escaping from<br />HTML. The Web server assumes all subsequent<br />statements are PHP statements and<br />executes the PHP statements. If there is<br />output, the server sends the output to the<br />browser.<br />4. The Web server continues in PHP mode<br />until it encounters a PHP closing tag (?&gt;).<br />5. When the Web server encounters a PHP<br />closing tag, it returns to HTML mode.<br />The scanning is then resumed, and the<br />cycle continues from Step 1.<br />Sometimes you can use a shorter version of the PHP tags. You can try using<br />&lt;? and ?&gt;, without including the php. If short tags are enabled, you can save<br />a little typing. You enable or disable short tags in the php.ini file.<br />Using short tags is sometimes not a good idea. If you move your site to a<br />server where short tags are not enabled, all your PHP tags will quit working.<br />So if you think you might ever move your Web site, using the regular tags is<br />safer.<br />All statements between the two PHP tags are passed to PHP by the Web server<br />and are processed by the PHP preprocessor. After processing, the PHP section<br />is discarded. If the PHP statements produce output, the output is sent back<br />to the Web server, which then sends the HTML and the output from the PHP<br />sections to the browser. The browser does not see the PHP section, only its<br />output (if there is any output).<br />For example, you can add the following PHP section to your HTML file. Don’t<br />forget to give the HTML file a .php extension:<br />&lt;?php<br />echo “This line brought to you by PHP”;<br />?&gt;<br />When the Web server gets the file and sees the .php extension, it checks for<br />PHP tags. When it finds the PHP tag, it executes the PHP echo statement<br />instead of sending it to the browser. Only the output from the PHP section,<br />which is This line brought to you by PHP, is sent on to the browser. In<br />your browser window, you see the output at the location in the page where<br />you added the PHP section. Even if you view the source in your browser, you<br />only see the output, not the PHP code.<br />Don’t look at the PHP file directly with your browser. That is, don’t choose<br />File➪Open➪Browse in your browser to navigate to the file and click it. You<br />must point at the file using its URL, as discussed in Chapter 2. If you see the<br />PHP code (and not the output) displayed in the browser window, you may<br />not have pointed to the file by using its URL.<br />You can add several PHP sections to a Web page. For instance, you could<br />have the following code in your file:<br />HTML statements<br />&lt;?php<br />echo “This line brought to you by PHP”;<br />?&gt;<br />HTML statements<br />&lt;?php<br />echo “This line also brought to you by PHP”;<br />?&gt;<br />39 Chapter 3: Creating Your First PHP Script<br />Both lines echoed by PHP appear in your Web page at the locations where<br />you inserted the PHP sections.<br />Using PHP independent of the Web<br />To use PHP as a general scripting language, independent of the Web, you use<br />the version of PHP called CLI, which stands for Command Line Interface. PHP<br />CLI is a different version of PHP than the version used with a Web server<br />(usually called PHP CGI). PHP CLI is created separately when PHP is installed.<br />Instructions for installing the CLI version are provided in Appendix A.<br />If you want to use the CLI version, you’re probably running PHP on Linux or<br />Unix. Windows programmers are much less likely to need to write generalpurpose<br />PHP scripts, but they can if they need to. In this section, I provide the<br />information for the Linux/Unix version, but most of the information is also<br />true when working on Windows. (In some places, I point out the differences.)<br />The following is a PHP script:<br />&lt;?php<br />echo “This line brought to you by PHP”;<br />?&gt;<br />40 Part I: Say Hello to the PHP Scripting Language<br />Running PHP scripts on Linux/Unix<br />If you’re used to running shell scripts or Perl<br />scripts on Linux/Unix, you can run PHP scripts<br />in the same way. You can add a line to the top of<br />your script that directs the script to run with<br />PHP CLI, as follows, so that you can just run the<br />script directly without manually calling PHP:<br />#! /usr/bin/php<br />&lt;?php<br />echo “This line brought to<br />you by PHP”;<br />?&gt;<br />The first line tells the script to execute by using<br />the program found at /usr/bin/php. This line<br />does not work for Windows, but it doesn’t do<br />any damage when run on Windows. You can<br />include the first line when you write the script<br />so that it is more convenient on Unix/Linux and<br />not worry about having a broken script if you<br />move the script to Windows.<br />You execute the program by typing its name. You<br />may need to be in the same directory where the<br />program is located, unless it is in a directory on<br />your system path, or you can type the entire<br />path name to the PHP script. For instance, if the<br />preceding script is called test.php, you can<br />execute it by typing the following:<br />test.php<br />Or you may need to type the entire path:<br />/mystuff/test.php<br />You need to give the file execute permission, as<br />you do for any other script that you want to execute<br />directly.<br />If you have a file named testcli.php containing this PHP code, you can run<br />it from the command line by having the file in the same directory where PHP<br />is installed and by typing the following:<br />php testcli.php<br />Or you can type the entire path name to PHP, as in the following example:<br />/usr/local/php/cli/php testcli.php<br />For Windows, use the command prompt. You enter command prompt mode<br />by choosing the appropriate entry on your menu. Usually, you choose Start➪<br />Programs➪Accessories➪Command Prompt.<br />The CLI version of PHP differs from the CGI version in the following ways:<br /> Outputting HTTP headers: Because the CGI version sends its output to<br />the Web server and then to the browser, it outputs the HTTP headers<br />(statements the Web server and browser use to communicate with each<br />other). Thus, the following is the output when the CGI version runs the<br />script in the previous example:<br />Content-type: text/html<br />X-Powered-By: PHP/5.0<br />This line brought to you by PHP<br />You don’t see the two headers on your Web page, but PHP for the Web<br />sends these headers because the Web server needs them. The CLI version,<br />on the other hand, does not automatically send the HTTP headers<br />because it is not sending its output to a Web server. The CLI output is<br />limited to the following:<br />This line brought to you by PHP<br /> Formatting error messages: The CGI version formats error messages<br />with HTML tags, because the errors are expected to be received by a<br />browser. The CLI version does not use HTML formatting for error messages;<br />it outputs error messages in plain text.<br /> Providing argc and argv by default: The argc and argv variables allow<br />you to supply data to the script from the command line (similar to argc<br />and argv in C and other languages). You aren’t likely to want to pass<br />data to the CGI version, but you are likely to want to pass data to the CLI<br />version. Therefore, argv and argc are available by default in the CLI version<br />and not in the CGI version. (The argv and argc built-in variables<br />are explained in Chapter 5.)<br />41 Chapter 3: Creating Your First PHP Script<br />When you run PHP CLI from the command line, you can use several options<br />that affect the way PHP behaves. For instance, -v is an option that displays<br />the version of PHP being accessed. To use this option, you would type the<br />following:<br />php –v<br />Table 3-1 shows the most useful PHP command-line options.<br />Table 3-1 PHP Command-Line Options<br />Option What It Does<br />-c Defines the path to the php.ini file to be used. This can be a different<br />php.ini file than the one used by the CGI version. For example,<br />-c /usr/local/php/cli/php.ini. (See Appendix A for more<br />on php.ini.)<br />-f Identifies the script to be run. For example, php -f /myfiles/<br />testcgi.php.<br />-h Displays a help file.<br />-i Displays PHP information in text output. Gives the same information as<br />phpinfo() (described in Chapter 2).<br />-l Checks the script file for errors, but doesn’t actually execute the code.<br />-m Lists the modules that are compiled into PHP. (See Chapter 14 for more<br />on modules.)<br />-r Runs PHP code entered at the command line. For example, php -r<br />‘print(‘Hi’);’.<br />-v Displays the version number of PHP.<br />Writing Your First Script<br />It’s sort of a tradition that the first program you write in any language is the<br />Hello World program. You may have written a Hello World program in<br />HTML when you first learned it. If you did, it probably looked similar to the<br />following HTML file:<br />42 Part I: Say Hello to the PHP Scripting Language<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Hello World HTML Program&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;p&gt;Hello World!&lt;/p&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />If you point your browser at this HTML program, you see a Web page that displays<br />the following output in the browser window:<br />Hello World!<br />Your first PHP script is a script that does exactly the same thing. The following<br />code is a PHP script that includes both HTML and PHP code and displays<br />Hello World! in a browser window:<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Hello World Script&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;?php<br />echo “&lt;p&gt;Hello World!&lt;/p&gt;”<br />?&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />If you point your browser at this script, it displays the same Web page as the<br />HTML script.<br />Don’t look at the file directly with your browser. That is, don’t choose File➪<br />Open➪Browse from your browser menu to navigate to the file and click it.<br />You must point at the file by typing its URL, as discussed in Chapter 2. If you<br />see the PHP code displayed in the browser window, instead of the output you<br />expect, you may not have pointed to the file by using its URL.<br />In this PHP script, the PHP section consists of the following code:<br />&lt;?php<br />echo _&lt;p&gt;Hello World!&lt;/p&gt;_<br />?&gt;<br />The PHP tags enclose only one statement — an echo statement — that simply<br />outputs the text between the double quotes.<br />When the PHP section is processed, it is replaced with the output. In this<br />case, the output is as follows:<br />&lt;p&gt;Hello World!&lt;/p&gt;<br />43 Chapter 3: Creating Your First PHP Script<br />If you replace the PHP section in the HTML version of Hello World with the<br />preceding output, the script now looks exactly like the HTML program. If you<br />point your browser at either program, you see the same Web page. If you look<br />at the source code that the browser sees (in the browser, choose View➪<br />Source), you see the same source code listing for both programs.<br />Discovering More about<br />Output Statements<br />In your Hello World script, created in the preceding section, you used an<br />echo statement, which is a good example of an output statement. Output<br />statements are used in almost every PHP script. It’s rare that you would write<br />a script that would do something and not output anything. True, a script can<br />do things that are invisible, like checking your entire hard disk to see if a certain<br />file exists. You would not see it checking. However, the search is pretty<br />pointless if the script doesn’t tell you what it found. You’d want to know where<br />it looked, when it finished, and whether or not it found the file. Because of<br />this, almost all scripts use output statements.<br />The general format of the echo statement is as follows:<br />echo outputitem1,outputitem2,outputitem3, . . .<br />Keep the following points in mind when working with echo statements:<br /> An outputitem is a number or a string of characters. Numbers are things<br />like 1 or 250. A string is a string of characters, which can include numbers.<br />See Chapter 5 for a discussion of data types.<br /> Enclose a string of characters with single or double quotes. (Chapter 5<br />explains when to use which type of quotes.)<br /> List as many outputitems as you need.<br /> Separate each outputitem with a comma. No space is added between<br />outputitems.<br /> If you want a space in your output, add it as a character in a character<br />string.<br />44 Part I: Say Hello to the PHP Scripting Language<br />Table 3-2 shows some echo statements and their output.<br />Table 3-2 echo Statements<br />Echo Statement Output<br />echo 123; 123<br />echo “Hello World!”; Hello World!<br />echo “Hello”,”World!”; HelloWorld!<br />echo “Hello”,” “,”World!”; Hello World!<br />echo Hello World!; Not valid because the string is not enclosed<br />in quotes; results in an error message<br />echo ‘Hello World!’; Hello World!<br />Processing PHP output statements<br />The Hello World script, like most PHP scripts for the Web, is written mainly<br />to output HTML code that the browser then processes and displays in your<br />Web page. When writing PHP code to deliver output to a Web browser, you<br />need to keep in mind that there are two stages, as follows:<br />1. PHP processes the PHP statement and sends the output to the Web<br />server, which sends the output to the browser.<br />PHP does not know anything about HTML code and just sends the output<br />according to the instructions you write in the PHP output statement.<br />2. The Web browser receives the output from PHP, interprets it as HTML<br />statements, and displays a Web page accordingly.<br />The Web browser only understands HTML, not PHP code, so make sure<br />your PHP output is understandable to your browser.<br />Consider the echo statement from the Hello World script:<br />echo _&lt;p&gt;Hello World!&lt;/p&gt;_<br />45 Chapter 3: Creating Your First PHP Script<br />The echo statement says to output everything that is between the double<br />quotes (“). So, for this statement, the two stages are as follows:<br />1. When PHP processes the echo statement, it outputs the following:<br />&lt;p&gt;Hello World!&lt;/p&gt;<br />PHP does not understand HTML, so it does not know that &lt;p&gt; is an HTML<br />tag and does not see &lt;p&gt; as any sort of instruction. It just outputs the<br />statement as text.<br />2. The Web browser receives the output, recognizes that &lt;p&gt; is an HTML<br />tag, and displays the output on the Web page according to the HTML<br />tags. You see the following on the Web page:<br />Hello World!<br />The HTML tags &lt;p&gt; and &lt;/p&gt; indicate the beginning and end of a paragraph<br />and are interpreted by the Web browser, but not displayed on the<br />screen. To see what PHP sent to the browser, view the source by using<br />the selections on your Web browser menu. For instance, in Internet<br />Explorer 5.5, choose View➪Source. For this Web page, the source would<br />show the following:<br />&lt;p&gt;Hello World!&lt;/p&gt;<br />Using special characters<br />in output statements<br />The echo statement interprets some special characters that affect the output.<br />One common special-character combination is \n, which starts a new line in<br />the output of an echo statement. For example, write the following line:<br />echo _&lt;p&gt;Hello\n World!&lt;/p&gt;_<br />The \n tells PHP that the output should start a new line. However, this does<br />not result in a new line on the Web page. To get a new line in the Web page,<br />you need to send the HTML code for a new line, which is &lt;br&gt;. Therefore, to<br />see the output on two lines in the Web page, you use the following statement:<br />echo _&lt;p&gt;Hello&lt;br&gt; World!&lt;/p&gt;_<br />46 Part I: Say Hello to the PHP Scripting Language<br />A comparison of echo statements in Table 3-3 shows the differences in output<br />at Stage 1 (the PHP output stage) and Stage 2 (the Web browser display stage).<br />The first column contains the echo statement used in a PHP script. The second<br />column shows the output sent by PHP to the browser. The third column is<br />the output displayed on the Web page after the PHP output is interpreted<br />by the browser as HTML code.<br />Table 3-3 Stages of Web Page Delivery<br />Echo Statement PHP Output Web Page Display<br />echo “Hello World!”; Hello World! Hello World!<br />echo “Hello”; HelloWorld! HelloWorld!<br />echo “World!”;<br />echo “Hello\nWorld!”; Hello Hello World!<br />World!<br />echo “Hello&lt;br&gt;World!”; Hello&lt;br&gt;World Hello<br />World!<br />echo “Hello &lt;br&gt;\nWorld!”; Hello &lt;br&gt; Hello<br />World! World!<br />Notice where spaces are included in the output. The first echo statement<br />includes a space so the space is output. The second row has two echo statements,<br />but neither includes a space, so no space appears in the Web page. The<br />third row shows a space on the Web page, even though no space is included<br />in the echo statement. The space is added by the browser when it reads the<br />PHP output as HTML. In HTML, a new line is not displayed as a new line; it is<br />just interpreted as a single space.<br />Use \n liberally. Otherwise, your HTML source code will have some really<br />long lines. For instance, if you echo a long form, the whole thing may be<br />one long line in the source code, even though it looks fine in the Web page<br />because you used &lt;br&gt; in all the right places. If your Web page doesn’t display<br />correctly, you may need to troubleshoot the problem in the Web page<br />source code, a difficult process if your source code is one mile-long line. Use<br />\n to break the HTML source code into reasonable lines. Taking the extra<br />time to add these line breaks will pay off if you have to troubleshoot a Web<br />page. In addition, some browsers don’t handle mile-long lines very well.<br />47 Chapter 3: Creating Your First PHP Script<br />PHP executes output statements as instructed. PHP doesn’t care whether the<br />output is going to the Web or displayed on the screen. It’s your job to know<br />what kind of output you need. If you’re writing PHP scripts for use on the Web,<br />the output needs to be in HTML statements. If you’re writing code for independent<br />scripts, executed outside the Web environment, the output needs to be<br />in plain text format for display on the screen.<br />Documenting the Script<br />Adding comments to your script is essential. Comments describe your<br />script — what it does and how it does it. The larger, more complicated, or<br />more unusual your code is, the more you need comments. After working<br />20 hours a day on a script, you may believe its code is permanently burned<br />into your brain. From experience, however, I know that two years from now,<br />when you need to revise this script, you will swear it was written by a stranger.<br />And there’s also the possibility that your scripts may need to be revised by<br />an actual stranger. You may be long gone, retired in luxury in the Bahamas,<br />when your scripts need to be revised.<br />Comments are notes that are embedded in the script itself. PHP ignores comments;<br />comments are for humans. You can embed comments in your script<br />anywhere as long as you tell PHP that they are comments. The format for<br />comments is as follows:<br />/* comment text<br />more comment text */<br />Your comments can be as long or as short as you need. When PHP sees code<br />that indicates the start of a comment (/*), it ignores everything until it sees<br />the code that indicates the end of a comment (*/).<br />It is customary and useful to put a block of comments at the top of your script<br />giving information about the script and an overview of what it does. For example,<br />here’s one possible format for a comment block at the top of your script:<br />/* name: hello.php<br />description: Displays “Hello World!” on a Web page.<br />written by: Joe Programmer<br />created: 2/1/03<br />modified: 3/15/03<br />*/<br />48 Part I: Say Hello to the PHP Scripting Language<br />PHP also has a short comment format. You can specify that a single line is a<br />comment by using the # or two slashes (//) in the following manner:<br /># This is comment line 1<br />// This is comment line 2<br />You can also use # or // in the middle of a line to signal the beginning of a<br />comment. PHP will ignore everything from the # or // to the end of the line.<br />This is useful for commenting a particular statement, as follows:<br />echo “Hello”; // this is my first output statement<br />PHP comments are not included in the HTML code that is sent to the user’s<br />browser, so the user does not see these comments.<br />It’s helpful to use descriptive comments as titles for sections of code, such as<br />the following:<br />/* Check whether the customer is over 18 years old */<br />/* Store the information in the database */<br />/* Search for the selected file name */<br />Sometimes you really want to emphasize a comment. The following format<br />makes a comment very noticeable:<br />######################################<br />## Double-Check This Section ##<br />######################################<br />Use comments as often as necessary in the script to make it clear. However,<br />using too many comments is a mistake. Don’t comment every line or everything<br />you do in the script. If your script is too full of comments, the really<br />important comments can get lost in the maze. Only use comments to label<br />sections and to explain code that is unusual or complicated, not code that is<br />obvious. For instance, the previous comment, documenting the echo statement,<br />is not a useful comment in most cases. It’s obvious what the code is<br />doing; a comment isn’t needed.<br />Be careful that you don’t get your comments mixed together. For instance, if<br />you nest one comment section inside another, PHP can’t handle it. For<br />instance, a comment such as the following won’t work:<br />/* This is the first comment.<br />/* This is the comment nested inside */<br />*/<br />49 Chapter 3: Creating Your First PHP Script<br />PHP looks at the opening /* of the first comment and ignores everything until<br />it comes to the first */. It ignores the second /* because it considers it part of<br />a comment. PHP considers the comment ended after the first */ and outputs<br />an error message when it comes to the second */. PHP doesn’t recognize the<br />second */ as closing a comment because it isn’t in comment mode.<br />50 Part I: Say Hello to the PHP Scripting Language<br />Part II<br />Variables and Data<br />In this part . . .<br />In this part, I describe the use of variables in PHP. I<br />explain how to create and use them. I describe the<br />types of data that can be stored in variables and how to<br />store these different types. I also show you how to store<br />related data in complex variables called arrays.<br />Chapter 4<br />Using Variables in PHP Scripts<br />In This Chapter<br /> Naming variables<br /> Assigning values to variables<br /> Removing variables<br /> Using constants<br /> Handling errors<br />Variables are containers that hold information. First, you give a variable a<br />name, and then you can store information in it. For example, you could<br />name a variable $age and store the number 21 in it. After you store information<br />in a variable, you can use that variable later in the script.<br />When using PHP on the Web, variables are often used to store the information<br />that users type into an HTML form, such as their names. You can then<br />use the variable later in the script, perhaps to personalize a Web page by displaying<br />the user’s name, as in, for example, Welcome Sam Smith.<br />In this chapter, you find out how to create variables, name them, and store<br />information in them. You also discover how to handle errors.<br />Naming Variables<br />Variable names or identifiers should be very descriptive. I have seen scripts<br />where all the variables were named $var1, $var1, $var2, and so on. It may<br />seem straightforward to name variables like this, but two years from now<br />when you come back to the script, it will take forever to figure out what<br />information is in each variable. PHP won’t care or get confused, but humans<br />trying to follow the script will have a hard time. Make your scripts much<br />easier to understand by using descriptive variable names like $firstName,<br />$directory_name, or $DateOfBirth.<br />The rules for variable names are as follows:<br /> All variable names start with a dollar sign ($). This tells PHP that it is a<br />variable name.<br /> Variable names can be any length.<br /> Variable names can include letters, numbers, and underscores only.<br /> Variable names must begin with a letter or an underscore. They<br />cannot begin with a number.<br /> Uppercase and lowercase letters are not the same. $favoritecity<br />and $Favoritecity are not the same variable. If you store information<br />in $FavoriteCity, you can’t retrieve that information later in the script<br />by using the variable name $favoriteCity.<br />The following are valid variable names:<br />$_name<br />$first_name<br />$name3<br />$name_3<br />The following variable names cause error messages:<br />$3name<br />$name?<br />$first+name<br />$first.name<br />The first name is invalid because it doesn’t begin with a letter or an underscore,<br />as required. The three remaining names are invalid because they contain<br />characters other than numbers, letters, and underscores.<br />Assigning variable names is a matter of personal style. Creating descriptive<br />variable names by connecting words with an underscore or by using uppercase<br />letters to denote the beginning of new words (often called camel caps)<br />are the two most common variable naming styles, as shown here:<br />$first_name<br />$firstName<br />Naming your variables by using one of these two common styles makes it<br />easier for other programmers to read your scripts. It’s also common to start<br />the name with a lowercase letter. The most important factor in naming variables,<br />however, is to be consistent. Pick a style and use it throughout the<br />entire script.<br />54 Part II: Variables and Data<br />Assigning and Displaying<br />Variable Values<br />Variables can hold either numbers or strings of characters. A variable can<br />exist or not exist and can hold information or not hold information; these are<br />two separate ideas. Even if a variable doesn’t currently contain any information,<br />it still can exist, just as a drawer exists even when it is empty. Of course,<br />if a variable contains information, it has to exist.<br />The following sections discuss how to create variables, and how to assign<br />and display their values.<br />Creating variables<br />Storing information in a variable creates it.<br />To store information in a variable, you use a single equal sign (=). For example,<br />the following four PHP statements assign information to variables:<br />$age = 21;<br />$price = 20.52;<br />$temperature = -5;<br />$name = “Clark Kent”;<br />In these examples, notice that the numbers are not enclosed in quotes, but<br />the name, which is a string of characters, is. The quotes tell PHP that the<br />characters are a string, handled by PHP as a unit. Without the quotes, PHP<br />doesn’t know the characters are a string and won’t handle them correctly.<br />The different types of data and their uses are discussed in detail in Chapter 5.<br />Whenever you put information into a variable that did not previously exist,<br />you create that variable. For example, suppose you use the following PHP<br />statements at the top of your script:<br />$color = “blue”;<br />$color = “red”;<br />If the first statement is the first time you mention the variable $color, this<br />statement creates the variable and sets it to “blue”. The next statement<br />changes the value of $color to “red”.<br />55 Chapter 4: Using Variables in PHP Scripts<br />You can store the value of one variable in another variable, as shown in the<br />following statements:<br />$name1 = “Sally”;<br />$name2 = “Susan”;<br />$favorite_name = $name2;<br />After these statements are executed, the variable $favorite_name contains<br />the value “Susan”.<br />You can create a variable without storing any information in it. For example,<br />the following statement creates a variable:<br />$city = “”;<br />The variable now exists but does not contain any value. Chapter 5 contains a<br />discussion of the types of data that can be stored in a variable and their uses.<br />Displaying variable values<br />The quickest way to display the value stored in a variable is with the print_r<br />statement. You can output the value of a variable as in the following statements:<br />$today = “Sunday”;<br />print_r($today);<br />The output from the preceding statements is Sunday.<br />You can also display the value by using an echo statement. If you used the<br />following PHP statements<br />$age = 21;<br />echo $age;<br />in a PHP section, the output would be 21.<br />Using an echo statement of the preceding form, with one variable only, provides<br />the same basic output as the print_r statement. However, you can do<br />a lot more with the echo statement. You can output several items and include<br />numbers and strings together. For example, suppose the variable $name has<br />the value Clark Kent. You can include the following line in an HTML file:<br />&lt;p&gt;Welcome &lt;?php echo $name ?&gt;&lt;/p&gt;<br />The output on the Web page is as follows:<br />Welcome Clark Kent<br />56 Part II: Variables and Data<br />If you use a variable that does not exist, you get a warning message. For<br />example, suppose you intend to display $age, but type the following statement<br />by mistake:<br />echo $aeg;<br />You get a notice that looks like the following:<br />Notice: Undefined variable: aeg in c:\testvar.php on line 5<br />The notice points out that you’re using a variable that has not yet been given<br />a value. The notice is helpful in this case because it pinpoints your typo.<br />However, in some cases, writing a statement using a variable that does not<br />exist may not be a typo; you may be using the variable deliberately. For example,<br />you may be using it for a conditional statement (conditional statements<br />are described in Chapter 7.) The script may be running exactly the way you<br />want it to, and your only problem is the notice. You can prevent the notice<br />from being displayed by using @ before the variable name. If you don’t want<br />the notice to display, use the following statement:<br />echo @$aeg;<br />Because the @ turns off the error message and the variable doesn’t exist, the<br />echo statement displays nothing.<br />Don’t turn off any error message that you don’t understand. Be sure you<br />understand the error and are confident that it doesn’t affect your program<br />before you shut it off. The message may mean that your script has a problem<br />that needs to be fixed, such as the typo in the variable name shown in the<br />previous example.<br />Many languages require you to create a variable before you can use it. In<br />these languages, using a variable without creating it first is a fatal error, and<br />the script stops running. PHP, however, doesn’t require this, which may be<br />confusing if you have C or Java experience.<br />Writing Your First Script<br />That Uses Variables<br />In Chapter 3, the Hello World script displays Hello World! on a Web page<br />by using a simple echo statement. In this section, you write a script that also<br />displays Hello World!, but uses a variable in the script. In the script in<br />Chapter 3, the following PHP section is used to display the output:<br />57 Chapter 4: Using Variables in PHP Scripts<br />&lt;?php<br />echo “&lt;p&gt;Hello World!&lt;/p&gt;”;<br />?&gt;<br />The following script is a complete script that contains a PHP section that<br />uses a variable to display Hello World!:<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Hello World Script using Variable&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;?php<br />$salutation = “Hello World!”;<br />echo “&lt;p&gt;$salutation&lt;/p&gt;”;<br />?&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />If you point your browser at this script by typing the URL into the browser,<br />the following output is displayed on the Web page:<br />Hello World!<br />A variable keeps its information for the whole script, not just for a single PHP<br />section. If a variable is set to 5 at the beginning of a script, it will still hold 5<br />at the end of the script (unless, of course, you assign it another value). For<br />example, the following script has two separate PHP sections:<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Hello World Script&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;?php<br />$salutation = “Hello World!”;<br />echo “&lt;p&gt;$salutation&lt;/p&gt;”;<br />?&gt;<br />&lt;p&gt;This is an HTML section&lt;/p&gt;<br />&lt;?php<br />echo “&lt;p&gt;$salutation again&lt;/p&gt;”;<br />?&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />If you point your browser at this script by typing the URL into your browser,<br />the following output displays on the Web page:<br />Hello World!<br />This is an HTML section<br />Hello World! again<br />58 Part II: Variables and Data<br />Discovering More about Output<br />Statements with Variables<br />In Chapter 3, echo statements are shown to have the following format:<br />echo outputitem1,outputitem2,outputitem3,&#8230;<br />You can use a variable for any output item. For example, you could write the<br />following PHP section:<br />&lt;?php<br />$first_name = “Clark”;<br />$last_name = “Kent”;<br />echo “My name is “,$first_name,” “,$last_name;<br />?&gt;<br />And the output of this section is the following:<br />My name is Clark Kent<br />Notice the space included between $first_name and $last_name. If this<br />space isn’t added, the output of the two variables runs together like this:<br />My name is ClarkKent.<br />Statements containing more than one variable must follow certain formatting<br />rules to produce the desired output. Table 4-1 shows some echo statements<br />containing variables and their output. The following variables are set for use<br />in the echo statements in the table:<br />$number = 123;<br />$word1 = “Hello”;<br />$word2 = “World!”;<br />Table 4-1 echo Statements with Variables<br />echo Statement Output<br />echo $number; 123<br />echo $word1,$word2; HelloWorld!<br />echo $word1,” “,$word2; Hello World!<br />echo $word1 $word2; Not valid because no commas separate<br />the variables; results in an error message<br />echo “$word1 $word2 now”; Hello World! now<br />59 Chapter 4: Using Variables in PHP Scripts<br />Notice that in line 2 of the table, there is no space between the two variable<br />names, so there is no space in the output. In line 3, a space is echoed between<br />the two variables.<br />In some echo statements, PHP can’t tell the variable name from the other<br />information around it. In cases where this could be confusing, you need to<br />enclose the variable name in curly braces. For example, suppose you use the<br />following statements:<br />$type = “bird”;<br />echo “Keep the $typecage clean”;<br />Rather than the desired output, you get the following message:<br />Notice: Undefined variable: typecage in testvar.php on line 6<br />After notifying you of the problem, the following output is displayed:<br />Keep the clean<br />To make this code work correctly, you need to use the following echo<br />statement:<br />echo “Keep the {$type}cage clean”;<br />With this statement, the output is the following:<br />Keep the birdcage clean<br />Using Variable Variables<br />PHP allows you to use dynamic variable names, called variable variables. You<br />can name a variable by using the value stored in another variable. That is, one<br />variable contains the name of another variable. For example, suppose you want<br />to construct a variable named $city with the value Los Angeles. You can use<br />the following statement:<br />$name_of_the_variable = “city”;<br />This statement creates a variable that contains the name that you want to<br />give to a variable. Then you use the following statements:<br />$$name_of_the_variable = “Los Angeles”;<br />Note the extra dollar sign ($) character at the beginning of the variable name.<br />This indicates a variable variable. This statement creates a new variable with<br />the name that is the value in $name_of_the_variable, resulting inthe<br />following:<br />60 Part II: Variables and Data<br />$city = “Los Angeles”;<br />The value of $name_of_the_variable does not change.<br />The following example shows how this feature works. In its present form, the<br />script statements may not seem that useful; you may see better ways to program<br />this task. The true value of variable variables becomes clear when they<br />are used with arrays and loops, as discussed in Chapters 6 and 7.<br />Suppose you want to name a series of variables with the names of cities that<br />have values that are the populations of the cities. You can use this code:<br />$Reno= 360000;<br />$Pasadena = 138000;<br />$cityname = “Reno”;<br />echo “The size of $cityname is ${$cityname}”;<br />$cityname = “Pasadena”;<br />echo “The size of $cityname is ${$cityname}”;<br />The output from this code is:<br />The size of Reno is 360000<br />The size of Pasadena is 138000<br />Notice that you need to use curly braces around the variable name in the<br />echo statement so that PHP knows where the variable name is. If you use the<br />statement without the curly braces, the output is as follows:<br />The size of Reno is $Reno<br />Without the curly braces in $$cityname, PHP converts $cityname to its<br />value and puts the extra $ in front of it, as part of the preceding string.<br />Removing Variables<br />You can also remove information from a variable. You can use the following<br />statement:<br />$age = __;<br />This takes the information out of the variable $age. It now has no value. This<br />does not mean that $age is set to 0. It means that $age is not storing any<br />information. Technically, it means that $age is storing a string of zero characters.<br />If you echo it, you get no error message or notice; it just echoes nothing,<br />a blank.<br />61 Chapter 4: Using Variables in PHP Scripts<br />You can go even further and uncreate the variable by using this statement:<br />unset($age);<br />After this statement, the variable $age no longer exists. If you try to echo it,<br />you get an “undefined variable” notice. You can unset more than one variable<br />at once, as follows:<br />unset($age,$name,$address);<br />Working with Constants<br />Constants are similar to variables. Constants are given names, and values are<br />stored in them. However, constants are constant; they can’t be changed by<br />the script. After you set the value for a constant, it stays the same. If you use<br />a constant for weather and set it to sunny, it can’t be changed. Wouldn’t that<br />be grand — only sunny days from now on?<br />Creating constants<br />Constants are set by using the define statement. The general format is as<br />follows:<br />define(“constantname”,”constantvalue”);<br />For example, to set a constant with the weather, use the following statement:<br />define(“WEATHER”,”Sunny”);<br />This statement creates a constant called WEATHER and sets its value to<br />“Sunny”.<br />When naming constants, use descriptive names, as you do for variables.<br />However, unlike variables, constant names do not begin with a dollar sign ($).<br />By convention, constants are given names that are all uppercase so you can<br />see easily that they’re constants. However, PHP accepts lowercase letters<br />without complaint.<br />You can store either a string or a number in a constant. The following statement,<br />which defines a constant named INTEREST and assigns to it the value<br />.01, is perfectly okay with PHP:<br />define (“INTEREST”,.01);<br />62 Part II: Variables and Data<br />Constants should not be given names that are keywords for PHP. Keywords are<br />words that have meaning for PHP, such as echo, and they can’t be used as constants<br />because PHP treats them as the PHP feature of the same name. PHP will<br />let you define a constant ECHO without giving an error message, but it will have<br />a problem when you try to use the constant. For example, if you use the following<br />statement:<br />echo ECHO;<br />PHP gets confused and displays an error message. It sees the constant as the<br />beginning of another echo statement, but it can’t find all the things it needs<br />to complete the first echo statement.<br />Some PHP keywords include the following:<br />63 Chapter 4: Using Variables in PHP Scripts<br />and<br />as<br />break<br />case<br />class<br />const<br />continue<br />declare<br />default<br />die<br />do<br />echo<br />else<br />empty<br />eval<br />exit<br />for<br />foreach<br />function<br />global<br />if<br />include<br />list<br />new<br />or<br />print<br />require<br />return<br />switch<br />use<br />var<br />while<br />If you’re baffled by some code that looks perfectly okay but refuses to work<br />correctly, even after numerous changes, try changing the name of a constant.<br />It’s possible that you are using an obscure keyword for your constant, and<br />that’s causing your problem. This doesn’t happen often, but it’s possible.<br />Although you can use keywords for variable names, because the beginning $<br />tells PHP the keyword is a variable name, you probably shouldn’t. It causes<br />too much confusion for the humans involved.<br />Understanding when to use constants<br />If you know the value of something won’t change during the script, use a constant.<br />Using a constant allows you to use a descriptive name, making the<br />script clearer. For example, PRODUCT_COST is much clearer than 20.50.<br />Using a constant allows you set the value once at the beginning of the script.<br />If this value ever needs to be changed, using constants allows you to change<br />it in only one place, instead of finding and changing the value in 20 different<br />places throughout the script. One change is better than 20. It’s less work and<br />lessens the likelihood of missing a place that needed to be changed, leading<br />to unknown and unseen havoc.<br />Using a constant ensures that the value won’t be changed accidentally somewhere<br />in the script, leading to the wrong value being used in statements later<br />in the script.<br />Suppose you have a script that must change money from one currency to<br />another by multiplying the dollar amount by the exchange rate. For example,<br />if the exchange rate from U.S. to Canadian dollars is 1.52, you can write the<br />following code:<br />&lt;?php<br />$US_dollars = 20.00;<br />$CA_dollars = $US_dollars * 1.52;<br />?&gt;<br />Now, suppose your script contains 40,000 lines of code and you need to convert<br />U.S. dollars to Canadian dollars in 50 different places in the script. So you use<br />the preceding code in 50 different places. Then you realize that the exchange<br />rate is likely to change every week, so you would need to go through this script<br />every week and change 1.52 to something else, manually, in 50 different places.<br />That’s a lot of work.<br />A better way to handle this is to put the exchange rate in a variable so you<br />could change it only in one place. You change your script to the following:<br />&lt;?php<br />$rate = 1.52;<br />$US_dollars = 20.00;<br />$CA_dollars = $US_dollars * $rate;<br />?&gt;<br />You set $rate at the beginning of the script. Then you can use the two lines<br />that convert the currency in all 50 parts of the script. This is clearly a better<br />option. When the rate changes, you need to change the rate in only one<br />place. For example, if the exchange rate changes to 1.53 next week, you just<br />change the first line of the script to the following:<br />$rate = 1.53;<br />This would work. However, $rate is not a very descriptive name. Remember<br />that your script is 40,000 lines of code and the 2 lines of code that convert<br />currency are used in 50 different places. Suppose somewhere in the middle of<br />64 Part II: Variables and Data<br />your script you need to add some code to compute interest. Suppose you<br />accidentally use the following code somewhere in the middle of your script:<br />$interest_rate = 20;<br />$rate = $interest_rate-1;<br />$amount = $principal * $rate;<br />All the places after this code will have a different value for rate; the 1.52 that<br />you set at the beginning of your script will be replaced by the 19 set by this<br />code. You can guard against this by using more descriptive variable names.<br />Or an even better option is to use a constant, as in the following script:<br />&lt;?php<br />define(“RATE”,1.52);<br />$US_dollars = 20;<br />$CA_dollars = $US_dollars * RATE;<br />?&gt;<br />Now you are using a constant, RATE, that can’t be changed in the script. If<br />you try to add the line<br />RATE = 20;<br />in the middle of your script, PHP won’t allow it. So, you won’t make the mistake<br />that you made with the variable.<br />Next week when the exchange rate changes to 1.53, you just edit your script<br />as follows:<br />&lt;?php<br />define(“RATE”,1.53);<br />$US_dollars = 20;<br />$CA_dollars = $US_dollars * RATE;<br />?&gt;<br />Of course, this would be even better if you used a more descriptive name,<br />such as the following:<br />define(“US_TO_CA”,1.52);<br />Keep in mind that mistakes that seem impossible to make when you’re looking<br />at a ten-line script, become entirely possible when you think in terms of<br />scripts with thousands of lines of code, especially scripts with more than one<br />programmer involved.<br />If you know the value of something won’t change during the script, use a<br />constant. If you need to manipulate the value somewhere in the script, use<br />a variable.<br />65 Chapter 4: Using Variables in PHP Scripts<br />Displaying constants<br />You can determine the value of a constant by using print_r as follows:<br />print_r(US_TO_CA);<br />You can also use a constant in an echo statement:<br />echo US_TO_CA;<br />When you echo a constant, you can’t enclose it in quotes. If you do, it echoes<br />the constant name rather than the value. You can echo the constant as shown<br />in the preceding example, or you can enclose it with parentheses. You can<br />build more complicated output statements by using commas, as in the following<br />example:<br />echo “The Canadian exchange rate is $”,US_TO_CA;<br />The output from this statement is the following:<br />The Canadian exchange rate is $1.52.<br />Notice that the dollar sign is inside the quoted string in the first output<br />string, not in the second output item as part of the constant name.<br />Utilizing built-in PHP constants<br />PHP has many built-in constants that you can use in your scripts. For example,<br />the constant _ _LINE_ _ has a value that is the line number where it is<br />used, and _ _FILE_ _ contains the name of the file in which it is used. (These<br />constants begin with two underscores and end with two underscores.) For<br />example, you can use the following statement:<br />echo _ _FILE_ _;<br />The output looks similar to the following:<br />c:\program files\apache group\apache\htdocs\testvar2.php<br />PHP has many other built-in constants. For example, E_ALL and E_ERROR are<br />constants you can use to affect how PHP handles errors. These constants are<br />explained in the next section.<br />66 Part II: Variables and Data<br />Handling Error Messages<br />PHP tries to be helpful when problems arise by providing error messages. It<br />provides the following types of messages:<br /> Error message: You receive this message when the script has a problem<br />that prevents it from running. The script displays an error message and<br />stops running. The message contains as much information as possible to<br />help you identify the problem. The following is a common error message:<br />Parse error: parse error in c:\test.php on line 6<br />Often, you receive this error message because you’ve forgotten a semicolon,<br />a parenthesis, or a curly brace.<br /> Warning message: You receive a warning message when the script sees<br />a problem but the problem does not prevent the script from running.<br />Warning messages do not mean the script can’t run; they indicate that<br />PHP believes something is probably wrong. You should identify the<br />source of the warning and then decide whether it needs to be fixed. It<br />usually does. For example, you see the following message if you don’t<br />include a variable name in the print_r statement — print_r() rather<br />than print_r($varname).<br />Warning: print_r() expects at least 1 parameter, 0 given<br />in d: test1.php on line 9<br />Because this is a warning, not an error, the script continues to execute<br />the statements after the print_r statement. However, a warning usually<br />indicates a more serious problem than a notice. In this case, you need to<br />fix the problem.<br /> Notice: You receive a notice when PHP sees a condition that may be an<br />error or may be perfectly okay. One common condition that produces a<br />notice is echoing variables that don’t exist. Here’s an example of what<br />you might see in that instance:<br />Notice: Undefined variable: age in testing.php on line 9<br />Error messages, warning messages, and notices all indicate the filename causing<br />the problem and the line number where the problem was encountered.<br />The types of error messages that are displayed depend on the error level that<br />PHP is set to. You need to see all the error messages, but you may not want<br />to see all the warnings and notices. (Often the only problem with a notice is<br />the unsightly notice; the code is working correctly.) Or, you may want warning<br />messages and notices displayed during development but not after customers<br />are using the application. Or, you may want to send all the error messages to<br />a log file, rather than have them output for users to see.<br />67 Chapter 4: Using Variables in PHP Scripts<br />The next few sections tackle the subject of setting PHP to give you the type of<br />error messages that you want.<br />Changing the error level for your Web site<br />The error level for your Web site is defined in the php.ini file. You can<br />change the error level if you are the PHP administrator and have access to<br />the php.ini file. If you are not the administrator (which will be the case if,<br />for example, you are using a Web hosting company), you can change the<br />error level for each script, as described in the next section. (See Appendix A<br />for more on the php.ini file.)<br />To see what the current error level is, open php.ini in an editor and look for<br />a line similar to the following:<br />error_reporting = E_ALL; display all errors, warnings and<br />notices<br />This statement causes all errors, warnings, and notices to be displayed. This<br />setting is useful when you’re developing the script. However, when you<br />release the script for users, you probably don’t want notices displayed.<br />In the preceding example, notice that there is a semicolon (;) after E_ALL but<br />not at the beginning of the line. The semicolon is the character that indicates<br />a comment in the php.ini file. Therefore, the text on the line after the semicolon<br />is just a comment, not part of the statement. If there were a semicolon<br />at the beginning of the line, the entire line would be a comment, and the<br />statement would not be in effect.<br />When you look in your php.ini file, you will probably find several statements<br />like the preceding line, except with semicolons at the beginning of the lines.<br />These statements are included as examples, not as statements that execute.<br />Look for the statement without a semicolon in front of it to see which statement<br />is currently active.<br />E_ALL is a built-in PHP constant that refers to all errors, warnings, and<br />notices. E_NOTICE is a built-in constant representing notices. You can use<br />these two constants in the following statement:<br />error_reporting = E_ALL &amp; ~E_NOTICE<br />E_ALL tells PHP to display all errors, warnings, and notices. However, the<br />second term ~E_NOTICE tells PHP not to display notices. The result is that<br />only errors and warnings are displayed. This method of specifying the errors<br />to be displayed is shorter than listing all the types of errors that you want to<br />display.<br />68 Part II: Variables and Data<br />The two statements shown in this section are used most often. You can use<br />other constants to specify error levels, but E_ALL and E_NOTICE are usually<br />sufficient for most scripts. You can find a listing of all the constants in the<br />php.ini file. For a complete discussion of error levels, check out the PHP<br />online manual.<br />You can stop error reporting all together. You may not want users to see any<br />of the PHP-generated error or warning messages because they may contain<br />compromising information. Usually if you do this, you want to save error<br />messages in a log instead, as described later in this chapter in the section,<br />“Sending messages to a log.”<br />To turn off error reporting, find the line that says display_errors = On in<br />php.ini and change On to Off.<br />You need to restart your Web server before any changes you make in<br />php.ini will go into effect.<br />Changing the error level for a script<br />If you want to set the error level for a particular script, add a statement with<br />the following format to the beginning of the script:<br />error_reporting(OPTIONS);<br />The OPTIONS in the statement are the built-in constants discussed in the preceding<br />section. For example, you can have all errors, warnings, and notices<br />displayed in the script by adding the following statement:<br />error_reporting(E_ALL);<br />Suppose the setting in php.ini is set to E_ALL. You may be satisfied with<br />that level while developing your scripts, but then want to stop displaying<br />notices when users start running your scripts. To override the php.ini setting,<br />you can add the following statement to the scripts after they are finetuned<br />and ready to go:<br />error_reporting(E_ALL &amp; ~E_NOTICE);<br />You can set error reporting so that no messages are displayed by using the<br />following statement:<br />error_reporting(0);<br />69 Chapter 4: Using Variables in PHP Scripts<br />Sometimes you want to turn error and warning messages off when your<br />scripts are complete and being used by the world. You may not want users to<br />see the error messages that PHP sends because the information in the PHP<br />messages can represent a security issue, but you may want to see any error<br />messages from PHP yourself. You can turn error reporting off by using a setting<br />of zero, but log the error messages to a file at the same time. Users don’t<br />see the messages, but you can look at them. Sending messages to a log is<br />described in the next section.<br />Sending messages to a log<br />You can send the errors and warnings from PHP to a log file. You may want to<br />have a permanent record of errors as well as display them, or you may want<br />to send the errors to a file rather than display them for the world to see.<br />You can set up an error message log for the whole site by using settings in<br />the php.ini file, if you have access to it. Open php.ini and find the following<br />line:<br />log_errors = Off<br />You need to change Off to On. You also need to tell PHP where to send the<br />error messages. To do this, find the following line:<br />;error_log = filename<br />Now remove the semicolon from the beginning of the line. This changes the<br />line from a comment to a statement. Change filename to the path to the file<br />into which you want the messages saved. For example, you could use the following<br />statement:<br />error_log = c:\temp\php_error_log<br />The directory (often called folder in Windows) must exist. For this statement,<br />you must create the directory c:\temp before the error messages can be<br />logged there. You don’t need to create the file; PHP can create the file as long<br />as it can find the directory.<br />You need to restart your Web server before any changes you make in<br />php.ini will go into effect.<br />Advanced error handling<br />This section describes advanced error handling. Newbies do not need to read<br />this section. Come back and read this section after you have some experience<br />with the programming techniques described in the rest of the book.<br />70 Part II: Variables and Data<br />The standard PHP errors and error messages may not be sufficient for your<br />needs. For example, you may know something is an error in your script,<br />although PHP sees nothing wrong with the problem. For example, you may<br />be writing a script to design a house. In such a case, if $height_of_door is<br />larger than $height_of_house, you know that something is wrong. You know<br />this, but PHP doesn’t. PHP would not recognize this as an error condition. To<br />get PHP to check for this error in the script, you could write the following<br />statement:<br />If ($height_of_door &gt; $height_of_house)<br />{<br />trigger_error(“Impossible condition”,E_USER_ERROR);<br />}<br />Using if statements is explained in detail in Chapter 7.<br />The E_USER_ERROR in the statement tells PHP that the condition is an error.<br />The string “Impossible condition” is the message to be displayed when the<br />error is encountered. If the condition is true, the following message is displayed:<br />Fatal error: Impossible condition in d:\testerr.php on line 9<br />The script stops at this point because you told PHP that it was an error,<br />rather than a warning or a notice. You can use E_USER_WARNING or<br />E_USER_NOTICE, rather than E_USER_ERROR, to have PHP treat the condition<br />as a warning or notice.<br />If you want to handle the error in your own way, instead of using PHP standard<br />error procedures, you can write your own statements to perform actions, such<br />as send a message, log a message, send an e-mail, or stop the script. For example,<br />you could simply echo an error message to the user and stop the script, as<br />follows:<br />If ($height_of_door &gt; $height_of_house)<br />{<br />echo “This is impossible&lt;br&gt;”;<br />exit();<br />}<br />If $height_of_door is larger than $height_of_house, the message is<br />echoed, and exit() stops the script. No more statements are executed.<br />You could also send a message to a PHP error log when this condition occurs<br />by using the following type of statement:<br />error_log(message,3,logfilename);<br />For example, you could use the following if block:<br />71 Chapter 4: Using Variables in PHP Scripts<br />If ($height_of_door &gt; $height_of_house)<br />{<br />error_log(“The door is taller than the<br />house”,3,”/temp/err_log”);<br />exit();<br />}<br />After this statement, if $height_of_door is larger than $height_of_house,<br />the message “The door is taller than the house” is stored in the log<br />file /temp/err_log. The 3 in the statement tells PHP to store the message in<br />the specified log file. The directory /temp must exist, but PHP will create the<br />file if it doesn’t already exist.<br />Alternatively, you might want to send yourself an e-mail message when the<br />error occurs. The error_log statement can be used for this purpose as well<br />as for logging an error message. The 1 in the following error_log statement<br />tells PHP to send the message as e-mail to the specified e-mail address:<br />error_log(“The door is taller than the<br />house”,1,”me@mymail.com”);<br />This statement assumes that e-mail can be accessed from PHP. See the discussion<br />of PHP and e-mail in Chapter 13.<br />On the other hand, you may be willing to accept PHP’s definition of an error,<br />but want it to behave differently when it encounters an error. You could have<br />procedures you want performed in the event of an error. You may want PHP<br />to display a message written by you or to execute statements written by you.<br />For example, you may want to be informed by e-mail of error messages, or<br />you may want certain files opened or closed before the script stops.<br />You can write your own code to handle errors and instruct PHP to use your<br />code whenever it encounters an error. To do this, you write your own errorhandling<br />code and save it as a function, which is a piece of code you write<br />and call repeatedly whenever you need it. (Instructions for writing functions<br />are provided in Chapter 8.) You can tell PHP to use your function rather than<br />its own procedure for error handling by using the following statement:<br />set_error_handler(functionname);<br />For example, you could use the following:<br />set_error_handler(my_error_handler);<br />Further instructions for writing my_error_handler are provided in Chapter 8<br />where functions are discussed.<br />Another method for handling errors recognized by PHP is to use the die<br />statement to display a message when a function fails. The die statement is<br />discussed in detail in Chapter 8 along with the discussion of functions.<br />72 Part II: Variables and Data<br />Chapter 5<br />Working with Data<br />In This Chapter<br /> Understanding data types<br /> Performing arithmetic<br /> Manipulating character strings<br /> Using dates and times<br />Variables can store data of different types, and different types of data can<br />do different things. For example, you can add variables whose values are<br />numbers (1 + 2), but adding variables whose values are characters (a + b)<br />doesn’t make much sense. In this chapter, you find out what data types PHP<br />can handle and how you can use them.<br />Understanding Data Types<br />You can store the following simple types of data in PHP variables:<br /> Integer: A whole number (no fractions), such as –43, 0, 1, 27, or 5438.<br />The range of integers that is allowed varies, depending on your operating<br />system, but in general, you can usually use any number from<br />–2 billion up to +2 billion.<br /> Floating point number: A number (usually not a whole number) that<br />includes decimal places, such as 5.24 or 123.456789. This is often called<br />a real number or a float.<br /> Character string: A series of single characters, such as hello. There is<br />no practical limit on the length of a string.<br /> Boolean: A TRUE or FALSE value. See the nearby sidebar for more<br />information.<br />Assigning data types<br />Most other languages require that you initialize the variable before using<br />it, specifying what type of data it can hold, but PHP is more informal. You<br />don’t need to tell PHP which data type is in a variable. PHP evaluates the<br />data when you assign it to the variable and then stores it as the appropriate<br />type. Generally, this is helpful. PHP guesses the data type pretty accurately.<br />PHP also converts data when it needs to be converted. For example, if you<br />have the following statements, PHP converts the data types with no problem:<br />$firstNumber = 1; # PHP stores it as an integer<br />$secondNumber = 1.1; # PHP stores it as a float<br />$sum = $firstNumber + $secondNumber;<br />Technically, the third statement is not possible because the data to be added<br />are different types. However, PHP converts the integer to a float so that the<br />addition proceeds smoothly. This happens automatically and invisibly and is<br />very helpful.<br />Type casting<br />On a rare occasion, PHP guesses badly when it stores the data. You might<br />need to do something with a variable, and PHP won’t let you because the<br />74 Part II: Variables and Data<br />True or false? Boolean values<br />Boolean data types represent two possible<br />states — TRUE or FALSE. Boolean values are<br />used mainly to compare conditions for use in<br />conditional statements. For example, PHP evaluates<br />an expression, such as $a &gt; $b, and the<br />outcome is either TRUE or FALSE.<br />PHP considers the following values FALSE :<br /> The string FALSE (can be upper- or<br />lowercase)<br /> The integer 0<br /> The float 0.0<br /> An empty string<br /> The one-character string 0<br /> The constant NULL<br />Any other values in a Boolean variable are considered<br />TRUE. If you echo a Boolean variable,<br />the value FALSE displays as a blank string; the<br />value TRUE echoes as a 1. Functions often<br />return a Boolean variable that you can test to<br />see whether the function succeeded or failed.<br />For more information on using Boolean variables<br />with functions, check out Chapter 8.<br />data is the wrong type. In such a case, you can specify how you want PHP to<br />store the data, rather than let PHP decide for itself. This is called type casting.<br />To specify a particular type, use a statement like one of the following:<br />$newint = (int) $var1;<br />$newfloat = (float) $var1;<br />$newstring = (string) $var1;<br />The value in the variable on the right side of the equal sign is stored in the<br />variable on the left side as the specified type. So the value in $var1 is stored<br />in $newint as an integer, as specified by (int).<br />Be careful when doing type casts. Sometimes you can get unexpected results.<br />For example, when you cast a float into an integer, it loses its decimal places.<br />To do this, PHP rounds the float toward 0. For example, if $number = 1.8<br />and you cast it into an integer — $newnumber = (int) $number —<br />$newnumber will equal 1.<br />You can find out the data type of a variable by using a statement like the<br />following:<br />var_dump($myvariable);<br />For example, the following statement checks the data type of $checkvar:<br />var_dump($checkvar);<br />The output from this statement is int(27), which tells you that $checkvar<br />contains the integer 27.<br />Working with Numbers<br />The data types float and integer are both numbers. You store them in variables<br />as follows:<br />$intvar = 3;<br />$floatvar = 9.3;<br />PHP automatically stores the values as the correct data type.<br />Performing mathematical operations<br />PHP allows you to do mathematical operations on numbers. You indicate<br />mathematical operations by using two numbers and a mathematical operator.<br />75 Chapter 5: Working with Data<br />For example, one operator is the plus (+) sign, so you can indicate a mathematical<br />operation like this:<br />1 + 2<br />You can also do math with variables:<br />$var1 + $var2;<br />If you plan to use numbers in mathematical operations, don’t enclose them in<br />quotes when assigning them to variables. Using quotes sets the numbers as<br />character strings, and you can’t perform mathematical operations on character<br />strings. However, PHP, as opposed to most other languages, will automatically<br />convert strings to numbers when it needs to. For example, suppose you<br />have the following statements:<br />$var1 = “1”;<br />$var2 = 2;<br />$total = $var1 + $var2;<br />Technically, you can’t add these two numbers together because $var1 is a<br />character string. However, PHP automatically converts the string 1 to a<br />number 1 when it gets to the third statement and then adds the numbers.<br />If you use the following statements, PHP also converts the string so it can add<br />the numbers, but the results are not as obvious:<br />$var1 = “x”;<br />$var2 = 2;<br />$total = $var1 + $var2;<br />Because x is not a number that PHP can convert, it uses 0 in the addition. The<br />result is that $total equals 2. In most cases, this conversion is not what you<br />want. The automatic conversion feature is useful, and saves some typing, but<br />be careful when depending on it. Sometimes you don’t get the results you<br />expect, as shown in the previous example.<br />PHP can also guess wrong because it doesn’t understand certain human notation.<br />For example, the following statements cause PHP to get it wrong:<br />$var1 = “2,000”;<br />$var2 = 2;<br />$total = $var1 + $var2;<br />76 Part II: Variables and Data<br />Although people understand what commas mean in numbers, PHP does not.<br />PHP thinks 2,000 ends at the comma. After these statements are executed,<br />$total equals 4.<br />Table 5-1 shows the mathematical operators that you can use.<br />Table 5-1 Mathematical Operators<br />Operator Description<br />+ Adds two numbers together.<br />- Subtracts the second number from the first number.<br />* Multiplies two numbers together.<br />/ Divides the first number by the second number.<br />% Finds the remainder when the first number is divided by the second<br />number. This is called modulus. For example, in $a = 13 % 4, $a<br />is set to 1.<br />Understanding the order of operations<br />You can do several mathematical operations at once. For example, the following<br />statement performs three operations:<br />$total = 1 + 2 * 3 + 1;<br />The order in which the arithmetic is performed is important. You can get different<br />results depending on which operation is performed first. PHP does<br />multiplication and division first, and then addition and subtraction. If other<br />considerations are equal, PHP goes from left to right. Consequently, the preceding<br />statement sets $total to 8, in the following order:<br />$total = 1 + 2 * 3 + 1 #first, it does the multiplication<br />$total = 1 + 6 + 1 #next, it does the leftmost addition<br />$total = 7 + 1 #next, the remaining addition<br />$total = 8<br />You can change the order in which the arithmetic is performed by using<br />parentheses. The arithmetic inside the parentheses is performed first. For<br />example, you can write the previous statement with parentheses, like this:<br />$total = (1 + 2) * 3 + 1;<br />77 Chapter 5: Working with Data<br />This statement sets $total to 10, in the following order:<br />$total = (1 + 2) * 3 + 1 #first, the math in the parentheses<br />$total = 3 * 3 + 1 #next, the multiplication<br />$result = 9 + 1 #next, the addition<br />$result = 10<br />The general order of operations is in force inside of parentheses when there<br />is more than one operation, such as (3 + 2 * 5). In this example, the multiplication<br />is performed first. You can use parentheses inside of parentheses to<br />change that order as well.<br />On the better-safe-than-sorry principle, it’s best to use parentheses whenever<br />more than one answer is possible.<br />Incrementing and decrementing<br />PHP provides a shortcut for adding 1 to a variable. If you want to add 1 to a<br />variable, you can use a statement like the following:<br />$counter=$counter+1;<br />PHP also lets you write a shorter statement that does the same thing:<br />$counter++;<br />For example, you could use the following statements:<br />$counter=0;<br />$counter++;<br />echo $counter;<br />This echo statement outputs 1, because ++ adds 1 to the current value of<br />$counter. You can also subtract 1 by using the following statement:<br />$counter&#8211;;<br />Another shortcut for adding a number to an existing variable is +=1, which<br />adds 1 to the variable. You can add any number to a variable by using this<br />shortcut. You can also subtract, multiply, or divide by using a similar shortcut.<br />The following are some valid statements using this shorter format:<br />$counter+=2;<br />$counter-=3;<br />$counter*=2;<br />$counter/=3;<br />78 Part II: Variables and Data<br />These statements add 2 to $counter, subtract 3 from $counter, multiply<br />$counter by 2, and divide $counter by 3, respectively.<br />Using built-in higher-math functions<br />PHP provides functions to perform more complicated math for you. (Functions<br />are described further in Chapter 8.) For example, if you need to compute a<br />square root, you don’t have to write code that does all the math. PHP has<br />already written this code for you. You can just use a statement like one of<br />these:<br />$rootvar = sqrt(91);<br />$rootvar = sqrt($number);<br />The first statement takes the square root of a number, and the second statement<br />takes the square root of a variable’s value.<br />You can use a statement like the following to round up to the next integer:<br />$upnumber = ceil(27.63);<br />The result is 28. You can also round down by using the following format:<br />$downnumber = floor(27.63);<br />The result of this segment is 27.<br />PHP offers many math functions, including functions for simple math, such as<br />maximum, minimum, and random numbers; and functions for advanced math,<br />such as sine, tangent, and converting to binary or octal numbers. To find a particular<br />mathematical function, see Appendix B.<br />Formatting numbers for output<br />Often you want to display a number in a familiar format, such as with commas<br />dividing the thousands or formatted as dollar amounts with two decimal places.<br />But PHP stores and displays numbers in the most efficient format. If the number<br />is 10.00, it is displayed as 10. Therefore, you need to tell PHP how you want the<br />number displayed.<br />One PHP statement that formats numbers is the number_format statement,<br />which has the following general form:<br />number_format(number,decimals,”decimalsep”,”thousandsep”)<br />79 Chapter 5: Working with Data<br />In this format, each piece of input has a meaning:<br /> number is the number to be formatted. This must always be included.<br /> decimals is the number of decimal places. If decimals is not included,<br />the number of decimal places is 0 by default, and number is rounded<br />to the closest integer. If you are going to include thousandsep and<br />decimalsep, you must include decimals.<br /> decimalsep is the character used to separate the decimal places. The<br />default is a decimal point. If you include this, you must also include<br />thousandsep.<br /> thousandsep is the character used to separate the number into thousands.<br />The default is a comma. If you include this parameter, you must<br />also include decimalsep.<br />Table 5-2 shows some number_format statements and their output.<br />Table 5-2 number_format Statements<br />$number Format Output<br />12321 number_format($number) 12,321<br />12321.66 number_format($number,2) 12,321.66<br />12321.66 number_format($number) 12,322<br />12321.6 number_format($number,3) 12,321.600<br />12321 number_format($number,0,”.”,”.”) 12.321<br />12321.66 number_format($number,2,”.”,””) 12321.66<br />After formatting, the number is converted to a string data type, so perform<br />any arithmetic on the number before you format it.<br />For more complicated formatting, PHP provides the statements printf and<br />sprintf:<br /> printf outputs the formatted number directly.<br /> sprintf is used to store the formatted number into a variable.<br />The formatting statements printf and sprintf can be used to format character<br />strings as well as numbers, and to output strings and numbers in the<br />same output statement. For a more complete description of these statements,<br />check out the section “Formatting output strings,” later in this chapter.<br />80 Part II: Variables and Data<br />Working with Character Strings<br />Characters are letters, numbers, and punctuation, and a character string is a<br />series of characters. When a number is used as a character, it is just a stored<br />character, the same as a letter. It can’t be used in arithmetic. For example, a<br />phone number usually is stored as a character string and not a number<br />because it only needs to be stored, not added or multiplied.<br />When you store a character string in a variable, you use double quotes or<br />single quotes to tell PHP where the string begins and ends. For example, the<br />following two statements are the same:<br />$string = _Hello World!_;<br />$string = _Hello World!_;<br />81 Chapter 5: Working with Data<br />Storing really long strings<br />PHP provides a feature called a heredoc that is<br />useful for assigning values to really long strings<br />that span several lines. A heredoc enables you<br />to tell PHP where to start and end reading a<br />string. A heredoc statement has the following<br />format:<br />$varname = &lt;&lt;&lt;ENDSTRING<br />text<br />ENDSTRING;<br />ENDSTRING is any string you want to use. You<br />enclose the text you want stored in the variable<br />$varname by typing ENDSTRING at the beginning<br />and again at the end. When PHP processes<br />the heredoc, it reads the first ENDSTRING and<br />knows to start reading text into $varname. It<br />continues reading text into $varname until it<br />encounters the same ENDSTRING again. At<br />that point, it ends the string.<br />The string created by a heredoc statement<br />evaluates variables and special characters in<br />the same manner as a double-quoted string.<br />(For details on double-quoted strings, see the<br />section, “Comparing single-quoted strings and<br />double-quoted strings,” later in this chapter.)<br />The following statements create a string by<br />using the heredoc method:<br />$distance = 10;<br />$herevariable = &lt;&lt;&lt;ENDOFTEXT<br />The distance between<br />Los Angeles and Pasadena<br />is $distance miles.<br />ENDOFTEXT;<br />echo $herevariable;<br />The output of the echo statement is as follows:<br />The distance between Los<br />Angeles and Pasadena is 10<br />miles.<br />But be careful. PHP is picky about its ENDSTRINGs.<br />When it first appears, the ENDSTRING<br />(ENDOFTEXT in this example) must<br />occur at the end of the first line, with nothing following<br />it, not even a space. And the ENDSTRING<br />on the last line must occur at the start<br />of the line, with nothing before it, not even a<br />space, and nothing following it other than the<br />semicolon. If these rules are broken, PHP won’t<br />recognize the ending string and will continue<br />looking for it throughout the rest of the script. It<br />will eventually display a parse error showing a<br />line number that is the last line in the script.<br />Using special characters in strings<br />PHP provides some special characters you can use in strings: \n and \t. You<br />can use \n to start a new line in a string, as in the following statements:<br />$string = “Hello \nWorld”;<br />echo $string;<br />The output is broken into two lines:<br />Hello<br />World<br />You can use \t to insert a tab, as in the following statements:<br />$string = “Line 1 \n\tLine 2”;<br />echo $string;<br />The second line of the output is indented:<br />Line 1<br />Line 2<br />Special characters can be used only in strings enclosed with double quotes.<br />In single-quoted strings, special characters have no special meaning; they are<br />output the same way as any other character. The difference between single<br />and double quotes is explained in the next section.<br />Comparing single-quoted strings<br />and double-quoted strings<br />Single-quoted and double-quoted strings are handled differently:<br /> Single-quoted strings are stored literally, with the exception of \’, which<br />is stored as an apostrophe. (For more information about \’, see the next<br />section, “Escaping characters.”)<br /> In double-quoted strings, variables and special characters are evaluated<br />before the string is stored.<br />The following examples show the difference in output produced by single and<br />double quotes.<br />If you enclose a variable in double quotes, PHP uses the value of the variable.<br />However, if you enclose a variable in single quotes, PHP uses the literal variable<br />82 Part II: Variables and Data<br />name. For example, the following statements use both the single and double<br />quote methods with a variable:<br />$name = “Sam”;<br />$output1 = _$name_;<br />$output2 = _$name_;<br />echo $output1;<br />echo $output2;<br />The output of these echo statements is as follows:<br />Sam<br />$name<br />If you use special characters in a string enclosed by double quotes, PHP outputs<br />the string after evaluating the special characters. However, if you enclose<br />the string in single quotes, PHP outputs the special characters as literals. For<br />example, the following statements use both single and double quotes with the<br />new line character \n and the tab character \t:<br />$string1 = “String in \n\tdouble quotes”;<br />$string2 = ‘String in \n\tsingle quotes’;<br />When $string1 is displayed, you get the following:<br />String in<br />double quotes<br />When $string2 is displayed, you get the following:<br />String in \n\tsingle quotes<br />The quotes that enclose the entire string determine the treatment of variables<br />and special characters, even if there are other sets of quotes inside the string.<br />For example, look at the following statements:<br />$number = 10;<br />$string1 = “There are ‘$number’ people in line.”;<br />$string2 = ‘There are “$number” people waiting.’;<br />echo $string1,”\n”;<br />echo $string2;<br />The output is as follows:<br />There are ‘10’ people in line.<br />There are “$number” people waiting.<br />83 Chapter 5: Working with Data<br />You can see that even though $number is enclosed in single quotes in<br />$string1, the double quotes around the entire string cause the output to<br />contain the value of the variable rather than the name of the variable.<br />Similarly, even though $number is enclosed in double quotes in $string2,<br />the single quotes around the entire string cause the output to contain the<br />name of the variable rather than the value of the variable<br />Escaping characters<br />Sometimes you want a character in a double-quoted string to be treated as a<br />literal, not as a special character, even though it has special meaning. For<br />example, you may want to output a dollar sign as a dollar sign, rather than<br />have the dollar sign treated as the first character of a variable name. You can<br />tell PHP to output characters, rather than use their special meaning, by preceding<br />the character with a backslash (\). This is called escaping the character.<br />For example, the following two strings produce the same output:<br />$string = ‘The variable name is $var1’;<br />$string = “The variable name is \$var1”;<br />The output from either string is the following:<br />The variable name is $var1<br />Suppose you want to store a string as follows:<br />$string = _Where is Sally_s house_;<br />echo $string;<br />These statements won’t work because when PHP sees the ‘ (single quote)<br />after Sally, it thinks this is the end of the string. It displays the following:<br />Where is Sally<br />You need to tell PHP to interpret the single quote (‘) as an apostrophe, not as<br />the end of the string. You can do this by using a backslash (\) in front of the<br />single quote. The backslash tells PHP that the single quote does not have any<br />special meaning; it’s just an apostrophe. To display the string correctly, use<br />the following statement:<br />$string = _Where is Sally\_s house_;<br />When you enclose a string in double quotes, you must also use a backslash in<br />front of any double quotes inside the string.<br />84 Part II: Variables and Data<br />Joining strings together<br />You can join strings together, a process called concatenation, by using a dot<br />(.). For example, you can join $string1 and $string2 with the following<br />statements:<br />$string1 = _Hello_;<br />$string2 = _World!_;<br />$stringall = $string1.$string2;<br />echo $stringall;<br />The echo statement outputs one string:<br />HelloWorld!<br />Notice that no space appears between Hello and World!. That’s because no<br />spaces are included in the two strings that are joined. You can add a space<br />between the words by joining three strings together — the two variables and<br />a string that contains a single space — with the following statement rather<br />than the earlier statement:<br />$stringall = $string1._ _.$string2;<br />You can use .= to add characters to an existing string. For example, you can<br />use the following statements, in place of the preceding statements:<br />$stringall = “Hello”;<br />$stringall .= “ World!”;<br />echo $stringall;<br />The echo statement outputs this:<br />Hello World!<br />Manipulating strings<br />PHP provides many built-in functions for manipulating strings. (Functions<br />are discussed in detail in Chapter 8.) Using PHP functions, you can find substrings<br />or characters, replace part of a string with different characters, take a<br />string apart, count the length of a string, and perform many other string<br />manipulations.<br />85 Chapter 5: Working with Data<br />Often you want to remove blank spaces before or after a string. You can<br />remove leading or trailing spaces by using the following statements:<br />$string = trim($string) # removes leading &amp; trailing spaces<br />$string = ltrim($string) # removes leading spaces<br />$string = rtrim($string) # removes trailing spaces<br />PHP can help you split a string into words, which is often handy. The general<br />form of this function is as follows:<br />str_word_count(“string”,format)<br />In this expression, format can be 1, meaning return the words as a numeric<br />array; or 2, meaning return the words as an array where the key is the position<br />of the first character of the word. (Arrays are explained in Chapter 6.) If<br />you don’t include a format, the function returns the number of words. The<br />following examples use str_word_count:<br />$string = “Counting Words”;<br />$numberOfWords = str_word_count($string);<br />$word1 = str_word_count($string,1);<br />$word2 = str_word_count($string,2);<br />After the statements are executed, the following variables exist:<br />$numberOfWords = 2<br />$word1[0] = Counting<br />$word1[1] = Words<br />$word2[0] = Counting<br />$word2[9] = Words<br />Notice that the first word starts at position 0 (not position 1 as you and I<br />might think), and the next word starts at position 9. I explain this more fully<br />in Chapter 6 when I discuss arrays.<br />Some additional useful string manipulation statements are shown in Table 5-3<br />with examples. When looking at the examples, remember that the first position<br />in the string is 0, not 1.<br />86 Part II: Variables and Data<br />Table 5-3<br />String Manipulation<br />Function Format<br />What It Does<br />Example<br />Result<br />str_repeat(“str”,n)<br />Repeat str<br />n<br />times<br />$x=str_repeat(“x”,5);<br />$x=xxxxx<br />str_replace(“a”,”b”,<br />Replace all a<br />$a=”abc abc”;<br />$s=<br />”str”)<br />with b<br />in str<br />$s=str_replace(“b”,”i”,$a);<br />aic aic<br />strchr(“string”,<br />Returns string<br />$str=”aBc abc”;<br />$sub=bc<br />”char”);<br />from char<br />to end<br />$sub=strchr($str,”b”);<br />stristr(“string”,<br />Same as strchr,<br />$str=”aBc abc”;<br />$sub=<br />”char”);<br />except not case sensitive<br />$sub=stristr($str,”b”);<br />Bc abc<br />strlen(“string”)<br />Returns length of string<br />$n=strlen(“hello”);<br />$n=5<br />strpos(“string”,<br />Returns position of first<br />$str=”hello”;<br />$n=2<br />”substr”)<br />substr<br />beginning<br />$n=strpos($str,”ll”);<br />strrchr(“string”,<br />Same as strchr, except<br />$str=”abc abc”;<br />$sub=bc<br />”char”);<br />finds only the last instance of char<br />$sub=strrchr($str,”b”);<br />strrev(“string”)<br />Reverses string<br />$n=strrev(“abcde”);<br />$n=edcba<br />strrpos(“string”,<br />Returns position of last<br />$str=”abc abc”;<br />$n=5<br />”substr”)<br />instance of substr<br />$n=strrpos($str,”bc”);<br />strtolower(“string”)<br />Returns a lowercase version of string<br />$str=strtolower(“YES”);<br />$str=yes<br />(continued)<br />87 Chapter 5: Working with Data<br />Table 5-3<br />(continued)<br />Function Format<br />What It Does<br />Example<br />Result<br />strtoupper(“string”)<br />Returns an uppercase version of string<br />$str=strtoupper(“yes”);<br />$str=YES<br />Replaces all str1<br />with<br />$str=”aa bb cc”;<br />$new=<br />”str1”,”str2”)<br />str2<br />in string<br />$new=strtr($str,”bb”,”xx”);<br />aa xx cc<br />substr(“string”,n1,n2)<br />Returns string<br />$sstr=substr(“hello”,2,4);<br />$sstr=llo<br />between n1<br />and n2<br />substr_count(“str”,<br />Returns the number of<br />$str=”abc ab abc”;<br />$n=2<br />”sub”)<br />occurrences of sub<br />in str<br />$s=”bc”;$n=substr_count($str,$s);<br />substr_replace(“s”,<br />Replace r<br />into s, beginning<br />$s=”abc abc”;<br />$t=<br />”r”,n,l)<br />with n<br />for l<br />characters<br />$t=<br />abxbc<br />substr_replace($s,”x”,2,3);<br />ucfirst(“string”)<br />Changes first letter of<br />$str=”a B c”;<br />$str2=<br />string<br />to uppercase<br />$str2=ucfirst($str);<br />A B c<br />ucwords(“string”)<br />Changes each word of<br />$str=”aa Bb cc”;<br />$str2=<br />string<br />to uppercase<br />$str2=ucwords($str);<br />Aa Bb Cc<br />88 Part II: Variables and Data<br />Formatting output strings<br />The output produced by PHP is always in string format. That is, the output of<br />the echo statement is a string, even if the output statement included a variable<br />containing a number. The following is an output statement:<br />$number = 4;<br />echo “Sally has $number children.”;<br />The output is as follows:<br />Sally has 4 children.<br />The output is a string, even though 4 was a number when it was in the variable<br />named $number. The echo statement outputs 4 as part of a character<br />string.<br />Formatting the output is an important part of scripting. The echo statement<br />allows quite a bit of flexibility in formatting output. In the section, “Formatting<br />numbers for output,” earlier in this chapter, I describe some possibilities for<br />formatting numbers by using the number_format statement. PHP provides<br />additional statements for formatting output strings. The printf and sprintf<br />statements allow you to format strings, numbers, and a mix of both strings<br />and numbers.<br />The general format is as follows:<br />printf(“format”,$varname1,$varname2,. . .);<br />$newvar = sprintf(“format”,$varname1,$varname2,. . .);<br />The printf statement outputs formatted strings; sprintf stores the formatted<br />output in a variable. You can format strings or numbers or both together,<br />including variable values. The information in format gives instructions for<br />the format, and $varname contains the value(s) to be formatted. The following<br />statement is valid:<br />$newvar = sprintf(“Hello World!”);<br />This statement outputs the literal string, as given, because no format is<br />included. The string “Hello World!” is now assigned to the variable $newvar.<br />However, you can mix variables with literals by using the following statements:<br />$nboys = 3;<br />$ngirls = 2;<br />printf(“%s boys and %s girls”,$nboys,$ngirls);<br />89 Chapter 5: Working with Data<br />The %s is a formatting instruction that tells printf to insert the variable<br />value as a string. Thus, the output is: 3 boys and 2 girls. The % character<br />signals printf that a formatting instruction starts here. The formatting<br />instruction has the following format:<br />%pad-width.dectype<br />These are the components of the formatting instructions:<br /> %: Signals the start of the formatting instruction.<br /> pad: A padding character that is used to fill out the string when the value<br />to be formatted is smaller than the width assigned. (See width, later in<br />this list.) If you don’t specify a character, a space is used. pad can be a<br />space, a 0, or any character preceded by a single quote (‘). For example,<br />it is common to pad numbers with 0 — for example, 01 or 0001.<br /> -: A symbol meaning to left-justify the characters. If this is not included,<br />the characters are right-justified.<br /> width: The number of characters to use for the value. If the value doesn’t<br />fill the width, the padding character is used to pad the value. For example,<br />if the width is 5, the padding character is 0, and the value is 1, the output<br />is 00001.<br /> .dec: The number of decimal places to use for a number. This value is<br />preceded by a decimal point.<br /> type: The type of value. Use s (string) for most values. Use f (float) for<br />numbers that you want to format with decimal places.<br />The following are some possible sprintf statements:<br />$money = 30;<br />$pet = “Kitten”;<br />$new = sprintf(“It costs $%03.2f for a %s.\n”,$money,$pet);<br />$new2 = sprintf(“%’.-20s%3.2f”,$pet,$money);<br />echo $new;<br />echo $new2;<br />The output of these statements is<br />It costs $030.00 for a Kitten.<br />Kitten&#8230;&#8230;&#8230;&#8230;.. 30.00<br />Notice that the format for $money is 3.2f (3 digits wide with 2 decimal places)<br />for both $new and $new2, but in $new, it’s padded with a 0. In $new2, the<br />number format is not padded, so there is a space before 30.<br />For $new2, the format for $pet is ‘.-20. The 20 makes the space for $pet<br />20 characters wide. The value Kitten takes up 6 characters. The format characters<br />‘. tell sprintf to pad the space with dots, so that produces 14 dots.<br />90 Part II: Variables and Data<br />The &#8211; format character says to left justify Kitten, so Kitten is on the left side<br />of the space, and the padding comes after Kitten. If the &#8211; is left out, Kitten is<br />right justified by default, which means that Kitten is on the right side of the<br />space, with the dots coming before it.<br />Often scripts need to display columns of numbers. For example, you might<br />have three numbers: 12.3, 1, and 234.55. If you just echo them, they display<br />as follows:<br />12.3<br />1<br />234.55<br />Even if you use number_format to specify two decimal places, they display<br />as follows:<br />12.30<br />1.00<br />234.55<br />You can display them in an orderly column, however, by using printf as<br />follows:<br />printf(“%5.2f\n”,$number1);<br />printf(“%5.2f\n”,$number2);<br />printf(“%5.2f\n”,$number3);<br />Your output is as follows:<br />12.30<br />1.00<br />234.55<br />In the preceding statements, %5.2f\n is the format that tells PHP how to<br />format the number in the output. Here’s a closer look:<br /> %: Tells PHP that the following digits are a formatting instruction.<br /> 5: The width — how long the number should be. If the number is less<br />than 5 digits wide, it is right-justified, which means it’s moved as far right<br />as it can go. Right-justified is the default, so no symbol is needed in the<br />format to right-justify the numbers.<br /> .2: Means that the number should be displayed with 2 decimal places.<br /> f: Tells PHP to display the number as a float.<br /> \n: Tells PHP to start a new line.<br />To put numbers into the proper format for dollars, you can use sprintf. The<br />following statement formats a number into a dollar amount:<br />$newvariablename = sprintf(“$%.2f”, $oldvariablename);<br />91 Chapter 5: Working with Data<br />This statement reformats the number in $oldvariablename and stores it in<br />the new format in $newvariablename. For example, the following statements<br />display money in the correct format:<br />$price = 25;<br />printf(“$%.2f”,$price);<br />You see the following output:<br />$25.00<br />Working with Dates and Times<br />Dates and times can be important elements in a script. PHP has the ability to<br />recognize dates and times and handle them differently than plain character<br />strings. The computer stores dates and times in a format called a timestamp,<br />which is expressed entirely in seconds. However, because this is an impractical<br />format for humans to read, PHP converts dates from your notation into a<br />timestamp the computer understands and from a timestamp into a format that<br />is familiar to people. PHP handles dates and times by using built-in functions.<br />The timestamp format is a UNIX Timestamp, an integer that is the number of<br />seconds from January 1, 1970 00:00:00 GMT to the time represented by the<br />timestamp. This format makes it easy to calculate the time between two<br />dates — just subtract one timestamp from the other.<br />Formatting dates<br />The function you will use most often is date. The date function converts a<br />date or time from the timestamp format into a format you specify. The general<br />format is as follows:<br />$mydate = date(“format”,$timestamp);<br />$timestamp is a variable with a timestamp stored in it. You previously stored<br />the timestamp in the variable by using a time or mktime, as described in the<br />next section. If $timestamp is not included, PHP obtains the current time<br />from the operating system. Thus, you can get today’s date with the following<br />statement:<br />$today = date(“Y/m/d”);<br />If today is March 10, 2004, this statement returns:<br />2004/03/10<br />92 Part II: Variables and Data<br />The format is a string that specifies the date format you want stored in the<br />variable. For example, the format “y-m-d” returns 04-3-10, and “M.d.Y”<br />returns Mar.10.2004. Table 5-4 lists some of the symbols that you can use in<br />the format string. (For a complete list of symbols, see the documentation at<br />www.php.net.) The parts of the date can be separated by hyphens (-), dots<br />(.), slashes (/), or spaces.<br />Table 5-4 Date Format Symbols<br />Symbol Meaning Example<br />M Month in text, abbreviated Jan<br />F Month in text not abbreviated January<br />m Month in numbers with leading zeros 02 or 12<br />n Month in numbers without leading zeros 1 or 12<br />d Day of the month; two digits with leading zeros 01 or 14<br />j Day of the month without leading zeros 3 or 30<br />l Day of the week in text not abbreviated Friday<br />D Day of the week in text as an abbreviation Fri<br />w Day of the week in numbers from 0 (Sunday) 5<br />to 6 (Saturday)<br />Y Year in four digits 2004<br />y Year in two digits 04<br />g Hour between 0 and 12 without leading zeros 2 or 10<br />G Hour between 0 and 24 without leading zeros 2 or 15<br />h Hour between 0 and 12 with leading zeros 01 or 10<br />H Hour between 0 and 12 with leading zeros 00 or 23<br />i Minutes 00 or 59<br />s Seconds 00 or 59<br />a am or pm in lowercase am<br />A AM or PM in uppercase AM<br />U Unix seconds 1056244941<br />93 Chapter 5: Working with Data<br />Storing a timestamp in a variable<br />You can assign a timestamp with the current date and time to a variable with<br />the following statement:<br />$today = time();<br />Another way to store a current timestamp is with the following statement:<br />$today = strtotime(“today”);<br />You can store a specific date and time as a timestamp by using the function<br />mktime. The format is<br />$importantDate = mktime(h,m,s,mo,d,y);<br />where h is hours, m is minutes, s is seconds, mo is month, d is day, and y is<br />year. For example, you would store the date January 15, 2003, by using the<br />following statement:<br />$importantDate = mktime(0,0,0,1,15,2003);<br />You can also store specific timestamps by using strtotime with various keywords<br />and abbreviations that are very much like English. For instance, you<br />can create a timestamp for January 15, 2003, as follows:<br />$importantDate = strtotime(“January 15 2003”);<br />strtotime recognizes the following words and abbreviations:<br /> Month names: Twelve month names and abbreviations<br /> Days of the week: Seven days and some abbreviations<br /> Time units: Year, month, fortnight, week, day, hour, minute, second;<br />am, pm<br /> Some useful English words: Ago, now, last, next; this, tomorrow,<br />yesterday<br /> Plus and minus: + or -<br /> All numbers<br /> Time zones: For example, gmt (Greenwich Mean Time), pdt (Pacific<br />Daylight Time), and akst (Alaska Standard Time)<br />94 Part II: Variables and Data<br />You can combine the words and abbreviations in a variety of ways. The following<br />statements are all valid:<br />$importantDate = strtotime(“tomorrow”); #24 hours from now<br />$importantDate = strtotime(“now + 24 hours”);<br />$importantDate = strtotime(“last saturday”);<br />$importantDate = strtotime(“8pm + 3 days”);<br />$importantDate = strtotime(“2 weeks ago”); # at current time<br />$importantDate = strtotime(“next year gmt”); #1 year from now<br />$importantDate = strtotime(“tomorrow 4am”);<br />You can find differences between timestamps by using subtraction. For example,<br />if $importantDate is in the past and you want to know how long ago<br />$importantDate was, you can subtract it from the variable $today you<br />defined earlier. For example:<br />$timeSpan = $today &#8211; $importantDate;<br />This gives you the number of seconds between the important date and today.<br />You can also use the following statement to find out how many hours have<br />transpired since the important date:<br />$timeSpan =(($today &#8211; $importantDate)/60)/60;<br />95 Chapter 5: Working with Data<br />96 Part II: Variables and Data<br />Chapter 6<br />Storing Data in Groups<br />by Using Arrays<br />In This Chapter<br /> Building arrays<br /> Assigning values to arrays<br /> Sorting arrays<br /> Using values in arrays<br /> Building multidimensional arrays<br />Arrays are complex variables that store a group of values under a single<br />variable name. An array is useful for storing a group of related values.<br />For example, you can store information about a car, such as model, color, and<br />cost, in a single array named $FordInfo. Information in an array can be handled,<br />accessed, and modified easily. For example, PHP has several methods<br />for sorting the information inside an array.<br />In this chapter, you find out how to create, modify, copy, and use arrays.<br />Creating and Working with Arrays<br />Arrays are an important feature in PHP programming. This section describes<br />how to create, modify, and remove arrays.<br />Creating arrays<br />To create a variable, you assign a value to it. Similarly, the simplest way to<br />create an array is to assign a value to it. For instance, assuming that you have<br />not referenced $customers at any earlier point in the script, the following<br />statement creates an array called $customers:<br />$customers[1] = “Sam Smith”;<br />At this point, the array named $customers has been created and holds only<br />one value — Sam Smith. Next, you use the following statements:<br />$customers[2] = “Sue Jones”;<br />$customers[3] = “Mary Huang”;<br />Now, the array $customers contains three values: Sam Smith, Sue Jones, and<br />Mary Huang.<br />An array can be viewed as a list of key/value pairs, stored as follows:<br />$arrayname[‘key1’] = value1;<br />$arrayname[‘key2’] = value2;<br />$arrayname[‘key3’] = value3;<br />and so on up to any number of elements in the array.<br />The key is also referred to as the index.<br />Arrays can use either numbers or strings for keys. In the $customers array,<br />the keys are numbers — 1, 2, and 3. However, you can also use strings for<br />keys. For example, the following statements create an array of state capitals:<br />$capitals[‘CA’] = “Sacramento”;<br />$capitals[‘TX’] = “Austin”;<br />$capitals[‘OR’] = “Salem”;<br />Or you can use shortcuts to create arrays, rather than write separate assignment<br />statements for each number. One shortcut uses the following statements:<br />$streets[] = “Elm St.”;<br />$streets[] = “Oak Dr.”;<br />$streets[] = “7th Ave.”;<br />When you create an array by using this shortcut, the values are automatically<br />assigned keys that are serial numbers, starting with the number 0. For example,<br />consider the following statement:<br />echo “$streets[0]”;<br />It sends the following output:<br />Elm St.<br />98 Part II: Variables and Data<br />The first value in an array with a numbered index is 0, unless you deliberately<br />set it to a different number. One common mistake when working with arrays<br />is to think of the first number as 1, rather than 0.<br />An even shorter shortcut is to use the following statement:<br />$streets = array ( “Elm St.”,”Oak Dr.”,”7th Ave.”);<br />This statement creates the same array as the preceding shortcut. It assigns<br />numbers as keys, starting with 0. If you want the array to start with the<br />number 12, instead of 0, you can use the following statement:<br />$streets = array ( 12 =&gt; “Elm St.”,”Oak Dr.”,”7th Ave.”);<br />This statement creates an array as follows:<br />$streets[12] = Elm St.<br />$streets[13] = Oak Dr.<br />$streets[14] = 7th Ave.<br />You can use a similar statement to create arrays with words as keys. For<br />example, the following statement creates the array of state capitals with an<br />array statement, instead of using separate statements for each element of the<br />array:<br />$capitals = array ( “CA” =&gt; “Sacramento”,<br />“TX” =&gt; “Austin”,<br />“OR” =&gt; “Salem” );<br />Notice the structure of this statement. PHP doesn’t pay attention to the white<br />spaces or new lines. The statement could be written as one long line. The<br />organization of this statement is solely to make it easier for people to read.<br />You should make your statements as clear and legible as possible. When you<br />are troubleshooting your scripts, you will be glad you took the time to make<br />them more people-friendly.<br />You can also create an array with a range of values by using the following<br />statement:<br />$years = range(2001, 2010);<br />The resulting array looks like the following:<br />$years[0] = 2001<br />$years[1] = 2002<br />. . .<br />$years[8] = 2009<br />$years[9] = 2010<br />99 Chapter 6: Storing Data in Groups by Using Arrays<br />Similarly, you can use a statement, as follows:<br />$reverse_letters = range(“z”, “a”);<br />This statement creates an array with 26 elements:<br />$reverse_letters[0]=z<br />$reverse_letters[1]=y<br />. . .<br />$reverse_letters[24]=b<br />$reverse_letters[25]=a<br />Viewing arrays<br />You can see the structure and values of any array by using one of two<br />statements — var_dump or print_r. The print_r() statement, however,<br />gives somewhat less information. To display the $customers array, use<br />the following statement:<br />print_r($customers);<br />This print_r statement provides the following output:<br />Array<br />(<br />[1] =&gt; Sam Smith<br />[2] =&gt; Sue Jones<br />[3] =&gt; Mary Huang<br />)<br />This output shows the key and the value for each element in the array. To get<br />more information, use the following statement:<br />var_dump($customers);<br />This statement gives the following output:<br />array(3) {<br />[1]=&gt;<br />string(9) “Sam Smith”<br />[2]=&gt;<br />string(9) “Sue Jones”<br />[3]=&gt;<br />string(10) “Mary Huang”<br />}<br />This output shows the data type of each element, such as a string of 9 characters,<br />in addition to the key and value. An array containing the customer<br />name and age would display as follows:<br />100 Part II: Variables and Data<br />array(2) {<br />[“name”]=&gt;<br />string(9) “Sam Smith”<br />[“age”]=&gt;<br />int(12)<br />}<br />The integer value is identified as an integer with int, and the value of age is<br />shown. This customer is 12 years old.<br />Remember, this output is sent by PHP. If you’re using PHP for the Web, the<br />output displays on the Web page with HTML, which means that it displays in<br />one long line. To see the output on the Web in the useful format that I describe<br />here, send HTML tags that tell the browser to display the text as received, without<br />changing it, by using the following statements:<br />echo “&lt;pre&gt;”;<br />var_dump($customers);<br />echo “&lt;/pre&gt;”;<br />Modifying arrays<br />Arrays can be changed at any time in the script, just as variables can. The<br />individual values can be changed, elements can be added or removed, and<br />elements can be rearranged. For example, if you have an existing array named<br />$capitals, you can use the following statement to change the value of an<br />element:<br />$capitals[‘TX’] = “Big Springs”;<br />This statement changes the value of this element of the $capitals array,<br />although the people in Austin might object to the change. Or you could use<br />the following statement:<br />$capitals[‘RI’] = “Providence”;<br />The statement adds a new element to the array, leaving the existing elements<br />intact.<br />Suppose that your array has numbers for keys, as is the case with the following<br />array, which is created at the beginning of a script:<br />$customers[1] = Sam Smith<br />$customers[2] = Sue Jones<br />$customers[3] = Mary Huang<br />101 Chapter 6: Storing Data in Groups by Using Arrays<br />You can use the following statement later in the script:<br />$customers[] = “Juan Lopez”;<br />$customers now becomes an array with four elements, as follows:<br />$customers[1] = Sam Smith<br />$customers[2] = Sue Jones<br />$customers[3] = Mary Huang<br />$customers[4] = Juan Lopez<br />You can also copy an entire existing array into a new array with this statement:<br />$customerCopy = $customers;<br />Removing values from arrays<br />Sometimes you need to completely remove a value from an array. For example,<br />suppose you have the following array:<br />$colors = array ( “red”, “green”, “blue”, “pink”, “yellow” );<br />This array has five values. Now you decide that you no longer like the color<br />pink, so you use the following statement to try to remove pink from the array:<br />$colors[3] = “”;<br />Although this statement sets $colors[3] to blank, it does not remove it from<br />the array. You still have an array with five values, one of the values being an<br />empty string. To totally remove the item from the array, you need to unset it<br />with the following statement:<br />unset($colors[3]);<br />Now your array has only four values in it and looks as follows:<br />$colors[0] = red<br />$colors[1] = green<br />$colors[2] = blue<br />$colors[4] = yellow<br />Notice that the other keys did not change when element 3 was removed.<br />After an array has been created, it does not cease to exist unless it is deliberately<br />removed. Removing all the values doesn’t remove the array itself, just<br />102 Part II: Variables and Data<br />like removing all the drawers from a dresser doesn’t make the dresser disappear.<br />To remove the array itself, you can use the following statement:<br />unset($colors);<br />Sorting Arrays<br />One of the most useful features of arrays is that PHP can sort them for you.<br />PHP originally stores array elements in the order in which you create them.<br />If you display the entire array without changing the order, the elements are<br />displayed in the order in which they were created. Often, you want to change<br />this order. For example, you may want to display the array in alphabetical<br />order by value or by key.<br />PHP can sort arrays in a variety of ways. To sort an array that has numbers<br />as keys, use a sort statement as follows:<br />sort($arrayname);<br />This statement sorts arrays by the values and assigns new keys that are the<br />appropriate numbers. The values are sorted with numbers first, uppercase<br />letters next, and lowercase letters last. For example, consider the $streets<br />array:<br />$streets[0] = “Elm St.”;<br />$streets[1] = “Oak Dr.”;<br />$streets[2] = “7th Ave.”;<br />You enter the following sort statement:<br />sort($streets);<br />Now the array becomes as follows:<br />$streets[0] = “7th Ave.”;<br />$streets[1] = “Elm St.”;<br />$streets[2] = “Oak Dr.”;<br />If you use sort() to sort an array with words as keys, the keys are changed<br />to numbers, and the word keys are thrown away.<br />To sort arrays that have words for keys, use the asort statement as follows:<br />asort($capitals);<br />103 Chapter 6: Storing Data in Groups by Using Arrays<br />This statement sorts the capitals by value, but it keeps the original key for<br />each value instead of assigning a number key. For example, consider the state<br />capitals array created in the preceding section:<br />$capitals[‘CA’] = “Sacramento”;<br />$capitals[‘TX’] = “Austin”;<br />$capitals[‘OR’] = “Salem”;<br />You use the following asort statement,<br />asort($capitals);<br />The array becomes as follows:<br />$capitals[‘TX’] = Austin<br />$capitals[‘CA’] = Sacramento<br />$capitals[‘OR’] = Salem<br />Notice that the keys stayed with the value when the elements were reordered.<br />Now the elements are in alphabetical order, and the correct state key is still<br />with the appropriate state capital. If the keys has been numbers, the numbers<br />would now be in a different order. For example, suppose the original array was<br />as follows:<br />$capitals[1] = “Sacramento”;<br />$capitals[2] = “Austin”;<br />$capitals[3] = “Salem”;<br />After an asort statement, the new array would be as follows:<br />$capitals[2] = Austin<br />$capitals[1] = Sacramento<br />$capitals[3] = Salem<br />It’s unlikely that you want to use asort on an array with numbers as a key.<br />You can use several other sort statements to sort in other ways. Table 6-1<br />lists all the available sort statements.<br />Table 6-1 Ways You Can Sort Arrays<br />Sort Statement What It Does<br />sort($arrayname) Sorts by value; assigns new numbers as the keys.<br />asort($arrayname) Sorts by value; keeps the same key.<br />rsort($arrayname) Sorts by value in reverse order; assigns new numbers<br />as the keys.<br />104 Part II: Variables and Data<br />Sort Statement What It Does<br />arsort($arrayname) Sorts by value in reverse order; keeps the<br />same key.<br />ksort($arrayname) Sorts by key.<br />krsort($arrayname) Sorts by key in reverse order.<br />usort($arrayname, Sorts by a function (see Chapter 8 for information<br />functionname) on functions).<br />natsort($arrayname) Sorts mixed string/number values in natural order.<br />For example, given an array with values day1, day5,<br />day11, day2, it sorts into the following order: day1,<br />day2, day5, day11. The previous sort functions sort<br />the array into this order: day1, day11, day2, day5.<br />Using Arrays in Statements<br />Arrays can be used in statements in the same way that variables are used in<br />statements. This section shows the use of arrays in PHP statements.<br />You can retrieve any individual value in an array by accessing it directly, as in<br />the following example:<br />$CAcapital = $capitals[‘CA’];<br />echo $CAcapital ;<br />You get the following output from these statements:<br />Sacramento<br />If you use an array element that doesn’t exist in a statement, a notice is displayed.<br />For example, suppose you use the following statement:<br />$CAcapital = $capitals[‘CAx’];<br />If the array $capitals exists, but no element has the key CAx, you see the<br />following notice:<br />Notice: Undefined index: CAx in d:\testarray.php on line 9<br />A notice does not cause the script to stop. Statements after the notice will<br />continue to execute. But because no value has been put into $CAcapital,<br />any subsequent echo statements will echo a blank space. You can prevent<br />the notice from being displayed by using the @ symbol:<br />105 Chapter 6: Storing Data in Groups by Using Arrays<br />@$CAcapital = $capitals[‘CAx’];<br />Using arrays in echo statements<br />You can echo an array value like this:<br />echo $capitals[‘TX’];<br />It displays the following:<br />Austin<br />If you include the array value in a longer echo statement that’s enclosed by<br />double quotes, you may need to enclose the array value name in curly braces<br />like this:<br />echo “The capital of Texas is {$capitals[‘TX’]}”;<br />The output is as follows:<br />The capital of Texas is Austin<br />Using arrays in list statements<br />You can retrieve several values at once from an array with the list statement.<br />The list statement copies values from an array into variables. Suppose you<br />create the following array:<br />$shoeInfo = array(“loafer”, “black”, 22.00);<br />You can display the array with the following statement:<br />print_r($shoeInfo);<br />The output is as follows:<br />Array<br />(<br />[0] =&gt; loafer<br />[1] =&gt; black<br />[2] =&gt; 22<br />)<br />106 Part II: Variables and Data<br />The following statements show the use of the list statement on the<br />$shoeInfo array:<br />list($first,$second) = $shoeInfo;<br />echo $second,” “,$first;<br />This list statement creates two variables named $first and $second and<br />copies the first two values from $shoeInfo into the two new variables, as if<br />you had used the following two statements:<br />$first=$shoeInfo[0];<br />$second=$shoeInfo[1];<br />The third value in $shoeInfo is not copied into a variable because the list<br />statement contains only two variables. The output from the echo statement<br />is as follows:<br />black loafer<br />In some cases, you may want to retrieve the key from an array element rather<br />than the value. Suppose the following element is the first element in an array:<br />$shoeInfo[‘style’] = loafer;<br />The following statements retrieve the key, along with the value, and echo<br />them:<br />$value = $shoeInfo[‘style’];<br />$key = key($shoeInfo);<br />echo “$key: $value”;<br />The output from these statements is as follows:<br />style: loafer<br />The first statement puts loafer into $value. The second statement puts<br />style into $key. The key statement gets the key of an array element. In this<br />case, it retrieves the key from the first element because that was the current<br />element where the pointer is located. You can get any key in the array by<br />walking through the array. The next section explains what the pointer is and<br />how to walk through arrays.<br />Walking through an Array<br />You will often want to do something to every value in an array. You may want<br />to echo each value, store each value in a database, or add six to each value in<br />107 Chapter 6: Storing Data in Groups by Using Arrays<br />the array. In technical talk, walking through each and every element in an<br />array, in order, is called iteration. It is also sometimes called traversing. This<br />section describes two ways to walk through an array:<br /> Traversing an array manually: Uses a pointer to move from one array<br />value to another<br /> Using foreach: Automatically walks through the array, from beginning<br />to end, one value at a time<br />Traversing an array manually<br />You can walk through an array manually by using a pointer. To do this, think of<br />your array as a list. Imagine a pointer pointing to a value in the list. The pointer<br />stays on a value until you move it. After you move it, it stays there until you<br />move it again. You can move the pointer with the following instructions:<br /> current($arrayname): Refers to the value currently under the pointer;<br />does not move the pointer<br /> next($arrayname): Moves the pointer to the value after the current value<br /> previous($arrayname): Moves the pointer to the value before the current<br />pointer location<br /> end($arrayname): Moves the pointer to the last value in the array<br /> reset($arrayname): Moves the pointer to the first value in the array<br />The following statements manually walk through an array containing state<br />capitals:<br />$value = current ($capitals);<br />echo “$value&lt;br&gt;”;<br />$value = next ($capitals);<br />echo “$value&lt;br&gt;”;<br />$value = next ($capitals);<br />echo “$value&lt;br&gt;”;<br />Unless you have moved the pointer previously, the pointer is located at the<br />first element when you start walking through the array. If you think the array<br />pointer may have been moved earlier in the script or if your output from the<br />array seems to start somewhere in the middle, use the reset statement<br />before you start walking, as follows:<br />reset($capitals);<br />Using this method to walk through an array, you need an assignment statement<br />and an echo statement for every value in the array — for each of the 50<br />states. The output is a list of all the state capitals.<br />108 Part II: Variables and Data<br />This method gives you flexibility. You can move through the array in any<br />manner, not just one value at a time. You can move backwards, go directly<br />to the end, skip every other value by using two consecutive next statements,<br />or employ whatever method is useful. However, if you want to go through the<br />array from beginning to end, one value at a time, PHP provides an easier<br />method: the foreach statement, which does exactly what you need more<br />efficiently. The foreach statement is described in the next section.<br />Using foreach to walk through an array<br />You can use foreach to walk through an array one value at a time and execute<br />a block of statements by using each value in the array. The general<br />format is as follows:<br />foreach ( $arrayname as $keyname =&gt; $valuename )<br />{<br />block of statements;<br />}<br />In this format, you need to fill in the following information:<br /> arrayname: The name of the array you are walking through.<br /> keyname: The name of the variable where you want to store the key. The<br />keyname variable is optional. If you leave out $keyname =&gt;, only the<br />value is stored into $valuename.<br /> valuename: The name of the variable where you want to store the value.<br />For example, the following foreach statement walks through a sample array<br />of state populations and echoes a list:<br />$state_population = array ( “CA” =&gt; 34501130,<br />“WY” =&gt; 494423,<br />“OR” =&gt; 3472867);<br />ksort($state_population);<br />foreach($state_population as $state =&gt; $population )<br />{<br />$population = number_format($population);<br />echo “$state: $population.&lt;br&gt;”;<br />}<br />The preceding statements give the following Web page output:<br />CA: 34,501,130<br />OR: 3,472,867<br />WY: 494,423<br />109 Chapter 6: Storing Data in Groups by Using Arrays<br />You can use the following line in place of the foreach line in the previous<br />statements:<br />foreach ( $state_population as $population )<br />With this statement, the key (state) is not stored in a variable. Only the populations<br />are available for the output.<br />When foreach starts walking through an array, it moves the pointer to the<br />beginning of the array. You don’t need to reset an array before walking<br />through it with foreach.<br />Finding Array Size<br />To see the structure and values of your array, you can use var_dump and<br />print_r (described earlier in this chapter in “Viewing arrays”), but sometimes<br />you just want to know the size of your array, rather than see everything<br />that’s in it.<br />You can find out the size of your array by using either the count statement or<br />a sizeof statement. The format for these statements is as follows:<br />$n = count($arrayname);<br />$n = sizeof($arrayname);<br />After either of these statements, $n will contain the number of elements in<br />the array.<br />Converting Arrays into Strings<br />(And Vice Versa)<br />Sometimes you want to perform an operation on information, but the operation<br />requires the information to be in a different format. For instance, you may<br />want to display every word in a sentence on a separate line. One way to do this<br />is to add a \n on the end of each word before you display it. You could use a<br />foreach statement to do that easily if the sentence is in an array, rather than<br />in a string. PHP allows you to create an array that contains one word of the sentence<br />in each element.<br />You can create an array that contains the contents of a string by using a<br />statement in the following format:<br />$arrayname = explode(“s”,string);<br />110 Part II: Variables and Data<br />The first item in the parentheses (s) is the character to use to divide the<br />string. The second item is the string itself. For example, the following statement<br />creates an array that contains the characters in a string:<br />$string1 = “This:is a: new:house”;<br />$testarray = explode(“:”,$string1);<br />print_r($testarray);<br />The explode statement tells PHP to split the string at each colon (:) and<br />create an array containing the substrings. The output is the following:<br />Array<br />(<br />[0] =&gt; This<br />[1] =&gt; is a<br />[2] =&gt; new<br />[3] =&gt; house<br />)<br />$string1 is not affected.<br />Conversely, you can convert an array into a string by using the following<br />statement:<br />$resString = implode(“s”,$array);<br />The statement tells PHP to create a string containing all the elements in<br />$array, with s separating the text from each array element, and store the<br />string in $resString. For example, you could use the following statements:<br />$arrayIn = array( “red”, “blue”, “green”);<br />$stringOut = implode(“;”,$arrayIn);<br />echo $stringOut;<br />The output string from implode is stored in $stringOut. The implode<br />statement, as you might guess, doesn’t affect $arrayIn. In general, these<br />statements do not affect the input to the statement; they just read it. If<br />any statement changes the input, I will point it out to you.<br />The following is the output of this echo statement:<br />red;blue;green<br />There is no space between the elements in the string because no space was<br />specified in the implode statement. Using a space in s, as in the following<br />implode statement, puts spaces into the resulting string:<br />$stringOut = implode(“; “,$arrayIn);<br />111 Chapter 6: Storing Data in Groups by Using Arrays<br />With this statement, the output is as follows:<br />red; blue; green<br />Converting Variables into<br />Arrays (And Vice Versa)<br />Sometimes you want the information in an array stored in variables that you<br />can use in PHP statements. Or you need variables converted to array elements.<br />For example, you might want to perform the same operation on a<br />bunch of variables, such as add 1 to each variable value. If you convert the<br />variables into elements of an array, you can use one foreach statement to<br />access the variable values one at a time, rather than write a bunch of statements<br />to access each variable separately.<br />Using the extract statement, you can retrieve all the values from an array,<br />and insert each value into a variable, by using the key for the variable name.<br />In other words, each array value is copied into a variable named for the key.<br />For example, the following statements get all the information from an array<br />and echo it:<br />$testarray = array( “pink”=&gt;”carnation”, “red”=&gt;”rose”);<br />extract($testarray);<br />echo “My favorite red flower is a $red.\n”;<br />echo “My favorite pink flower is a $pink.”;<br />The output for these statements is the following:<br />My favorite red flower is a rose.<br />My favorite pink flower is a carnation.<br />Conversely, you can also convert a group of simple variables into an array by<br />using a compact statement that copies the value from each specified variable<br />name into an array element. The use of the compact statement is, shown in<br />the following statements:<br />$color1 = “red”;<br />$color2 = “blue”;<br />$a = “purple”;<br />$b = “orange”;<br />$arrayIn = array(“a”,”b”);<br />$arrayOut = compact(“color1”,”color2”,$arrayIn);<br />112 Part II: Variables and Data<br />The result is the following array:<br />$arrayOut[color1] = red<br />$arrayOut[color2] = blue<br />$arrayOut[a] = purple<br />$arrayOut[b] = orange<br />As you can see, the names of the variables are used as the keys.<br />Notice that two different methods are used in the compact statement to specify<br />the variables that make up the array:<br /> First method: You can use the variable names directly, as strings. The<br />two variables color1 and color2 in the example show this method.<br /> Second method: You use an array that contains the names of the variables.<br />In the previous code, $arrayIn contains the variable names: a<br />and b. Then in the compact statement, the array name is used to add the<br />variables to the array.<br />You can use either method. If you have only a few variables to compact into<br />an array, the first method of just using the variable names is probably fine.<br />However, if you have a lot of variables to include, you may prefer putting the<br />names into an array first, and then using the array in the compact statement.<br />Splitting and Merging Arrays<br />You often need to put arrays together or take them apart. For example, suppose<br />you have two classes of students and you have two arrays, each of which stores<br />the names of the students in one class. If the two classes were to merge, you<br />would want to merge the two arrays containing the student names.<br />You can split an array by creating a new array that contains a subset of an<br />existing array. You can do this by using a statement of the following general<br />format:<br />$subArray = array_slice($arrayname,n1,n2);<br />The n1 in the statement is the sequence number of the element where the<br />new array should start, such as 0 for the first element in the array or 1 for the<br />second element. The n2 is the length of the new array. For example, consider<br />the following statements:<br />$testarray = array( “red”, “green”, “blue”,”pink”);<br />$subArray = array_slice($testarray,1,2);<br />113 Chapter 6: Storing Data in Groups by Using Arrays<br />The new array, $subArray, will contain the following:<br />[0] =&gt; green<br />[1] =&gt; blue<br />It starts with element 1 of $testarray and takes 2 elements.<br />Unless you specify otherwise, arrays begin with 0, not 1. Therefore, element 1<br />of $testarray is green. Red is element 0.<br />Conversely, you can merge two or more arrays together by using the following<br />statement:<br />$bigArray = array_merge($array1,$array2,&#8230;);<br />For example, you might use the following statements to merge arrays:<br />$array1 = array(“red”,”blue”);<br />$array2 = array(“green”,”yellow”);<br />$bigArray = array_merge($array1,$array2);<br />After the statement, $bigArray is the following array:<br />$bigArray[0] = red<br />$bigArray[1] = blue<br />$bigArray[2] = green<br />$bigArray[3] = yellow<br />You can merge arrays with keys that are words, rather than numbers, as well.<br />However, if the keys are the same for any of the elements, the later element<br />with the same key word will overwrite the first element of the same key. For<br />example, suppose you merge the following arrays:<br />$array1 = array(“color1”=&gt;”red”,”color2”=&gt;”blue”);<br />$array2 = array(“color1”=&gt;”green”,”color3”=&gt;”yellow”);<br />$bigArray = array_merge($array1,$array2);<br />The output array is as follows:<br />$bigArray[color1] = green<br />$bigArray[color2] = blue<br />$bigArray[color3] = yellow<br />If you need to merge arrays that have identical keys, you can use the statement<br />array_merge_recursive rather than array_merge. The array_merge_<br />recursive statement creates a multidimensional array when keys are identical,<br />instead of overwriting the value as array_merge does. Multidimensional arrays<br />are explained in the section, “Multidimensional Arrays,” later in this chapter.<br />114 Part II: Variables and Data<br />Comparing Arrays<br />You may need to know whether two arrays are the same. You can identify<br />the elements that are different or the elements that are the same. To find<br />out which elements are different, use the following statement:<br />$diffArray = array_diff($array1,$array2,&#8230;);<br />After this statement, $diffArray contains the elements from $array1 that are<br />not present in any of the other listed arrays. The elements in the result array<br />will have the same keys. For example, you can use the following statements:<br />$array1 = array( “a”=&gt;”apple”, “b”=&gt;”orange”, “c”=&gt;”banana”);<br />$array2 = array( “prune”, “orange”, “banana” );<br />$diffArray = array_diff($array1,$array2);<br />After this code, $diffArray looks like this:<br />$diffArray[a] = apple;<br />The element apple is in the array because apple is in $array1 but not in<br />$array2.<br />The order in which you list the arrays to be compared makes a difference.<br />For example, if you used the following statement, instead of the preceding<br />one, you’d get a different output:<br />$diffArray = array_diff($array2,$array1);<br />After this statement, $diffArray looks like the following:<br />$diffArray[0] = prune;<br />Because $array2 is listed first in this statement, the resulting difference<br />array contains only prune because prune is in $array2, listed first, but not<br />in $array1, listed second.<br />If you want to find array elements that differ in either the value or the key,<br />you can use the following statement:<br />$diffArray = array_diff_assoc($array1,$array2);<br />Using the same $array1 and $array2 as the previous examples, the resulting<br />array would look like this:<br />$diffArray[a] = apple<br />$diffArray[b] = orange<br />$diffArray[c] = banana<br />115 Chapter 6: Storing Data in Groups by Using Arrays<br />In this case, none of the elements in $array1 appear in $array2 because the<br />keys are all different.<br />You can create an array that contains the elements that are the same, rather<br />than different, in two or more arrays by using the following statement:<br />$simArray = array_intersect($array1,$array2,. . .);<br />For example, using the same arrays, you could use the following statement:<br />$simArray = array_intersect($array1,$array2);<br />The results array would look like this:<br />$simArray[b] = orange<br />$simArray[c] = banana<br />This array_intersect statement adds an element to the new array for any<br />values that are in both the arrays. If you want both the value and the key to<br />be the same, use the following statement:<br />$simArray = array_intersect_assoc($array1,$array2);<br />This statement requires both the value and the key to be identical before<br />adding an element to the array. Using the same arrays, $simArray is empty<br />after the statement, because even though two of the values are the same,<br />none of the keys are the same.<br />Working with Other Array Operations<br />The following sections describe these miscellaneous operations on arrays:<br /> Adding the values of an array<br /> Removing duplicate items from an array<br /> Exchanging keys and values in an array<br />Summing arrays<br />To add all the values in an array, use the following statement:<br />$sum = array_sum($array);<br />116 Part II: Variables and Data<br />For example, you can use the following statements;<br />$arrayAdd = array(3,3,3);<br />$sum = array_sum($arrayAdd);<br />echo $sum;<br />The output is 9.<br />Of course, you are only going to add elements in an array of numbers. As<br />mentioned in Chapter 5, PHP converts strings to 0 if you try to add them.<br />Removing duplicate items<br />You sometimes need to remove duplicate elements from an array. For example,<br />if you want to print a list of customer names from the elements of an<br />array, you probably want each name listed only once. You can do so with the<br />following statements:<br />$names = array( “Mary”, “Sally”, “Sally”,”Sam”);<br />$names2 = array_unique($names);<br />The array $names2 looks like this:<br />$names2[0] =&gt; Mary<br />$names2[1] =&gt; Sally<br />$names2[3] =&gt; Sam<br />As you can see, the duplicate element and its key are not in the resulting<br />array.<br />Exchanging keys and values<br />You can exchange values and keys in an array. For example, suppose you<br />have the following array:<br />$testarray[‘rose’] = red<br />$testarray[‘iris’] = purple<br />To exchange the values, use the following statement:<br />$arrayFlipped = array_flip($testarray);<br />The array $arrayFlipped looks like this:<br />$testarray[‘red’] = rose<br />$testarray[‘purple’] = iris<br />117 Chapter 6: Storing Data in Groups by Using Arrays<br />Multidimensional Arrays<br />In the earlier sections of this chapter, I describe arrays that are a single list of<br />key/value pairs. However, on some occasions, you may want to store values<br />with more than one key. For example, suppose you want to store the following<br />food prices together in one variable:<br /> onion, 0.50<br /> apple, 2.50<br /> orange, 2.00<br /> bacon, 3.50<br /> potato, 1.00<br /> ham, 5.00<br />You can store these products in an array as follows:<br />$foodPrices[‘onion’] = 0.50;<br />$foodPrices[‘apple’] = 2.50;<br />$foodPrices[‘orange’] = 2.00;<br />$foodPrices[‘bacon’] = 3.50;<br />$foodPrices[‘potato’] = 1.00;<br />$foodPrices[‘ham’] = 5.00;<br />Your script can easily look through this array whenever it needs to know the<br />price of an item. But suppose you have 3,000 products. Your script would need<br />to look through 3,000 products to find the one with onion or ham as the key.<br />Notice that the list of foods and prices includes a variety of food that can be<br />classified into three groups: vegetable, fruit, and meat. If you classify the products,<br />then the script needs to look through only one classification to find the<br />correct price. Classifying the products is much more efficient. You can classify<br />the products by putting the costs in a multidimensional array as follows:<br />$foodPrices[‘vegetable’][‘onion’] = 0.50;<br />$foodPrices[‘vegetable’][‘potato’] = 1.00;<br />$foodPrices[‘fruit’][‘apple’] = 2.50;<br />$foodPrices[‘fruit’][‘orange’] = 2.00;<br />$foodPrices[‘meat’][‘bacon’] = 3.50;<br />$foodPrices[‘meat’][‘ham’] = 5.00;<br />This kind of array is called a multidimensional array because it’s like an array<br />of arrays. Figure 6-1 shows the structure of $foodPrices as an array of arrays.<br />The figure shows that $foodPrices has three key/value pairs. The value for<br />each key — vegetable, fruit, and meat — is an array with two key/value pairs.<br />For example, the value for the key meat is an array with the two key/value<br />pairs: bacon/3.50 and ham/5.00.<br />118 Part II: Variables and Data<br />$foodPrices is a two-dimensional array. PHP can also understand multidimensional<br />arrays that are four, five, six, or more levels deep. However, my<br />head starts to hurt if I try to comprehend an array that is more than three<br />levels deep. The possibility of confusion increases as the number of dimensions<br />increases.<br />Creating multidimensional arrays<br />You can create multidimensional arrays in the same ways you create onedimensional<br />arrays. You can create them with a series of direct statements,<br />as follows:<br />$foodPrices[‘vegetable’][‘potato’] = 1.00;<br />$foodPrices[‘fruit’][‘apple’] = 2.50;<br />You can also use a shortcut and allow PHP to choose the keys, as follows:<br />transportation[‘car’][] = “Ford”;<br />transportation[‘car’][] = “Jeep”;<br />PHP will assign numbers as keys so that the array looks like the following:<br />transportation[car][0] = Ford;<br />transportation[car][1] = Jeep;<br />You can also create a multidimensional array by using the array statement, as<br />follows:<br />$foodPrices = array(<br />“vegetable”=&gt;array(“potato”=&gt;1.00,”onion”=&gt;.50),<br />“fruit”=&gt;array(“apple”=&gt;2.50,”orange”=&gt;2.00));<br />Notice that foodPrices is an array, created by the first array statement. The<br />first array statement sets two elements — vegetable and fruit. The values for<br />the two elements are themselves set by array statements, resulting in an array<br />of arrays. This statement creates the following multidimensional array:<br />$foodPrices key value<br />key value<br />vegetable onion 0.50<br />potato 1.00<br />fruit orange 2.00<br />apple 2.50<br />meat bacon 3.50<br />ham 5.00<br />Figure 6-1:<br />The<br />structure of<br />$food<br />Prices, an<br />array of<br />arrays.<br />119 Chapter 6: Storing Data in Groups by Using Arrays<br />$foodPrices[vegetable][potato] = 1.00<br />$foodPrices[vegetable][onion] = .50<br />$foodPrices[fruit][apple] = 2.50<br />$foodPrices[fruit][orange] = 2.00<br />Viewing multidimensional arrays<br />You can view a multidimensional array in the same ways you can view any<br />array — by using the print_r or the var_dump statements. The output of<br />the var_dump statement is shown here:<br />array(2) {<br />[“vegetable”]=&gt;<br />array(2) {<br />[“potato”]=&gt;<br />float(1)<br />[“onion”]=&gt;<br />float(0.5)<br />}<br />[“fruit”]=&gt;<br />array(2) {<br />[“apple”]=&gt;<br />float(2.5)<br />[“orange”]=&gt;<br />float(2)<br />}<br />}<br />The first line identifies the first array and says it has two elements. The first<br />element, with the key vegetable, contains an array of two elements with the<br />keys potato with a value of 1 of type float, and the second element with the<br />key onion and a value of 0.5 of type float. The second element of the main<br />array, with the key fruit, also contains an array with two elements.<br />Using multidimensional<br />arrays in statements<br />You can get values from a multidimensional array by using the same procedures<br />that you use with a one-dimensional array. For example, you can<br />access a value directly with this statement:<br />$hamPrice = $foodPrices[‘meat’][‘ham’];<br />You can also echo the value:<br />echo $foodPrices[‘meat’][‘ham’];<br />120 Part II: Variables and Data<br />However, if you combine the value within double quotes, you need to use<br />curly braces to enclose the variable name. The $ that begins the variable<br />name must follow the { immediately, without a space, as follows:<br />echo “The price of ham is \${$foodPrices[‘meat’][‘ham’]}”;<br />Notice the backslash (\) in front of the first dollar sign ($). The backslash<br />tells PHP that $ is a literal dollar sign, not the beginning of a variable name.<br />The output is<br />The price of ham is $5<br />Earlier in this chapter, I describe several statements that convert strings to<br />arrays (and vice versa) and convert arrays to variables (and vice versa) and<br />statements for other operations on arrays. Most of the statements don’t<br />make sense with multidimensional arrays and won’t work correctly. However,<br />remember that a multidimensional array is an array of arrays. Therefore, you<br />can use one of the elements of the multidimensional array (which is an array<br />itself) in these statements. For instance, the implode statement described earlier<br />in this chapter converts an array into a string. You can’t use the implode<br />statement with a multidimensional array because its values are arrays, not<br />strings. However, you can use any one of the elements in the implode statements,<br />as follows:<br />$resString = implode(“: “,$foodPrices[‘vegetable’]);<br />This statement puts the value for each element of the vegetable array into<br />the string, separating them by :. When you echo $resString, you see the<br />following output:<br />1: 0.5<br />The output is the value of potato (1) and the value of onion (0.5). The two<br />values are separated by a semicolon and a space, as specified in the implode<br />statement.<br />Walking through a multidimensional array<br />You can walk through a multidimensional array by using foreach statements<br />(described in the section “Walking through an Array,” earlier in this chapter).<br />Because a two-dimensional array, such as $foodPrices, contains two arrays,<br />it takes two foreach statements to walk through it. One foreach statement<br />is inside the other foreach statement. (Putting statements inside other statements<br />is called nesting.)<br />121 Chapter 6: Storing Data in Groups by Using Arrays<br />The following statements echo the values from the multidimensional array:<br />foreach ( $foodPrices as $category )<br />{<br />foreach ( $category as $food =&gt; $price )<br />{<br />$f_price = sprintf(“%01.2f”, $price);<br />echo “$food: \$$f_price \n”;<br />}<br />}<br />The output is the following:<br />onion: $0.50<br />potato: $1.00<br />apple: $2.50<br />orange: $2.00<br />bacon: $3.50<br />ham: $5.00<br />Here is how PHP interprets these foreach statements:<br />1. The first key/value pair in the $foodPrices array is retrieved, and the<br />value is stored in the variable $category. (The value is an array.)<br />2. The first key/value pair in the $category array is retrieved. The key is<br />stored in $food, and the value is stored in $price.<br />3. The value in $price is formatted into the correct format for money.<br />4. One row for the product and its price is echoed.<br />5. The next key/value pair in the $category array is reached.<br />6. The price is formatted, and the next row for the food and its price is<br />echoed.<br />7. Because there are no more key/value pairs in $category, the inner<br />foreach statement ends.<br />8. The next key/value pair in the outer foreach statement is reached. The<br />next value is put in $category, which is an array.<br />9. The procedure in Steps 1 through 8 is repeated until the last key/value<br />pair in the last $category array is reached. The inner foreach statement<br />ends. The outer foreach statement ends.<br />In other words, the outer foreach starts with the first key/value pair in the<br />array. The key is vegetable, and the value of this pair is an array that is put<br />into the variable $category. The inner foreach then walks through the<br />array in $category. When it reaches the last key/value pair in $category, it<br />ends. The script is then back in the outer loop, which goes on to the second<br />key/value pair . . . and so on until the outer foreach reaches the end of the<br />array.<br />122 Part II: Variables and Data<br />Built-in PHP Arrays<br />PHP has several built-in arrays that you can use when writing PHP scripts.<br />Different types of information are stored in different arrays. For example,<br />information about your server (such as headers, paths, and script locations)<br />is stored in an array called $_SERVER. When you want to display the name of<br />the current script that is running, it’s available in the $_SERVER built-in array<br />in $_SERVER[‘PHP_SELF’].<br />Using superglobal arrays<br />Currently, two sets of built-in arrays contain the same information. One set of<br />arrays, introduced in PHP 4.1.0, are called superglobals or autoglobals because<br />they can be used anywhere, even inside a function. (Functions and the use of<br />variables inside functions are explained in Chapter 8.) The older arrays, with<br />long names such as $HTTP_SERVER_VARS, must be made global before they<br />can be used in an array, as explained in Chapter 8. Unless you’re using an old<br />version of PHP, use the newer arrays, those whose names begin with an<br />underscore (_). The older arrays should be used only when you’re forced to<br />use a version of PHP older than PHP 4.1.0.<br />A new php.ini setting introduced in PHP 5 allows you to prevent PHP from<br />automatically creating the older, long arrays. It’s very unlikely that you will<br />need to use them, unless you’re using some old scripts containing the long<br />variables. The following line in php.ini controls this setting:<br />register_long_arrays = On<br />At the current time, this setting is On by default. Unless you’re running old<br />scripts that need the old arrays, you should change the setting to Off so that<br />PHP doesn’t do this extra work.<br />Although the setting is currently On by default, that could change. The default<br />setting might change to Off in a future version. If you’re using some old scripts<br />and getting errors on lines containing the long arrays, such as $HTTP_GET_<br />VARS, check your php.ini setting for long arrays. It might be Off, and the long<br />arrays needed by the older script are not being created at all.<br />The built-in arrays are listed in Table 6-2, along with a short description. The<br />use of specific arrays is described in detail in this book where the related<br />subjects are described. For example, the built-in arrays that contain form<br />variables are discussed in Chapter 10 when I discuss the use of forms.<br />123 Chapter 6: Storing Data in Groups by Using Arrays<br />Table 6-2 Handy Built-in Arrays<br />Array Description<br />$GLOBALS Contains all the global variables. For example, if<br />you use the statement, $testvar = 1, you can<br />then access the variable as $GLOBALS<br />[‘testvar’].<br />$ _POST Contains all the variables contained in a form if<br />the form uses method=”post”.<br />$HTTP_POST_VARS Same as $ _POST.<br />$ _GET Contains all the variables passed from a previous<br />page as part of the URL. This includes variables<br />passed in a form using method=”get”.<br />$HTTP_GET_VARS Same as $ _GET.<br />$ _COOKIE Contains all the cookie variables.<br />$HTTP_COOKIE_VARS Same as $ _COOKIE.<br />$ _SESSION Contains all the session variables.<br />$HTTP_SESSION_VARS Same as $ _SESSION.<br />$_REQUEST Contains all the variables together that are in<br />$_POST, $_GET, and $_SESSION.<br />$_FILES Contains the names of files that have been<br />uploaded.<br />$HTTP_FILES_VARS Same as $_FILES.<br />$_SERVER Contains information about your server. Because<br />your Web server provides the information, the<br />information that’s available depends on what<br />server you’re using.<br />$HTTP_SERVER_VARS Same as $_SERVER.<br />$_ENV Contains information provided by your operating<br />system, such as the operating system name, the<br />system drive, and the path to your temp directory.<br />This info varies depending on your operating<br />system.<br />$HTTP_ENV_VARS Same as $_ENV.<br />124 Part II: Variables and Data<br />Using $_SERVER and $_ENV<br />The $_SERVER and $_ENV arrays contain different information, depending on<br />the server and operating system you’re using. You can see what information<br />is in the arrays for your particular server and operating system by using the<br />following statements:<br />foreach($_SERVER as $key =&gt;$value)<br />{<br />echo “Key=$key, Value=$value\n”;<br />}<br />The output includes such lines as the following:<br />Key=DOCUMENT_ROOT, Value=c:/program files/apache<br />group/apache/htdocs<br />Key=PHP_SELF, Value=/test.php<br />The DOCUMENT_ROOT element shows the path to the directory where Apache<br />expects to find the Web page files.<br />The PHP_SELF element shows the file that contains the script that is currently<br />running.<br />You can see the information in the $_ENV array by using the phpinfo() statement<br />with a 16 to specify the environmental variables, as follows:<br />phpinfo(16);<br />Built-in arrays are available only if track-vars is enabled. As of PHP 4.0.3,<br />track-vars is always enabled, unless the PHP administrator deliberately<br />turns track-vars off when installing PHP. It’s rare that track-vars would<br />be turned off. If the built-in arrays don’t seem to be available, check with<br />phpinfo() to make sure that track-vars is turned on. If it’s turned off, PHP<br />has to be reinstalled.<br />Using $argv and $argc<br />Sometimes you want to pass information into a script from the outside. One<br />way to do this is to pass the information to the script on the command line<br />when you start the script. You rarely want to do this when using PHP for the<br />Web, but you may want to do this when running PHP CLI from the command<br />line. For example, suppose you write a script that can add any two numbers<br />125 Chapter 6: Storing Data in Groups by Using Arrays<br />together and you want to pass the two numbers into the script when you<br />start it. You can give PHP the two numbers you want it to add together when<br />you start the script, on the command line, as follows:<br />php add.php 2 3<br />In this statement, the script is named add.php, and 2 and 3 are the numbers<br />you want the script to add together. These numbers are available inside the<br />script in an array called $argv. This array contains all the information on the<br />command line, as follows:<br />$argv[0]=add.php<br />$argv[1]=2<br />$argv[2]=3<br />So, $argv always contains at least one element — the script name.<br />Then, in your script, you can use the following statements:<br />$sum = $argv[1] + $argv[2];<br />echo $sum;<br />The output is the following:<br />5<br />Another variable is also available called $argc. This variable stores the number<br />of elements in $argv. Thus, $argc always equals at least 1, which is the name<br />of the script. In the preceding example, $argc equals 3.<br />126 Part II: Variables and Data<br />Part III<br />Basic PHP<br />Programming<br />In this part . . .<br />In this part, you find out how to write complete PHP<br />scripts. You discover how to combine simple statements<br />into a finished script. You find out about complex<br />statements that allow you to write scripts that perform<br />complex tasks. You see the usefulness of reusing code and<br />find out how to write code that can be reused. When you<br />finish this part, you will know everything you need to<br />know to write useful and complex PHP scripts.<br />Chapter 7<br />Controlling the Flow of the Script<br />In This Chapter<br /> Changing the order in which statements are executed<br /> Setting up conditions<br /> Joining simple conditions to make complex conditions<br /> Using conditions in conditional statements and loops<br />Writing if statements<br /> Building and using loops for repeated statements<br /> Breaking out of loops<br />PHP scripts are a series of instructions in a file. PHP begins at the top<br />of the file and executes each instruction, in order, as it comes to it.<br />However, some scripts need to be more complicated. You may want your<br />script to display one page to new customers and a different page to existing<br />customers. Or you may need to display a list of phone numbers by executing<br />a single echo statement repeatedly, once for each phone number. This chapter<br />describes how to change the order in which simple statements are executed<br />by using complex statements such as conditional statements or loops.<br />Changing the Order of<br />Statement Execution<br />Simple statements in PHP are executed one after another from the beginning<br />of the script to the end. For example, the following statements in a script are<br />executed in order:<br />$a = “Good Morning”;<br />echo $a;<br />$a = “Good Afternoon”;<br />echo $a;<br />To change the order of execution of these statements, you have to change the<br />order of the statements themselves, as follows:<br />130 Part III: Basic PHP Programming<br />$a = “Good Afternoon”;<br />echo $a;<br />$a = “Good Morning”;<br />echo $a;<br />However, suppose you want to display the appropriate greeting for the time<br />of day. You want to echo Good Morning if it’s before noon, and you want to<br />echo Good Afternoon if it’s after noon. In other words, you want to do the<br />following:<br />if (time is before noon)<br />{<br />$a = Good Morning;<br />echo $a;<br />}<br />or else if (time is after noon)<br />{<br />$a = Good Afternoon;<br />echo $a;<br />}<br />To display the appropriate greeting, you need a complex statement that tests<br />the condition of time. PHP provides two types of complex statements that<br />enable you to perform tasks like this — tasks that change the order in which<br />statements are executed:<br /> Conditional statements: Sometimes you need to set up statements that<br />execute only when certain conditions are met. For example, you may<br />want to provide your catalog only to customers who have paid their bills<br />and not to customers who owe you money. This type of statement is<br />called a conditional statement. The PHP conditional statements are the<br />if statement and the switch statement.<br /> Looping statements: Frequently you need to set up a block of statements<br />that is repeated. For example, you may want to send an e-mail message to<br />all your customers. To do that, you can use two statements: one that gets<br />the customer’s e-mail address from the database and one that sends the<br />customer an e-mail message. You would need to repeat these two statements<br />for every customer in the database. The feature that enables you<br />to execute statements repeatedly is called a loop. Three types of loops<br />are for loops, while loops, and do..while loops.<br />Both types of complex statements execute a block of statements based on a<br />condition. That is, if a condition is true, the block of statements executes. In<br />conditional statements, the block of statements executes once. For example,<br />if the time is after noon, the script echoes Good Afternoon. In loops, the block<br />of statements executes repeatedly, until the condition is no longer true. For<br />example, if another customer in the database has not yet received an e-mail<br />message, send that person one. The loop repeats this process as long as there<br />is another customer who has not received an e-mail.<br />131 Chapter 7: Controlling the Flow of the Script<br />Setting Up Conditions<br />Conditions are expressions that PHP tests or evaluates to see whether they<br />are true or false. Conditions are used in complex statements to determine<br />whether or not a block of simple statements should be executed. To set up<br />conditions, you compare values. Some questions you may ask in comparing<br />values for conditions are as follows:<br /> Are two values equal? Is Sally’s last name the same as Bobby’s last<br />name? Or, is Nick 15 years old? (Does Nick’s age equal 15?)<br /> Is one value larger or smaller than another? Is Nick younger than<br />Bobby? Or, did Sally’s house cost more than a million dollars?<br /> Does a string match a pattern? Does Bobby’s name begin with an S?<br />Does the zip code have five numeric characters?<br />You can also set up conditions in which you ask two or more questions. For<br />example, you may ask: Is Nick older than Bobby and is Nick younger than<br />Sally? Or you may ask: Is today Sunday and is today sunny? Or you may ask:<br />Is today Sunday or is today Monday?<br />Using comparison operators<br />PHP offers several comparison operators that you can use to compare<br />values. Table 7-1 shows these comparison operators.<br />Table 7-1 Comparison Operators<br />Operator What It Means<br />== Are the two values equal in value?<br />=== Are the two values equal in both value and data type?<br />&gt; Is the first value larger than the second value?<br />&gt;= Is the first value larger than or equal to the second value?<br />&lt; Is the first value smaller than the second value?<br />&lt;= Is the first value smaller than or equal to the second value?<br />!=, &lt;&gt; Are the two values not equal to each other in value?<br />!== Are the two values not equal to each other in either value or<br />data type?<br />132 Part III: Basic PHP Programming<br />You can compare both numbers and strings. Strings are compared alphabetically,<br />with all uppercase characters coming before any lowercase characters.<br />For example, SS comes before Sa. Punctuation characters also have an order,<br />and one character can be found to be larger than another character. However,<br />comparing a comma to a period doesn’t have much practical value.<br />Strings are compared based on their ASCII code. In the ASCII character set,<br />each character is assigned an ASCII code that corresponds to a number<br />between 0 and 127. When strings are compared, they are compared based<br />on this code. For example, the number that represents the comma is 44. The<br />period corresponds to 46. Therefore, if a period and a comma are compared,<br />the period is seen as larger.<br />The following are some valid comparisons that PHP can test to determine<br />whether they are true:<br /> $a == $b<br /> $age != 21<br /> $ageNick &lt; $ageBobby<br /> $house_price &gt;= 1000000<br />The comparison operator that asks whether two values are equal consists<br />of two equal signs (==). One of the most common mistakes is to use a single<br />equal sign for a comparison. A single equal sign puts the value into the variable.<br />Thus, a statement like if ($weather = “raining”) would set<br />$weather to raining rather than check whether it already equaled raining,<br />and would always be true.<br />PHP tests comparisons by evaluating them and returning a Boolean value,<br />either TRUE or FALSE. For example, look at the following comparison:<br />$a == $b<br />If $a=1 and $b=1, the comparison returns TRUE. If $a =1 and $b =2, the comparison<br />returns FALSE.<br />If you write a negative (by using !), the negative condition is true. Look at the<br />following comparison:<br />$age != 21<br />The condition is that $age does not equal 21. That’s the condition that is<br />being tested. Therefore, if $age = 20, the comparison is TRUE.<br />133 Chapter 7: Controlling the Flow of the Script<br />Checking variable content<br />Sometimes you just need to know whether a variable exists or what type of<br />data is in the variable. Here are some common ways to test variables:<br />isset($varname) # True if variable is set, even if<br />nothing is stored in it.<br />empty($varname) # True if value is 0 or is a string with<br />no characters in it or is not set.<br />You can also test what type of data is in the variable. For example, to see if<br />the value is an integer, you can use the following:<br />is_int($number)<br />The comparison is TRUE if the value in $number is an integer. Some other<br />tests provided by PHP are as follows:<br /> is_array($var2): Checks to see if $var2 is an array<br /> is_float($number): Checks to see if $number is a floating point<br />number<br /> is_null($var1): Checks to see if $var1 is equal to 0<br /> is_numeric($string): Checks to see if $string is a numeric string<br /> is_string($string): Checks to see if $string is a string<br />You can test for a negative, as well, by using an exclamation point (!) in front<br />of the expression. For example, the following statement returns TRUE if the<br />variable does not exist at all:<br />!isset($varname)<br />Pattern matching with regular expressions<br />Sometimes you need to compare character strings to see whether they fit<br />certain characteristics, rather than to see whether they match exact values.<br />For example, you may want to identify strings that begin with S or strings<br />that have numbers in them. For this type of comparison, you compare the<br />string to a pattern. These patterns are called regular expressions.<br />You have probably used some form of pattern matching in the past. When you<br />use an asterisk (*) as a wild card when searching for files (dir ex*.doc or<br />ls ex*.txt, for example), you’re pattern matching. For example, ex*.txt is<br />a pattern. Any string that begins with ex and ends with the string .txt, with<br />any characters in between the ex and the .txt, matches the pattern. The<br />strings exam.txt, ex33.txt, and ex3x4.txt all match the pattern. Using<br />regular expressions is just a more complicated variation of using wild cards.<br />One common use for pattern matching is to check the input from a Web page<br />form. If the information input doesn’t match a specific pattern, it may not be<br />something you want to store in your database. For example, if the user types<br />a zip code into your form, you know the format needs to be five numbers or<br />a zip + 4. So, you can check the input to see if it fits the pattern. If it doesn’t,<br />you know it’s not a valid zip code, and you can ask the user to type in the correct<br />information.<br />Using special characters in patterns<br />Patterns consist of literal characters and special characters. Literal characters<br />are normal characters, with no special meaning. An e is an e, for example,<br />with no meaning other than that it’s one of 26 letters in the alphabet.<br />Special characters, on the other hand, have special meaning in the pattern,<br />such as the asterisk (*) when used as a wild card. Table 7-2 shows the special<br />characters that you can use in patterns.<br />Table 7-2 Special Characters Used in Patterns<br />Character Meaning Example Matches Does Not<br />Match<br />^ Beginning ^e exam math exam<br />of line<br />$ End of line m$ exam exams<br />. Any single .. up, do A, 2<br />character Longer words<br />match because<br />they contain a<br />string of two<br />characters.<br />? The preceding ger?m germ, gem geam<br />character is<br />optional<br />( ) Groups literal g(er)m germ Gem,<br />characters into grem<br />a string that<br />must be<br />matched exactly<br />[ ] Encloses a set g[er]m gem, grm germ, gel<br />of optional literal<br />characters<br />134 Part III: Basic PHP Programming<br />135 Chapter 7: Controlling the Flow of the Script<br />Character Meaning Example Matches Does Not<br />Match<br />[^] Encloses a set g[^er]m gym, gum gem, grem,<br />of nonmatching germ<br />optional characters<br />- Represents all the g[a-c]m gam, gbm, gcm gdm, gxm,<br />characters between gal<br />two characters (a<br />range of possible<br />characters)<br />+ One or more of the bldg bldg111, bldg,<br />preceding items [1-3]+ bldg132 bldg555<br />* Zero or more of the ge*m gm, geeem germ, grm<br />preceding items<br />{n} Repeat n times ge{5}m geeeeem geeeem,<br />geeeeeem<br />{n1,n2} Specifies a range a{2,5} aa, aaa, aaaa, 1, a3<br />of repetitions of 145aaaaa<br />the preceding<br />character(s).<br />\ The following g\*m g*m gem, germ<br />character is literal<br />( | | ) A set of alternate (Sam| Samuel Go Sarah,<br />strings Sally) Sally Salmon<br />Considering some example patterns<br />Literal and special characters are combined to make patterns, sometimes long<br />complicated patterns. A string is compared to the pattern, and if it matches,<br />the comparison is true. Some example patterns follow, with a breakdown of<br />the pattern and some sample matching and non-matching strings:<br />Example 1<br />^[A-Za-z].*<br />This pattern defines strings that begin with a letter and have two parts:<br /> ^[A-Za-z] The first part of the pattern dictates that the beginning of<br />the string must be a letter (either uppercase or lowercase).<br /> .* The second part of the pattern tells PHP the string of characters can<br />be one or more characters long.<br />136 Part III: Basic PHP Programming<br />The expression ^[A-Za-z].* matches the following strings: play it<br />again, Sam and I.<br />The expression ^[A-Za-z].* does not match the following strings: 123 and ?.<br />Example 2<br />Dear (Kim|Rikki)<br />This pattern defines two alternate strings and has two parts:<br /> Dear The first part of the pattern is just literal characters.<br /> (Kim|Rikki) The second part defines either Kim or Rikki as matching<br />strings.<br />The expression Dear (Kim|Rikki) matches the following strings: Dear Kim<br />and My Dear Rikki.<br />The expression Dear (Kim|Rikki) does not match the following strings:<br />Dear Bobby and Kim.<br />Example 3<br />^[0-9]{5}(\-[0-9]{4})?$<br />This pattern defines any zip code and has several parts:<br /> ^[0-9]{5} The first part of the pattern describes any string of five<br />numbers.<br /> \- The slash indicates that the hyphen is a literal.<br /> [0-9]{4} This part of the pattern tells PHP that the next characters<br />should be a string of numbers consisting of four characters.<br /> ( )? These characters group the last two parts of the pattern and make<br />them optional.<br /> $ The dollar sign dictates that this string should end (no characters are<br />allowed after the pattern).<br />The expression ^[0-9]{5}(\-[0-9]{4})?$ matches the following strings:<br />90001 and 90002-4323.<br />The expression ^[0-9]{5}(\-[0-9]{4})?$ does not match the following<br />strings: 9001 and 12-4321.<br />Example 4<br />^.+@.+\.com$<br />137 Chapter 7: Controlling the Flow of the Script<br />This pattern defines any string with @ embedded that ends in .com. In other<br />words, it defines an e-mail address. This expression has several parts:<br /> ^.+ The first part of the pattern describes any string of one or more<br />characters that precedes the @.<br /> @ This is a literal @ (at sign). @ is not a special character and does not<br />need to be preceded by a \.<br /> .+ This is any string of one or more characters.<br /> \. The slash indicates that PHP should look for a literal dot.<br /> com$ This defines the literal string com at the end of the string, and the<br />$ marks the end of the string.<br />The expression ^.+@.+\.com$ matches the following strings: you@your<br />company.com and johndoe@somedomain.com.<br />The expression ^.+@.+\.com$ does not match the following strings: you@<br />yourcompany.net, you@.com, and @you.com.<br />Comparing strings to patterns<br />You can compare a string to a pattern by using ereg. The general format is as<br />follows:<br />ereg(“pattern”,value);<br />For example, to check the name that a user typed in a form, compare the<br />name (stored in the variable $name) to a pattern as follows:<br />ereg(“^[A-Za-z’ -]+$”,$name)<br />The pattern in this statement does the following:<br /> Uses ^ and $ to signify the beginning and end of the string. That means<br />that all the characters in the string must match the pattern.<br /> Encloses all the literal characters that are allowed in the string in [ ]. No<br />other characters are allowed. The allowed characters are upper and<br />lower case letters, an apostrophe (‘), a blank space, and a hyphen (-).<br />You can specify a range of characters using a hyphen within the [ ]. When<br />you do that, as in A-Z above, the hyphen does not represent a literal character.<br />Since you want the hyphen included as a literal character that is<br />allowed in your string, you need to add a hyphen that is not between any<br />two other characters. In this case, the hyphen is included at the end of the<br />list of literal characters,<br /> Follows the list of literal characters in the [ ] with a +. The plus sign<br />means that the string can contain any number of the characters inside<br />the [ ], but must contain at least one character.<br />138 Part III: Basic PHP Programming<br />Joining multiple comparisons<br />Often you need to ask more than one question to determine your condition.<br />For example, suppose your company offers catalogs for different products in<br />different languages. You need to know which type of product catalog the customer<br />wants to see and which language he or she needs to see it in. This<br />requires you to join comparisons, which have the following the general<br />format:<br />comparison1 and|or|xor comparison2 and|or|xor comparison3<br />and|or|xor &#8230;<br />Comparisons are connected by one of the following three words:<br /> and: Both comparisons are true.<br /> or: One of the comparisons or both of the comparisons are true.<br /> xor: One of the comparisons is true but not both of the comparisons.<br />Table 7-3 shows some examples of multiple comparisons.<br />Table 7-3 Multiple Comparisons<br />Condition Is True If . . .<br />$ageBobby == 21 Bobby is 21 or 22 years of age.<br />or $ageBobby == 22<br />$ageSally &gt; 29 and Sally is older than 29 and lives in Oregon.<br />$state ==”OR”<br />$ageSally &gt; 29 Sally is older than 29 or lives in Oregon or both.<br />or $state == “OR”<br />$city == “Reno” The city is Reno or the state is Oregon, but<br />xor $state == “OR” not both.<br />$name != “Sam” The name is anything except Sam and age is<br />and $age &lt; 13 under 13 years of age.<br />You can string together as many comparisons as necessary. The comparisons<br />using and are tested first, the comparisons using xor are tested next, and the<br />comparisons using or are tested last. For example, the following condition<br />includes three comparisons:<br />$resCity == “Reno” or $resState == “NV” and $name == “Sally”<br />139 Chapter 7: Controlling the Flow of the Script<br />If the customer’s name is Sally and she lives in NV, this statement is true. The<br />statement is also true if she lives in Reno, regardless of what her name is.<br />This condition is not true if she lives in NV but her name is not Sally. You get<br />these results because the script checks the condition in the following order:<br />1. The and is compared.<br />The script checks $resState to see if it equals NV and checks $name to<br />see if it equals Sally. If both match, the condition is true, and the script<br />does not need to check or. If only one or neither of the variables equal<br />the designated value, the testing continues.<br />2. The or is compared.<br />The script checks $resCity to see if it equals Reno. If it does, the condition<br />is true. If it doesn’t, the condition is false.<br />You can change the order in which comparisons are made by using parentheses.<br />The connecting word inside the parentheses is evaluated first. For example,<br />you can rewrite the previous statement with parentheses as follows:<br />($resCity == “Reno or $resState == “NV”) and $name == “Sally”<br />The parentheses change the order in which the conditions are checked. Now<br />the or is checked first because it is inside the parentheses. This condition<br />statement is true if the customer’s name is Sally and she lives in either Reno<br />or NV. You get these results because the script checks the condition as follows:<br />1. The or is compared.<br />The script checks to see if $resCity equals Reno or $resState equals<br />NV. If it does not, the entire condition is false, and testing stops. If it<br />does, this part of the condition is true. However, the comparison on the<br />other side of the and must also be true, so the testing continues.<br />2. The and is compared.<br />The script checks $name to see if it equals Sally. If it does, the condition<br />is true. If it does not, the condition is false.<br />Use parentheses liberally, even when you believe you know the order of the<br />comparisons. Unnecessary parentheses can’t hurt, but comparisons that<br />have unexpected results can.<br />If you’re familiar with other languages, such as C, you may have used || (for<br />or) and &amp;&amp; (for and) in place of the words. The || and &amp;&amp; work in PHP as well.<br />The statement $a &lt; $b &amp;&amp; $c &gt; $b is just as valid as the statement $a &lt;<br />$b and $c &gt; $b. The || is checked before the word or, and the &amp;&amp; is<br />checked before the word and.<br />140 Part III: Basic PHP Programming<br />Using Conditional Statements<br />A conditional statement executes a block of statements only when certain conditions<br />are true. Here are two useful types of conditional statements:<br /> An if statement: Sets up a condition and tests it. If the condition is true,<br />a block of statements is executed.<br /> A switch statement: Sets up a list of alternative conditions. It tests for<br />the true condition and executes the appropriate block of statements.<br />Using if statements<br />An if statement tests conditions, executing a block of statements when a condition<br />is true. The general format of an if conditional statement is as follows:<br />if ( condition )<br />{<br />block of statements<br />}<br />elseif ( condition )<br />{<br />block of statements<br />}<br />else<br />{<br />block of statements<br />}<br />The if statement consists of three sections:<br /> if: This section is required. It tests a condition:<br />• If the condition is true: The block of statements is executed. After<br />the statements are executed, the script moves to the next instruction<br />following the conditional statement; if the conditional statement<br />contains any elseif or else sections, the script skips over<br />them.<br />• If the condition is not true: The block of statements is not executed.<br />The script skips to the next instruction, which can be an<br />elseif, an else, or the next instruction after the if conditional<br />statement.<br /> elseif: This section is optional. You can use more than one elseif section<br />if you want. It also tests a condition:<br />• If the condition is true: The block of statements is executed.<br />After executing the block of statements, the script goes to the next<br />instruction following the conditional statement; if the if statement<br />141 Chapter 7: Controlling the Flow of the Script<br />contains any additional elseif sections or an else section, the<br />script skips over them.<br />• If the condition is not true: The block of statements is not executed.<br />The script skips to next instruction, which can be an elseif, an<br />else, or the next instruction after the if conditional statement.<br /> else: This section is also optional. Only one else section is allowed.<br />This section does not test a condition, rather it executes the block of<br />statements. If the script has entered this section, it means that the if<br />section and all the elseif sections are not true.<br />Here’s an example. Pretend you’re a teacher. The following if statement,<br />when given a test score, sends your student a grade and a snappy little text<br />message. It uses all three sections of the if statement, as follows:<br />if ($score &gt; 92 )<br />{<br />$grade = “A”;<br />$message = “Excellent!”;<br />}<br />elseif ($score &lt;= 92 and $score &gt; 83 )<br />{<br />$grade = “B”;<br />$message = “Good!”;<br />}<br />elseif ($score &lt;= 83 and $score &gt; 74 )<br />{<br />$grade = “C”;<br />$message = “Okay”;<br />}<br />elseif ($score &lt;= 74 and $score &gt; 62 )<br />{<br />$grade = “D”;<br />$message = “Uh oh!”;<br />}<br />else<br />{<br />$grade = “F”;<br />$message = “Doom is upon you!”;<br />}<br />echo $message.”\n”;<br />echo “Your grade is $grade\n”;<br />The if conditional statement proceeds as follows:<br />1. The value in $score is compared to 92.<br />If $score is greater than 92, $grade is set to A, $message is set to<br />Excellent!, and the script skips to the echo statement. If $score is 92<br />or less, $grade and $message are not set, and the script skips to the<br />elseif section.<br />142 Part III: Basic PHP Programming<br />2. The value in $score is compared to 92 and to 83.<br />If $score is 92 or less and greater than 83, $grade and $message are<br />set, and the script skips to the echo statement. If $score is 83 or less,<br />$grade and $message are not set, and the script skips to the second<br />elseif section.<br />3. The value in $score is compared to 83 and to 74.<br />If $score is 83 or less and greater than 74, $grade and $message are<br />set, and the script skips to the echo statement. If $score is 74 or less,<br />$grade and $message are not set, and the script skips to the next<br />elseif section.<br />4. The value in $score is compared to 74 and to 62.<br />If $score is 74 or less and greater than 62, $grade and $message are set,<br />and the script skips to the echo statement. If $score is 62 or less, $grade<br />and $message are not set, and the script skips to the else section.<br />5. $grade is set to F, and $message is set to Doom is upon you!.<br />The script continues to the echo statement.<br />When the block to be executed by any section of the if conditional statement<br />contains only one statement, the curly braces are not needed. For<br />example, say the preceding example had only one statement in the blocks,<br />as follows:<br />if ($grade &gt; 92 )<br />{<br />$grade = “A”;<br />}<br />You could write it as follows:<br />if ($grade &gt; 92 )<br />$grade = “A”;<br />This shortcut can save some typing, but when several if statements are<br />used, it can lead to confusion.<br />Negating if statements<br />You can write an if statement so that the statement block is executed when<br />the condition is false by putting an exclamation point (!) at the beginning of<br />the condition. For example, you can use the following if statement:<br />if (ereg(“^S[a-z]*”,$string))<br />{<br />$list[]=$string.”\n”;<br />}<br />143 Chapter 7: Controlling the Flow of the Script<br />This if statement creates an array of strings that begin with S. More specifically,<br />if $string matches a pattern that specifies one uppercase S at the<br />beginning, followed by a number of lowercase letters, the statement block is<br />executed. However, if you were to place an exclamation point at the beginning<br />of the condition, things would change considerably. For example, say<br />you use the following statements instead:<br />if (!egreg(“^S[a-z]*”,$string)<br />{<br />$list[]=$string.”\n”;<br />}<br />In this case, the array $list contains all the strings except those that begin<br />with S. In this case, because a ! appears at the beginning of the condition, the<br />condition is “$string does not match a pattern that begins with S.” So, when<br />$string does not begin with S, the condition is true.<br />Nesting if statements<br />You can have an if conditional statement inside another if conditional<br />statement. Putting one statement inside another is called nesting. For example,<br />suppose you need to contact all your customers who live in Idaho. You<br />plan to send e-mail to those who have e-mail addresses and send letters to<br />those who do not have e-mail addresses. You can identify the groups of customers<br />by using the following nested if statements:<br />if ( $custState == “ID” )<br />{<br />if ( $EmailAdd = “” )<br />{<br />$contactMethod = “letter”;<br />}<br />else<br />{<br />$contactMethod = “email”;<br />}<br />}<br />else<br />{<br />$contactMethod = “none needed”;<br />}<br />These statements first check to see if the customer lives in Idaho. If the customer<br />does live in Idaho, the script tests for an e-mail address. If the e-mail<br />address is blank, the contact method is set to letter. If the e-mail address<br />is not blank, the contact method is email. If the customer does not live in<br />Idaho, the else section sets the contact method to indicate that the customer<br />will not be contacted at all.<br />144 Part III: Basic PHP Programming<br />Using switch statements<br />For most situations, the if conditional statement works best. However,<br />sometimes you have a list of conditions and want to execute different statements<br />for each condition. For example, suppose your script computes sales<br />tax. How do you handle the different state sales tax rates? The switch statement<br />was designed for such situations.<br />The switch statement tests the value of one variable and executes the block<br />of statements for the matching value of the variable. The general format is as<br />follows:<br />switch ( $variablename )<br />{<br />case value :<br />block of statements;<br />break;<br />case value :<br />block of statements;<br />break;<br />&#8230;<br />default:<br />block of statements;<br />break;<br />}<br />The switch statement tests the value of $variablename. The script then<br />skips to the case section for that value and executes statements until it<br />reaches a break statement or the end of the switch statement. If there is no<br />case section for the value of $variablename, the script executes the default<br />section. You can use as many case sections as you need. The default section<br />is optional. If you use a default section, it’s customary to put the default section<br />at the end, but as far as PHP is concerned, it can go anywhere.<br />The following statements set the sales tax rate for different states:<br />switch ( $custState )<br />{<br />case “OR” :<br />$salestaxrate = 0;<br />break;<br />case “CA” :<br />$salestaxrate = 1.0;<br />break;<br />default:<br />$salestaxrate = .5;<br />break;<br />}<br />$salestax = $orderTotalCost * $salestaxrate;<br />In this case, the tax rate for Oregon is 0, the tax rate for California is 100 percent,<br />and the tax rate for all the other states is 50 percent. The switch statement<br />looks at the value of $custState and skips to the section that matches<br />the value. For example, if $custState is TX, the script executes the default<br />section and sets $salestaxrate to .5. After the switch statement, the<br />script computes $salestax at .5 times the cost of the order.<br />The break statements are essential in the case section. If a case section<br />does not include a break statement, the script does not stop executing at<br />the end of the case section. The script continues executing statements past<br />the end of the case section, on to the next case section, and continues until<br />it reaches a break statement or the end of the switch statement. This is a<br />problem for every case section except the last one because it will execute<br />sections following the appropriate section.<br />The last case section in a switch statement doesn’t actually require a break<br />statement. You can leave it out. However, it’s a good idea to include it for clarity<br />and consistency.<br />Repeating Actions by Using Loops<br />Loops are used frequently in scripts to set up a block of statements that<br />repeat. The loop can repeat a specified number of times. For example, a loop<br />that echoes all the state capitals needs to repeat 50 times. Or the loop can<br />repeat until a certain condition is met. For example, a loop that echoes the<br />names of all the files in a directory needs to repeat until it runs out of files,<br />regardless of how many files there are. Here are three types of loops:<br /> A for loop: Sets up a counter; repeats a block of statements until the<br />counter reaches a specified number<br /> A while loop: Sets up a condition; checks the condition, and if it’s true,<br />repeats a block of statements until the condition becomes false<br /> A do..while loop: Sets up a condition; executes a block of statements;<br />checks the condition; if the condition is true, repeats the block of statements<br />until the condition becomes false<br />I describe each of these loops in detail in the following few sections.<br />145 Chapter 7: Controlling the Flow of the Script<br />146 Part III: Basic PHP Programming<br />Using for loops<br />The most basic for loops are based on a counter. You set the beginning value<br />for the counter, set the ending value, and set how the counter is incremented<br />each time the statement block is executed. The general format is as follows:<br />for (startingvalue;endingcondition;increment)<br />{<br />block of statements;<br />}<br />Within the for statement, you need to fill in the following values:<br /> startingvalue: The startingvalue is a statement that sets up a variable<br />to be your counter and sets it to your starting value. For example,<br />the statement $i=1; sets $i as the counter variable and sets it equal to 1.<br />Frequently, the counter variable is started at 0 or 1. The starting value can<br />be a number, a combination of numbers (like 2 + 2), or a variable.<br /> endingcondition: The endingcondition is a statement that sets your<br />ending value. As long as this statement is true, the block of statements<br />keeps repeating. When this statement is not true, the loop ends. For<br />example, the statement $i&lt;10; sets the ending value for the loop to 10.<br />When $i is equal to 10, the statement is no longer true (because $i is no<br />longer less than 10), and the loop stops repeating. The statement can<br />include variables, such as $i&lt;$size;.<br /> increment: A statement that increments your counter. For example, the<br />statement $i++; adds 1 to your counter at the end of each block of statements.<br />You can use other increment statements, such as $i=+1; or $i—;.<br />A basic for loop sets up a variable, like $i, that is used as a counter. This<br />variable has a value that changes during each loop. The variable $i can be<br />used in the block of statements that is repeating. For example, the following<br />simple loop displays Hello World! three times:<br />for ($i=1;$i&lt;=3;$i++)<br />{<br />echo “$i. Hello World!&lt;br&gt;”;<br />}<br />The statements in the block do not need to be indented. PHP doesn’t care<br />whether they’re indented. However, indenting the blocks makes it much<br />easier for you to understand the script.<br />The following is the output from these statements:<br />1. Hello World!<br />2. Hello World!<br />3. Hello World!<br />147 Chapter 7: Controlling the Flow of the Script<br />Nesting for loops<br />You can nest for loops inside of for loops. Suppose you want to print out<br />the times tables from 1 to 9. You can use the following statements:<br />for($i=1;$i&lt;=9;$i++)<br />{<br />echo “\nMultiply by $i \n”;<br />for($j=1;$j&lt;=9;$j++)<br />{<br />$result = $i * $j;<br />echo “$i x $j = $result\n”;<br />}<br />}<br />The output is as follows:<br />Multiply by 1<br />1 x 1 = 1<br />1 x 2 = 2<br />&#8230;<br />1 x 8 = 8<br />1 x 9 = 9<br />Multiply by 2<br />2 x 1 = 2<br />2 x 2 = 4<br />&#8230;<br />2 x 8 = 16<br />2 x 9 = 18<br />Multiply by 3<br />3 x 1 = 3<br />and so on.<br />Designing advanced for loops<br />The structure of a for loop is quite flexible and allows you to build loops for<br />almost any purpose. A for loop has this general format:<br />for (beginning statements; conditional statements; ending<br />statements)<br />{<br />block of statements;<br />}<br />The statements within a for loop have the following roles:<br /> The beginning statements execute once at the start of the loop. They<br />can be statements that set any needed starting values or other statements<br />that you want to execute before your loop starts running.<br />148 Part III: Basic PHP Programming<br /> The conditional statements are tested for each iteration of your loop.<br /> The ending statements execute once at the end of the loop. They can be<br />statements that increment your values or any other statements that you<br />want to execute at the end of your loop.<br />Each statement section is separated by a semicolon (;). Each section can contain<br />as many statements as needed, separated by commas. Any section can<br />be empty.<br />The following loop has statements in all three sections:<br />$t = 0;<br />for ($i=0,$j=1;$t&lt;=4;$i++,$j++)<br />{<br />$t = $i + $j;<br />echo “$t&lt;br&gt;”;<br />}<br />The two statements in the first section are the beginning statements; the conditional<br />statement in the second section is the conditional statements; and<br />the two statements in the third section are the ending statements.<br />The output of these statements is as follows:<br />135<br />The loop is executed in the following order:<br />1. The beginning section containing two statements is executed.<br />$i is set to 0, and $j is set to 1.<br />2. The conditional section containing one statement is evaluated.<br />Is $t less than or equal to 4? Yes, so the statement is true. The loop continues<br />to execute.<br />3. The statements in the statement block are executed.<br />$t becomes equal to $i plus $j, which is 0 + 1, which equals 1. Then $t<br />is echoed to give the output 1.<br />4. The ending section containing two statements ($i++ and $j++) is<br />executed.<br />Both $i and $j are incremented by one, so $i now equals 1, and $j now<br />equals 2.<br />5. The conditional section is evaluated.<br />Is $t less than or equal to 4? Because $t is equal to 1 at this point, the<br />statement is true. The loop continues to execute.<br />149 Chapter 7: Controlling the Flow of the Script<br />6. The statements in the statement block are executed.<br />$t becomes equal to $i plus $j, which is 1 + 2, which equals 3. Then $t<br />is echoed to give the output 3.<br />7. The ending section containing two statements ($i++ and $j++) is<br />executed.<br />Both $i and $j are incremented by one, so $i now equals 2, and $j now<br />equals 3.<br />8. The conditional section is evaluated.<br />Is $t less than or equal to 4? Because $t now equals 3, the statement is<br />true. The loop continues to execute.<br />9. The statements in the statement block are executed.<br />$t becomes equal to $i plus $j, which is 2 + 3, which equals 5. Then $t<br />is echoed to give the output 5.<br />10. The ending section containing two statements ($i++ and $j++) is<br />executed.<br />Both $i and $j are incremented by 1, so $i now equals 2, and $j now<br />equals 3.<br />11. The conditional section is evaluated.<br />Is $t less than or equal to 4? Because $t now equals 5, the statement is<br />not true. The loop does not continue to execute. The loop ends, and the<br />script continues to the next statement after the end of the loop.<br />Using while loops<br />A while loop continues repeating as long as certain conditions are true. The<br />loop works as follows:<br />1. You set up a condition.<br />2. The condition is tested at the top of each loop.<br />3. If the condition is true, the loop repeats. If the condition is not true, the<br />loop stops.<br />The following is the general format of a while loop:<br />while ( condition )<br />{<br />block of statements<br />}<br />150 Part III: Basic PHP Programming<br />The following statements set up a while loop that looks through an array for<br />an apple:<br />$fruit = array ( “orange”, “apple”, “grape” );<br />$testvar = “no”;<br />$k = 0;<br />while ( $testvar != “yes” )<br />{<br />if ($fruit[$k] == “apple” )<br />{<br />$testvar = “yes”;<br />echo “apple\n”;<br />}<br />else<br />{<br />echo “$fruit[$k] is not an apple\n”;<br />}<br />$k++;<br />}<br />These statements generate the following output:<br />orange is not an apple<br />apple<br />The script executes the statements as follows:<br />1. The variables are set before starting the loop.<br />$fruit is an array with three values, $testvar is a test variable set to<br />“no”, and $k is a counter variable set to 0.<br />2. The loop starts by testing whether $testvar != “yes” is true.<br />Because $testvar was set to “no”, the statement is true, so the loop<br />continues.<br />3. The condition in the if statement is tested.<br />Is $fruit[$k] == “apple” true? At this point, $k is 0, so the script<br />checks $fruit[0]. Because $fruit[0] is “orange”, the statement is<br />not true. The statements in the if block are not executed, so the script<br />skips to the else statement.<br />4. The statement in the else block is executed.<br />The else block outputs the line “orange is not an apple”. This is<br />the first line of the output.<br />5. $k is incremented by one.<br />Now $k becomes equal to 1.<br />151 Chapter 7: Controlling the Flow of the Script<br />6. The bottom of the loop is reached.<br />Flow returns to the top of the loop.<br />7. The condition $testvar != “yes” is tested again.<br />Is $testvar != “yes” true? Because $testvar has not been changed<br />and is still set to “no”, it is true, so the loop continues.<br />8. The condition in the if statement is tested again.<br />Is $fruit[$k] == “apple” true? At this point, $k is 1, so the script<br />checks $fruit[1]. Because $fruit[1] is “apple”, the statement is<br />true. So the loop enters the if block.<br />9. The statements in the if block are executed.<br />These statements set $testvar to “yes” and output “apple”. This is<br />the second line of the output.<br />10. $k is incremented again.<br />Now $k equals 2.<br />11. The bottom of the loop is reached again.<br />Once again, the flow returns to the top of the loop.<br />12. The condition $testvar != “yes” is tested one last time.<br />Is $testvar != “yes” true? Because $testvar has been changed and<br />is now set to “yes”, it is not true. The loop stops.<br />It’s possible to write a while loop that is infinite — that is, a loop that loops<br />forever. You can easily, without intending to, write a loop in which the condition<br />is always true. If the condition never becomes false, the loop never ends.<br />For a discussion of infinite loops, see the section “Avoiding infinite loops,”<br />later in this chapter.<br />Using do..while loops<br />A do..while loop is very similar to a while loop. Like a while loop, a<br />do..while loop continues repeating as long as certain conditions are true.<br />Unlike while loops, however, those conditions are tested at the bottom of<br />each loop. If the condition is true, the loop repeats. When the condition is<br />not true, the loop stops.<br />The general format for a do..while loop is as follows:<br />do<br />{<br />block of statements<br />} while ( condition );<br />152 Part III: Basic PHP Programming<br />The following statements set up a loop that looks for an apple. This script<br />does the same thing as the script in the preceding section that uses a while<br />loop:<br />$fruit = array ( “orange”, “apple”, “grape” );<br />$testvar = “no”;<br />$k = 0;<br />do<br />{<br />if ($fruit[$k] == “apple” )<br />{<br />$testvar = “yes”;<br />echo “apple\n”;<br />}<br />else<br />{<br />echo “$fruit[$k] is not an apple\n”;<br />}<br />$k++;<br />} while ( $testvar != “yes” );<br />The output of these statements in a browser is as follows:<br />orange is not an apple<br />apple<br />This is the same output shown for the while loop example. The difference<br />between a while loop and a do..while loop is where the condition is checked.<br />In a while loop, the condition is checked at the top of the loop. Therefore, the<br />loop will never execute if the condition is never true. In the do..while loop,<br />the condition is checked at the bottom of the loop. Therefore, the loop always<br />executes at least once, even if the condition is never true.<br />For example, in the preceding loop that checks for an apple, suppose the<br />original condition is set to yes, instead of no, by using this statement:<br />$testvar = “yes”;<br />The condition tests false from the beginning. It is never true. In a while loop,<br />there is no output. The statement block never runs. However, in a do..while<br />loop, the statement block runs once before the condition is tested. Thus, the<br />while loop produces no output, but the do..while loop produces the following<br />output:<br />orange is not an apple<br />The do..while loop produces one line of output before the condition is<br />tested. It does not produce the second line of output because the condition<br />tests false.<br />153 Chapter 7: Controlling the Flow of the Script<br />Avoiding infinite loops<br />You can easily set up loops so that they never stop. These are called infinite<br />loops. They repeat forever. However, seldom does anyone create an infinite<br />loop intentionally. It is usually a mistake in the programming. For example,<br />a slight change to the script that sets up a while loop can make it into an<br />infinite loop.<br />Here is the script shown in the section, “Using while loops,” earlier in this<br />chapter, with a slight change:<br />$fruit = array ( “orange”, “apple”, “grape” );<br />$testvar = “no”;<br />while ( $testvar != “yes” )<br />{<br />$k = 0;<br />if ($fruit[$k] == “apple” )<br />{<br />$testvar = “yes”;<br />echo “apple\n”;<br />}<br />else<br />{<br />echo “$fruit[$k] is not an apple\n”;<br />}<br />$k++;<br />}<br />The small change is moving the statement $k = 0; from outside the loop to<br />inside the loop. This small change makes it into an endless loop. This changed<br />script has the following output:<br />orange is not an apple<br />orange is not an apple<br />orange is not an apple<br />orange is not an apple<br />&#8230;<br />This will repeat forever. Every time the loop runs, it resets $k to 0. Then it<br />gets $fruit[0] and echoes it. At the end of the loop, $k is incremented to 1.<br />However, when the loop starts again, $k is set back to 0. Consequently, only<br />the first value in the array, orange, is ever read. The loop never gets to the<br />apple, and $testvar is never set to “yes”. The loop is endless.<br />Don’t be embarrassed if you write an infinite loop. I guarantee that the best<br />programming guru in the world has written many infinite loops. It’s not a big<br />deal. If you are testing a script and get output repeating endlessly, there’s no<br />need to panic. Do one of the following:<br />154 Part III: Basic PHP Programming<br /> If you’re using PHP on a Web page: Wait. It will stop by itself in a short<br />time. The default time is 30 seconds, but the timeout period may have<br />been changed by the PHP administrator. You can also click the Stop<br />button on your browser to stop the display in your browser.<br /> If you’re using PHP CLI: Press Ctrl + C. This stops the script from running.<br />Sometimes the output will continue to display a little longer, but it<br />will stop very shortly.<br />Then figure out why the loop is repeating endlessly and fix it.<br />A common mistake that can result in an infinite loop is using a single equal<br />sign (=) when you mean to use double equal signs (==). The single equal sign<br />stores a value in a variable; the double equal signs test whether two values<br />are equal. The following condition using a single equal sign is always true:<br />while ($testvar = “yes”)<br />The condition simply sets $testvar equal to “yes”. This is not a question<br />that can be false. What you probably meant to write is this:<br />while ($testvar == “yes”)<br />This is a question asking whether $testvar is equal to “yes”, which can be<br />answered either true or false.<br />Another common mistake is to leave out the statement that increments the<br />counter. For example, in the script earlier in this section, if you leave out the<br />statement $k++;, $k is always 0, and the result is an infinite loop.<br />Breaking out of a loop<br />Sometimes you want your script to break out of a loop. PHP provides two<br />statements for this purpose:<br /> break: Breaks completely out of a loop and continues with the script<br />statements after the loop.<br /> continue: Skips to the end of the loop where the condition is tested.<br />If the condition tests positive, the script continues from the top of the<br />loop.<br />The break and continue statements are usually used in conditional statements.<br />In particular, break is used most often in switch statements, discussed<br />earlier in this chapter.<br />155 Chapter 7: Controlling the Flow of the Script<br />The following statements show the difference between continue and break.<br />This first section is an example of the break statement:<br />$counter = 0;<br />while ( $counter &lt; 5 )<br />{<br />$counter++;<br />If ( $counter == 3 )<br />{<br />echo “break\n”;<br />break;<br />}<br />echo “Last line in loop: counter=$counter\n”;<br />}<br />echo “First line after loop\n\n”;<br />The output of this statement is the following:<br />Last line in loop: counter=1<br />Last line in loop: counter=2<br />break<br />First line after loop<br />Notice that the first loop ends at the break statement. It stops looping and<br />jumps immediately to the statement after the loop. That’s not true of the<br />continue statement.<br />The following section is an example of the continue statement:<br />$counter = 0;<br />while ( $counter &lt; 5 )<br />{<br />$counter++;<br />If ( $counter == 3 )<br />{<br />echo “continue\n”;<br />continue;<br />}<br />echo “Last line in loop: counter=$counter\n”;<br />}<br />echo “First line after loop\n”;<br />The output of this statement is the following:<br />Last line in loop: counter=1<br />Last line in loop: counter=2<br />continue<br />Last line in loop: counter=4<br />Last line in loop: counter=5<br />First line after loop<br />156 Part III: Basic PHP Programming<br />Unlike the break statement loop, this loop does not end at the continue<br />statement. It just stops the third repeat of the loop and jumps back up to the<br />top of the loop. It then finishes the loop, with the fourth and fifth repeats,<br />before it goes to the statement after the loop.<br />One use for break statements is insurance against infinite loops. The following<br />statements inside a loop can stop it at a reasonable point:<br />$test4infinity++;<br />if ($test4infinity &gt; 100 )<br />{<br />break;<br />}<br />If you’re sure that your loop should never repeat more than 100 times, these<br />statements will stop the loop if it becomes endless. Use whatever number<br />seems reasonable for the loop you’re building.<br />Chapter 8<br />Reusing PHP Code<br />In This Chapter<br /> Including files in scripts<br /> Understanding security for included files<br />Writing functions<br /> Using functions<br />Often scripts need to perform the same actions in several different locations<br />in the script. For example, a script may need to get data from a<br />database several different times. It may even be the case that you use the<br />same code in different scripts. If you find yourself typing the same ten lines of<br />code over and over (or cutting and pasting it repeatedly), you can move that<br />code into a separate file and get it from that file whenever you need it. Here<br />are several reasons to reuse code:<br /> Less typing: Less work is always a good reason for anything.<br /> Debug once: You can write the code once, debug it so you know it works,<br />and then use it whenever you need it. It’s rare to write code that doesn’t<br />have a typo or two in it, let alone occasional peculiar logic, so code always<br />has to be debugged. It saves time to use proven code when possible,<br />instead of writing new code that will have to be debugged.<br /> Easier to understand: A shorter script that is less cluttered with code is<br />easier for people to read and understand. For example, one line in your<br />script that says getData() is easier to understand than the ten lines<br />that actually get the data.<br /> Easier to maintain: If you reuse code and you need to change something<br />in the code, you only need to change it in one external file, instead of<br />having to find and change it in a dozen places in your script. For example,<br />if you change the name of your database, you can change the name<br />in one file, rather than having to change it repeatedly in many scripts.<br />You can reuse code two ways: by inserting a file containing code into a script<br />or by writing and calling a function. In this chapter, you find out how to use<br />both methods.<br />Inserting Code in Your Script<br />You can put as many lines of code as you need into a file, separate from your<br />script, and include that file in the script wherever you need it. PHP provides<br />the include statement to insert code where it’s needed.<br />Including files<br />Suppose you’re writing an online product catalog and your application contains<br />many pages that display pictures of your products. You can define the<br />height and width for the pictures in constants and use the constants in your<br />HTML image tags, thereby displaying all your pictures consistently. By using<br />constants, you can change the size of the graphics simply by changing the<br />constant definition; you don’t have to change every image tag in your script.<br />You can define these constants by using the following statements in the top<br />of your script:<br />define(“HEIGHT”,60);<br />define(“WIDTH”,60);<br />You can then use the constants in your HTML image tags as follows:<br />&lt;img src=”mypic.jpg” height=”&lt;?php echo HEIGHT?&gt;”<br />width=”&lt;?php echo WIDTH?&gt;” /&gt;;<br />If you display the product pictures in many different scripts, you don’t have to<br />add the define statements in the top of every script. Instead, you can put the<br />statements into a separate file and include the file in the top of the scripts.<br />You can create a file called size.inc (you can use any extension for include<br />files, but .inc is often used by convention) that contains the following:<br />&lt;?php<br />define(“HEIGHT”,60);<br />define(“WIDTH”,60);<br />?&gt;<br />You can then include the file at the top of each script with the following<br />statement:<br />include(“size.inc”);<br />When PHP sees the include statement, it reads the code from the file so the<br />code is inserted at the location where the include statement is used. That<br />means that the constants are defined when size.inc is included, and the<br />image tags in your file will be output as follows:<br />&lt;img src=”mypic.jpg” height=”60” width=”60” /&gt;<br />158 Part III: Basic PHP Programming<br />This HTML code displays the image on your Web page. If you want to change<br />the height or width at any time, just change the definitions of HEIGHT and<br />WIDTH in size.inc, and all the images will automatically change size. Actually,<br />because the image tag that displays the picture is rather complex, you could<br />put the image statement into a file called displayPix.inc and include the file<br />whenever you want to display an image. You could have the image tag alone<br />in displayPix.inc and include both size.inc and displayPix.inc at the<br />beginning of each script, or you could include size.inc in displayPix.inc<br />and only include displayPix.inc in your script.<br />Forgetting the PHP tags in the include file is a common mistake. It’s also a<br />security problem because without the PHP tags, the code in the file is displayed<br />to the user as HTML. If the user sees the size of the graphic files, it’s<br />not much of a problem. However, suppose you had the password for your<br />database in the include file — that would be a problem.<br />Instead of the standard include statement, you can use the following similar<br />statement:<br />include_once(“filename”);<br />This statement prevents included files with similar variables from overwriting<br />each other. For example, you can use include_once to include your function<br />definitions (which are discussed later in this chapter) to be sure that<br />they are only defined once.<br />PHP also provides the require and require_once statements that work just<br />like include statements, differing only in the way errors are handled. This difference<br />arises when you use an include or a require statement that calls a<br />file that doesn’t exist. If you require a file that doesn’t exist, it is a fatal error,<br />and your script stops running. If you include a file that doesn’t exist, you only<br />receive a warning, and the script continues to run.<br />You can use a variable name for the filename as follows:<br />include (“$filename”);<br />For example, you might want to display different messages on different days:<br />You might store these messages in files that are named for the day on which<br />the message should display. For example, you could have a file named<br />Sun.inc with the following contents:<br />echo “Go ahead. Sleep in. No work today.”;<br />And similar files for all days of the week. The following statements can be<br />used to display the correct message for the current day:<br />$today = date(“D”);<br />include(“$today”.”inc”);<br />159 Chapter 8: Reusing PHP Code<br />After the first statement, $today contains the day of the week in abbreviation<br />form. The date statement is discussed in Chapter 5. The second statement<br />includes the correct file, using the day stored in $today. If $today contains<br />Sun, the statement includes a file called Sun.inc.<br />Storing include files<br />Where you store include files can be a security issue, especially for Web sites.<br />Files stored on Web sites can be downloaded by any user, unless the files are<br />protected. Theoretically, a user could connect to your Web site by using the<br />following type of URL:<br />http://yourdomain.com/secretpasswords.inc<br />Suppose you happen to have a file in your Web space named<br />secretpasswords.inc that contains the following statements:<br />&lt;?php<br />$mysecretaccount=”account48756”;<br />$mypassword=”secret”;<br />?&gt;<br />In most cases, the Web server is not configured to process PHP sections in<br />files with any extensions other than PHP. Therefore, the Web server would<br />not process these statements. Instead, it would obligingly display the contents<br />of secretpasswords.inc to the user, as if the lines were HTML code.<br />You can protect against this in one of the following ways:<br /> Name include files with .php extensions. The Web server will then<br />process the PHP sections, rather than treat them the same as the HTML<br />sections. However, you need to think carefully about the contents of the<br />include files if you name them with a .php extension. In some cases, running<br />the PHP sections in an include file independently, without the context<br />provided when they are run by including them in a script, can be a<br />problem. For example, suppose you had code in your include file that<br />deleted a record in the database (highly unlikely). Running the code outside<br />of a script might have negative consequences. Another drawback is<br />that it can be convenient to name files with an .inc extension so you<br />can see at a glance that the file is a fragment, not a script intended to<br />run by itself.<br /> Configure the Web server to scan for PHP sections in files with the<br />.inc extension, as well as the .php extension. This allows you to recognize<br />include files by their name. However, you still have the problem<br />of possible unintended consequences of running the file independently,<br />as discussed in the preceding bullet.<br />160 Part III: Basic PHP Programming<br /> Store the file in a location that is not accessible to outside users. This<br />is the preferred solution, but it may not be possible in some environments,<br />such as when you’re using a Web hosting company.<br />The best place to store include files is in a directory that outside users can’t<br />access. For example, for your Web site, you can set up an include directory<br />that is outside your Web space. That is, you can create a directory in a location<br />that outside users can’t access with their browsers. For example, the default<br />Web space for Apache — unless it has been changed in the configuration file<br />(usually called httpd.conf) — is apache/htdocs. If you store your include<br />files in a directory that is not in your Web space, such as d:\include, you can<br />protect the files from outside users.<br />Setting up include directories<br />You can set up an include directory where PHP looks for any files specified<br />in an include statement. If you are the PHP administrator, you can set up an<br />include directory in the php.ini file (the PHP configuration file in your system<br />directory, as described in Appendix A). Find the setting for include_path and<br />change it to the path to your preferred directory. If there is a semicolon at the<br />beginning of the line, before include_path, remove it. The following are examples<br />of include_path settings in the php.ini file:<br />include_path=”.;d:\include”; # for Windows<br />include_path=”.:/user/local/include”; # for Unix/Linux/Mac<br />Both of these statements specify two directories where PHP looks for include<br />files. The first directory is dot (meaning the current directory), followed by<br />the second directory path. You can specify as many include directories as you<br />want, and PHP will search them for the include file in the order in which they<br />are listed. The directory paths are separated by a semicolon for Windows and<br />a colon for Unix/Linux.<br />If you don’t have access to php.ini, you can set the path in each individual<br />script by using the following statement:<br />ini_set(“include_path”,”d:\hidden”);<br />This statement sets the include_path to the specified directory only while<br />the script is running. It doesn’t set the directory for your entire Web site.<br />To access a file from an include directory, just use the file name, as follows.<br />You don’t need to use the full path name.<br />include(“secretpasswords.inc”);<br />161 Chapter 8: Reusing PHP Code<br />If your include file is not in an include directory, you may need to use the<br />entire path name in the include statement. If the file is in the same directory<br />as the script, the file name alone is sufficient. However, if the file is located in<br />another directory, such as a subdirectory of the directory the script is in or a<br />hidden directory outside the Web space, you need to use the full path name<br />to the file, as follows:<br />include(“d:/hidden/secretpasswords.inc”);<br />Creating Reusable Code (Functions)<br />Applications often perform the same task at different points in the script or in<br />different scripts. This is when functions come in handy. A function is a group<br />of PHP statements that perform a specific task. You can use the function<br />wherever you need to perform the task.<br />For example, suppose you add a footer to the bottom of every Web page by<br />using the following statements:<br />.<br />echo ‘&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;<br />&lt;address&gt;My Great Company<br />&lt;br /&gt;1234 Wonderful Rd.<br />&lt;br /&gt;San Diego, CA 92126<br />&lt;/address&gt;&lt;/font&gt;<br />&lt;p&gt;or send questions to<br />&lt;a href=”mailto:sales@company.com”&gt;sales &lt;/a&gt;<br />&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;’;<br />It’s not uncommon for Web pages to have headers or footers much longer<br />than this. So, rather than type this code into the bottom of every Web page,<br />probably incurring at least a couple of typos in the process, you can create a<br />function that contains the preceding statements and name it add_footer.<br />Then at the end of every page, you can just use the function (a process<br />referred to as calling the function) that contains the footer statements. The<br />code for this simple function call is as follows:<br />add_footer();<br />Notice the parentheses after the function name. These are required in a function<br />call because they tell PHP that this is a function.<br />162 Part III: Basic PHP Programming<br />Defining functions<br />You can create a function by putting the code into a function block. The general<br />format is as follows:<br />function functionname()<br />{<br />block of statements;<br />return;<br />}<br />For example, you create the function add_footer() that I discuss in the preceding<br />section with the following statements:<br />function add_footer()<br />{<br />echo ‘&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;<br />&lt;address&gt;My Great Company<br />&lt;br /&gt;1234 Wonderful Rd.<br />&lt;br /&gt;San Diego, CA 92126<br />&lt;/address&gt;&lt;/font&gt;<br />&lt;p&gt;or send questions to<br />&lt;a href=”mailto:sales@company.com”&gt;sales &lt;/a&gt;<br />&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;’;<br />return;<br />}<br />The return statement stops the function and returns to the main script. (The<br />return statement at the end of the function is not required, but it makes the<br />function easier to understand. The return statement is discussed in more<br />detail in the section “Returning a value from a function,” later in this chapter.)<br />You can write a function anywhere in the script, but the usual practice is to<br />put all the functions together at the beginning or the end of the script file.<br />Functions that you plan to use in more than one script can be in a separate<br />file, and you can include the file in any scripts that need to use the functions.<br />At this point, you’re probably wondering, “Why can’t I just put the footer statements<br />into a separate file called footer.inc and include footer.inc at the<br />end of each Web page?” Good question! Actually, you can. In fact, you should.<br />In this case, the instructions for creating the footer consist of a simple block<br />of statements that echo static HTML code. You could just put the HTML in the<br />include file and include it at the end of the page. You wouldn’t even need to use<br />PHP tags in the include file.<br />163 Chapter 8: Reusing PHP Code<br />However, suppose the company has three divisions and you want to include<br />the division name in the footer and have the e-mail address send the e-mail<br />to the appropriate division. You could write three different include files and<br />include the correct one. However, a function works better in this situation<br />because functions are more flexible and faster. You can send information to<br />the function (called passing values), telling it which division to use in the<br />output. The function looks like this:<br />function add_footer($division)<br />{<br />echo ‘&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;<br />&lt;p&gt;’.$division.’ Division&lt;/p&gt;<br />&lt;address&gt;My Great Company<br />&lt;br /&gt;1234 Wonderful Rd.<br />&lt;br /&gt;San Diego, CA 92126<br />&lt;/address&gt;&lt;/font&gt;<br />&lt;p&gt;or send questions to<br />&lt;a href=”mailto:’.$division.’@company.com”&gt;’<br />.$division.’&lt;/a&gt;<br />&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;’;<br />return;<br />}<br />In this version, the function is expecting a value to be passed to it. It stores<br />the passed value in a variable called $division and uses the variable for the<br />text that needs to change. When you use this function, you must pass it a<br />value, as follows:<br />add_footer(“Sales”);<br />You can change the division by calling the function with a different value:<br />add_footer(“Accounting”);<br />Notice the format of the echo statement. The string is enclosed in single<br />quotes. In the previous function, without variables, the format was simple —<br />just a single quote at the beginning and another single quote at the end. In<br />this function example, using a variable, the quoted string is ended when<br />$division is used and reopened after the variable. Remember, variables are<br />not evaluated inside single quotes. If $division were used inside single<br />quotes, the output would show $division Division, instead of Sales<br />Division.<br />You can pass a value back from a function, called returning a value. Values are<br />returned by using the return statement. For example, suppose you want the<br />function to put the footer into a variable rather than echo the footer. In that<br />case, the function looks like this:<br />164 Part III: Basic PHP Programming<br />function add_footer($division)<br />{<br />$str=’&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;<br />&lt;p&gt;’.$division.’ Division&lt;/p&gt;<br />&lt;address&gt;My Great Company<br />&lt;br /&gt;1234 Wonderful Rd.<br />&lt;br /&gt;San Diego, CA 92126<br />&lt;/address&gt;&lt;/font&gt;<br />&lt;p&gt;or send questions to<br />&lt;a href=”mailto:’.$division.’@company.com”&gt;’<br />.$division.’&lt;/a&gt;<br />&lt;img src=”greenrule.jpg” width=”100%” height=”7” /&gt;’;<br />return $str;<br />}<br />In this case, you could use these statements:<br />$footer = add_footer(“Sales”);<br />echo $footer;<br />When you echo $footer, you output the entire footer string that was created<br />in the function.<br />The rest of this chapter describes in detail how to create and use functions.<br />A good programmer looks for opportunities to put script code into functions,<br />which improves readability and maintainability, as well as makes the script<br />run faster.<br />Using variables in functions<br />You can create and use a variable inside your function. Such a variable is<br />called local to the function A local variable is not available outside of the<br />function, so it’s not available to the main script. (If you want to use the variable<br />outside the function, you have to make the variable global, rather than<br />local, by using a global statement.) For example, the variable $name is created<br />in the following function:<br />function format_name($first_name,$last_name)<br />{<br />$name = $last_name.”, “.$first_name;<br />}<br />You can then call the function, passing it values, and attempt to echo the<br />value of the variable $name:<br />format_name(“Jess”,”Jones”);<br />echo “$name”;<br />165 Chapter 8: Reusing PHP Code<br />However, these statements do not produce any output. In the echo statement,<br />$name doesn’t contain any value. The variable $name was created<br />inside the function, so it doesn’t exist outside the function.<br />You can create a variable inside a function that does exist outside the function<br />by using the global statement. The following statements contain the<br />same function with a global statement added:<br />function format_name($first_name,$last_name)<br />{<br />global $name;<br />$name = $last_name.”, “.$first_name;<br />}<br />You can now call the function, passing it the same values, and echo the value<br />of the variable $name:<br />format_name(“Jess”,”Jones”);<br />echo “$name”;<br />The script now echoes the value of the variable $name:<br />Jones, Jess<br />You must make the variable global before you can use it. If the global statement<br />follows the $name assignment statement, the script does not produce<br />any output. That is, in the preceding function, if the global statement followed<br />the $name = statement, the function wouldn’t work correctly.<br />Similarly, if a variable is created outside the function, you can’t use it inside<br />the function unless it is global. You can make the variable global as shown in<br />the following statements:<br />$first_name = “Jess”;<br />$last_name = “Jones”;<br />function format_name()<br />{<br />global $first_name, $last_name;<br />$name = $last_name.”, “.$first_name;<br />echo “$name”;<br />}<br />format_name();<br />If you don’t use the global statement, $last_name and $first_name inside<br />the function are different variables than $last_name and $first_name created<br />outside the script. The local variables $last_name and $first_name<br />inside the function are created when you name them and have no values.<br />Therefore, $name would echo only a comma.<br />You need the global statement for the function to work correctly.<br />166 Part III: Basic PHP Programming<br />Passing values to a function<br />You pass values to a function by putting the values between the parentheses<br />when you call the function, as follows:<br />functionname(value1,value2,&#8230;);<br />Of course, the variables can’t just show up. The function must be expecting<br />them. The function statement includes variable names for the values it’s<br />expecting, as follows:<br />function functionname($varname1,$varname2,&#8230;)<br />{<br />statements<br />return;<br />}<br />Passing the right type of values<br />Values can be variables or values, including values that are computed. The<br />values passed can be any type of data, including arrays or objects (objects<br />are discussed in Chapter 9).<br />The following statements call a function that computes the sales tax. A<br />salestax function needs to know the amount of the purchase, so it can<br />compute the amount of tax. It also needs to know the state, so it can use the<br />correct tax rate to compute the sales tax. The values you need to pass are a<br />number (the purchase amount) and a string (the state’s name). The following<br />calls are valid:<br /> compute_salestax(2000,”CA”); This function is being passed two<br />values, 2000 and CA, CA.<br /> compute_salestax(2*1000,””); This function is being passed two<br />values, 2000 and ???, an empty value. The function must include code<br />that handles the empty variable.<br /> compute_salestax(2000,”C”.”A”); This function is being passed two<br />values, 2000 and ???, CA.<br />You can pass arrays to functions. (Arrays are discussed in Chapter 6.) For<br />example, the following function uses an array that is passed to it:<br />function add_numbers($numbers)<br />{<br />for($i=0;$i &lt;sizeof($numbers);$i++)<br />{<br />@$sum = $sum + $numbers[$i];<br />}<br />return $sum;<br />}<br />167 Chapter 8: Reusing PHP Code<br />This function adds all the numbers passed to it in an array of numbers. If the<br />value passed to it is not an array, PHP stores the value in $numbers as its correct<br />data type — an integer or a string. When the function gets to the statement<br />sizeof($numbers), it fails because $numbers is not an array and sizeof<br />requires an array. A well-written function checks the values that are passed to<br />it make sure they are the type of value needed before executing the statements<br />in the function. For example, the following statement can be added to the function<br />block, immediately before the for statement:<br />If(!is_array($numbers)<br />{<br />echo “The value passed is not an array”;<br />exit();<br />}<br />Similarly, this function should check whether the elements of the array are<br />numbers, using some of the functions described in Chapter 5.<br />You can use the following statements to define an array that is then passed to<br />the add_numbers function:<br />$arrayofnumbers = array(100,200);<br />$total = add_numbers($arrayofnumbers);<br />After these statements, $total equals 300.<br />Passing values in the correct order<br />The function receives the values in the order they are passed. That is, suppose<br />you have the following function:<br />function functionx($x,$y,$z)<br />{<br />do stuff<br />}<br />You call the function as follows:<br />functionx($var1,$var2,$var3);<br />The function sets $x=$var1, $y=$var2, and $z=$var3.<br />If the values you pass aren’t in the expected order, the function uses the wrong<br />value when performing the task. For example, suppose that your definition for<br />a function to compute sales tax looks like the following:<br />function compute_salestax($orderCost,$custState)<br />{<br />compute tax<br />}<br />168 Part III: Basic PHP Programming<br />But suppose you call it by using the following call:<br />compute_salestax($custState,$orderCost);<br />The function uses the state as the cost of the order, which it sets to 0 because<br />it is a string. It sets the state to the number in $orderCost, which would not<br />match any of its categories. The output would be 0.<br />Passing the right number of values<br />A function is designed to expect a certain number of values to be passed to<br />it. If you don’t send enough values, the function sets the missing one(s) to<br />NULL. If you have your warning message level turned on, a warning message<br />is displayed. (See Chapter 4 for a description of error levels.) For example,<br />you might see a message similar to the following:<br />Warning: Missing argument 2 for format_name() in testing.php<br />on line 9<br />Remember, warnings don’t stop the script; it continues to run. Suppose that<br />you call the format_name function described in the section “Using variables<br />in functions,” earlier in this chapter, by using the following statement:<br />format_name(“Jess”);<br />The output is as follows:<br />Jess,<br />If you send too many values, the function ignores the extra values. In most<br />cases, you do not want to pass the wrong number of values.<br />You can set default values to be used when a value isn’t passed. The defaults<br />are set when you write the function, be assigning a default value for the value(s)<br />it is expecting, as follows:<br />function add_2_numbers($num1=1,$num2=1)<br />{<br />$total = $num1 + $num2;<br />return $total;<br />}<br />If one or both values are not passed, the function uses the assigned defaults.<br />But if a value is passed, it is used instead of the default. For example, you<br />could use one of the following calls:<br />add_2_numbers(2,2);<br />add_2_numbers(2);<br />add_2_numbers();<br />169 Chapter 8: Reusing PHP Code<br />The result are, in consecutive order:<br />$total = 4<br />$total = 3<br />$total = 2<br />The first $total is 4, because 2 and 2 are passed. The second $total is<br />three because 2 is passed and the default 1 is used for $num2. The third<br />$total is 2 because neither value is passed and, therefore, the defaults of 1<br />are used for both $num1 and $num2.<br />Passing values by reference<br />When you pass values into variables in the function definition, you are passing<br />by value. Passing by value is the most common way to pass values to a<br />function, as in the following example:<br />function add_1($num1)<br />{<br />$num1 = $num1 + 1;<br />}<br />When passing by value, a copy is made of a value and the copy is passed<br />to the function. The value passed into the function is stored in the variable<br />$num1, and 1 is added to it in the function. However, the value of the variable<br />outside the function is not changed. Suppose that you call the function with<br />the following statements:<br />$orig_num = 3;<br />add_1($orig_num);<br />echo $orig_num;<br />The output from the echo statement is 3. A copy of the value stored in<br />$orig_num was passed to add_1, but nothing in the function affected<br />$orig_num. It is unchanged. You can change $orig_num by adding a return<br />statement to the function, as follows:<br />return $num1;<br />You then store the returned value in $orig_num as follows:<br />$orig_num = 3;<br />$orig_num = add_1($orig_num);<br />echo $orig_num;<br />Now, the echo statement outputs 4.<br />In some cases, you may want to change the values of variables directly, changing<br />their values outside the function. That is, in the first example above, you<br />may want $orig_value changed from inside the function, without having to<br />170 Part III: Basic PHP Programming<br />pass it back. In this simple case, you could make the variable global, but you<br />can also do it using a technique called passing by reference. To pass a variable<br />by reference, add &amp; before the variable name, as follows:<br />function add_1(&amp;$num1)<br />{<br />$num1 = $num1 + 1;<br />}<br />When you call this function, a value is passed that tells PHP where the variable<br />is stored, (that is, a pointer to the container called $orig_num where the<br />value 3 is stored) rather than a copy of the value. The variable $num1 then<br />becomes another name for $orig_num, rather than a different variable that<br />contains 3. When you assign something to $num1, it is stored in $orig_num.<br />$num1 and $orig_num are two names for the same storage location. When<br />you change the variable by using statements inside the function, the value at<br />the original location is changed as well. For example, suppose you call the<br />function by using the following statements:<br />$orig_num = 3;<br />add_1($orig_num);<br />echo $orig_num;<br />The output of the echo statement is 4.<br />Because you’re passing a pointer to a variable, the following doesn’t make<br />sense:<br />add_1(&amp;7);<br />Passing by reference is used mainly when passing really large values, such as<br />an object or a large array. It’s more efficient to pass a pointer than to pass a<br />copy of really large values.<br />Returning a value from a function<br />If you want a function to send a value back to the main script, you use the<br />return statement. The main script can put the returned value in a variable<br />or use it in any manner it would use any value.<br />A return statement returns any values specified and ends the function,<br />returning to the main script. The general format is as follows:<br />return value;<br />171 Chapter 8: Reusing PHP Code<br />For example, the add2numbers function looks like this:<br />function add_2_numbers($num1,$num2)<br />{<br />$total = $num1 + $num2;<br />return $total;<br />}<br />The total of the two numbers is returned and the function ends. You call the<br />function as follows:<br />$sum = add_2_numbers(5,6);<br />$sum then equals the value in $total that was returned from the function,<br />which is 11 in this case. In fact, you could use a shortcut when defining the<br />function and send the total back to the main script with one statement:<br />return $num1 + $num2;<br />The main script can use the value in any of the usual ways. The following<br />statements use the function call in valid ways:<br />$total_height = add_2_numbers($height1,$height2);<br />$totalSize = $current_size + add_2_numbers($size1,$size2);<br />if (add_2_numbers($costSocks,$costShoes) &gt; 200.00 )<br />$echo “No sale”;<br />A return statement can return only one value. However, the value returned<br />can be an array, so you can actually return many values from a function.<br />You can use a return statement in a conditional statement to end a function,<br />as follows:<br />function find_value($array,$value)<br />{<br />for($i=1;$i&lt;sizeof($array);$i++)<br />{<br />if($array[$i] = $value)<br />{<br />echo “$i. $array[$i]&lt;br&gt;”;<br />return;<br />}<br />}<br />}<br />172 Part III: Basic PHP Programming<br />The function checks an array to see if it contains a particular value. For example,<br />you can call the function with the following statements:<br />$names = array(“Joe”,”Sam”,”Juan”);<br />find_value($names,”Sam”);<br />The function searches through the values in the array looking for Sam. If it<br />finds Sam, it stops searching. The output shows the array item where Sam<br />is found, as follows:<br />1. Sam<br />Often functions are designed to return Boolean values, as in the following<br />function:<br />function is_over_100($number)<br />{<br />if($number &gt; 100)<br />{<br />return TRUE;<br />}<br />else {<br />return FALSE;<br />}<br />}<br />Numbers 100 or less return FALSE; numbers over 100 return TRUE.<br />Another common function design returns a value if the function succeeds,<br />but returns FALSE if the function does not succeed. For example, you could<br />design the find_value function as follows:<br />function find_value($array,$value)<br />{<br />for($i=1;$i&lt;sizeof($array);$i++)<br />{<br />if($array[$i] == $value)<br />{<br />return i$;<br />}<br />}<br />return FALSE;<br />}<br />If the function finds the value in the array, it returns the number of the array<br />element where it found $value. However, if it does not find the value anywhere<br />in the array, it returns FALSE.<br />173 Chapter 8: Reusing PHP Code<br />Using built-in functions<br />PHP’s built-in functions are one reason why PHP is so powerful and useful.<br />The functions included with PHP are normal functions. They are no different<br />than functions you create yourself. It’s just that PHP has already done all the<br />work for you.<br />Rather than discussing built-in functions here, out of context, I discuss specific<br />PHP functions where I describe tasks in which functions can be very<br />helpful. For example, in Chapter 7, I discuss several functions that can be<br />used to check whether a variable exists or whether it is empty. Here are a<br />couple of those functions:<br />isset($varname)<br />empty($varname)<br />Also, in Chapter 5 I describe several functions that are useful for formatting<br />and manipulating numbers and strings. And other PHP built-in functions are<br />discussed throughout the book.<br />Appendix B is a reference list of many useful functions. Keep this list handy<br />when writing scripts so you can quickly look up PHP built-in functions. Although<br />you could write functions yourself to perform the tasks, take advantage of<br />PHP’s functions whenever possible. The reference in Appendix B does not<br />include all the functions, of course — there are hundreds — but it includes<br />the functions I have found to be most useful. All the functions are listed and<br />described in the PHP documentation on the PHP Web site at<br />www.php.net/docs.php.<br />Handling Errors<br />Sometimes functions fail. Sad, but true. You write them to carefully handle all<br />possibilities, but something can still go wrong. For example, a function that<br />connects to a database might fail because the database is currently down.<br />It’s not the function’s fault; the situation is beyond its control. A well-written<br />function tries to anticipate all possible situations, but recognizes that the<br />unexpected can happen by including a statement that returns FALSE when<br />the function is unable to carry out its mission for unexpected reasons.<br />Your script should anticipate any possible function failure and handle the situation.<br />One possible action is to display your own message, rather than allow the<br />user to see the warning message provided by PHP. PHP provides the die statement,<br />which displays the message you specify. The format of the die statement<br />is as follows:<br />die(“message”);<br />174 Part III: Basic PHP Programming<br />The die statement stops the script and prints out whatever you have entered<br />in the place of message. When you use it with a function, you use it with or,<br />as follows:<br />functionname() or die(“message”);<br />If the function returns FALSE, the die statement stops the script and prints<br />out the message.<br />For example, if you use a function to connect to a MySQL database, you could<br />use the following statement:<br />mysql_connect(“host”,”user”,”password”)<br />or die(“Database is not available. Try again later.”);<br />Remember, if the function fails, PHP will display a warning message. If you<br />want your message to be displayed instead of the PHP warning message,<br />you need to change your error-reporting level so that warning messages are<br />not displayed, or shut off the display of all error messages, as described in<br />Chapter 4. Otherwise, both the PHP warning and your message will be<br />displayed.<br />You can use die with any function, but it doesn’t make sense to use it when<br />FALSE is a legitimate return value. Remember, die stops the script dead in its<br />tracks.<br />You can also handle possible function failures by using the function call as a<br />condition. For example, you can get the same result as the previous example<br />by using the following statements instead:<br />if(!mysql_connect(“host”,”user”,”password”))<br />{<br />echo “Database is not available. Try again later\n”;<br />exit();<br />}<br />Notice the exclamation point before the function call, making it a negative<br />condition. The condition is TRUE if the function returns FALSE.<br />The exit statement does the same thing as the die statement. Keep in mind<br />that you can use any statement in the if block; you can even have the script<br />send you an e-mail if the database is unreachable.<br />175 Chapter 8: Reusing PHP Code<br />176 Part III: Basic PHP Programming<br />Chapter 9<br />Object-Oriented Programming<br />Meets PHP<br />In This Chapter<br /> Understanding object-oriented programming<br /> Identifying objects<br />Writing classes<br /> Using classes<br />PHP began life as a simple set of scripts. Over the course of its life, PHP<br />has added some object-oriented programming features, and objectoriented<br />programming became possible with PHP 4. With the introduction of<br />PHP 5, the PHP developers have really beefed up the object-oriented features<br />of PHP, resulting in both more speed and added features. Much of this<br />improvement is invisible — changes introduced with the Zend 2 engine that<br />powers PHP 5, that make scripts using objects run much faster and more<br />efficiently than they did in PHP 4. In addition, to speeding up scripts, objectoriented<br />functionality has been added to PHP that object-oriented programmers<br />have been waiting for.<br />Introducing Object-Oriented<br />Programming<br />Object-oriented programming is an approach to programming that uses objects<br />and classes, which are discussed in more detail later in this chapter. Objectoriented<br />programming is widespread today, and many universities teach<br />object-oriented programming in beginning programming classes. Currently,<br />Java and C++ are the most prevalent languages used for object-oriented<br />programming.<br />Object-oriented programming is not just a matter of using different syntax.<br />It’s a different way of analyzing programming problems. The program is<br />designed by modeling the programming problem. For example, a programmer<br />designing a program to support a company’s sales department may look at<br />the programming problem in terms of the relationships between customers<br />and sales and credit lines — in other words, in terms of the design of the<br />sales department itself.<br />In object-oriented programming, the elements of a program are objects. The<br />objects represent the elements of the problem your program is meant to<br />solve. For example, if the program is related to a used-car lot, the objects are<br />probably cars and customers. Or if the program is related to outer space, the<br />objects would probably be stars and planets.<br />Object-oriented programming developed new concepts and new terminology<br />to represent those concepts. Understanding the terminology is the road to<br />understanding object-oriented programming.<br />Objects and classes<br />The basic elements of object-oriented programs are objects. It’s easiest to<br />understand objects as physical objects. For example, a car is an object. A car<br />has properties, such as color, model, engine, and tires, also called attributes.<br />A car has things it can do, too, such as move forward, move backward, park,<br />roll over, and play dead (well, mine does anyway).<br />In general, objects are nouns. A person is an object. So are animals, houses,<br />offices, customers, garbage cans, coats, clouds, planets, and buttons. However,<br />objects are not just physical objects. Often objects, like nouns, are more conceptual.<br />For example, a bank account is not something you can hold in your<br />hand, but it can be considered an object. So can a computer account. Or a<br />mortgage. A file is often an object. So is a database. Orders, e-mail messages,<br />addresses, songs, TV shows, meetings, and dates can all be objects.<br />A class is the script that serves as the template, or the pattern, that is used to<br />create an object. The class defines the properties, the attributes, of the<br />object. It also defines the things the object can do — its responsibilities. For<br />example, you write a class that defines a car as four wheels and an engine<br />and lists the things it can do, such as move forward and park. Then, given<br />that class, you can write a statement that creates a car object. Your new car<br />is created following the pattern in your class. When you use your car object,<br />you may find that it is missing a few important things, like a door or a steering<br />wheel or a reverse gear. That’s because you left those out of the class<br />when you wrote it.<br />As the person who writes a class, you know how things work inside the class.<br />But it’s not necessary to know how an object accomplishes its responsibilities<br />in order to use it; anyone can use a class. I have no clue how a telephone<br />178 Part III: Basic PHP Programming<br />object works, but I can use it to make a phone call. The person who built the<br />telephone knows what’s happening inside it. When there’s new technology,<br />the phone builder can open my phone and improve it. As long as he doesn’t<br />change the interface — the keypad and buttons — it doesn’t affect my use of<br />the phone at all.<br />Properties<br />Objects have properties, also sometimes called attributes. A car may be red,<br />green, or covered in polka dots. Properties — such as color, size, or model<br />for a car — are stored inside the object. Properties are set up in the class as<br />variables. For example, the color attribute is stored in the object in a variable,<br />given the descriptive name such as $color. Thus, the car object may<br />contain $color = red.<br />The variables that store properties can have default values, can be given<br />values when the object is created, or values can be added or modified later.<br />For example, a car is created red, but when it is painted later, $color is<br />changed to chartreuse.<br />Methods<br />The things objects can do are sometimes referred to as responsibilities. For<br />example, a car object can move forward, stop, backup, and park. Each thing<br />an object can do — each responsibility — is programmed into the class and<br />called a method.<br />In PHP, methods use the same syntax as functions. Although the code looks<br />like the code for a function, the distinction is that methods are inside a class.<br />It can’t be called independently of an object. PHP won’t allow it. This type of<br />function can perform its task only when called with an object.<br />When creating methods, give them names that are descriptive of what they<br />do. Methods often have names like parkCar or getColor. Methods, like<br />other PHP entities, can be named with any valid name, but are often named<br />with camel caps, by convention.<br />The methods are the interface between the object and the rest of the world.<br />The object needs methods for all its responsibilities. Objects should interact<br />with the outside world only through their methods. If your neighbor object<br />wants to borrow a cup of sugar, you want him to knock on your door and<br />request the sugar. You don’t want him to just climb in the kitchen window and<br />help himself. Your house object should have a front door, and neighbor<br />objects should not be able to get into your house without using the front<br />door. In other words, your house object has a method for openFrontDoor that<br />179 Chapter 9: Object-Oriented Programming Meets PHP<br />the neighbor must use. There should not be any other way the neighbor can<br />get into the house. Opening the front door is something your house object<br />can do, via a method called openDoor. Don’t leave any open windows in your<br />object design.<br />A good object should contain all it needs to perform its responsibilities, but<br />not a lot of extraneous data. It should not perform actions that are another<br />object’s responsibility. The car object should travel and should have everything<br />it needs to perform its responsibilities, such as gas, oil, tires, engine,<br />and so on. The car object should not cook and does not need to have salt or<br />frying pans. Nor should the cook object carry the kids to soccer practice.<br />Inheritance<br />Objects should contain only the properties and methods they need. No more.<br />No less. One way to accomplish that is to share properties and methods<br />between classes by using inheritance. For example, suppose you have two<br />rose objects: one with white roses and one with red roses. You could write<br />two classes: a redRose class and a whiteRose class. However, a lot of the<br />information is the same for both objects. Both are bushes, both are thorny,<br />and both bloom in June. Inheritance enables you to eliminate the duplication.<br />You can write one class called Rose. You can store the common information<br />in this class, such as $plant = bush, $stem=thorns, and $blooms=June.<br />Then you can write subclasses for the two rose types. The Rose class is<br />called the master class or the parent class. redRose and whiteRose are the<br />subclasses, which are referred to as child classes, or the kids, as my favorite<br />professor fondly referred to them.<br />Child classes inherit all the properties and methods from the parent class. But<br />they can also have their own individual properties, such as $color=white for<br />the whiteRose class and $color=red for the redRose class.<br />A child class can contain a method with the same name as a method in a<br />parent class. In that case, the method in the child class takes precedence for<br />a child object. You can specify the method in the parent class for a child<br />object if you want, but if you don’t, the child class method is used.<br />Object-oriented concepts PHP 5 omits<br />If you’re familiar with object-oriented programming in other languages, you<br />may find that some features you’re accustomed to using aren’t available in<br />PHP. Things are getting better — many of the features missing in PHP 4 have<br />been added in PHP 5. The still-missing features include the following:<br />180 Part III: Basic PHP Programming<br /> Polymorphism: PHP does not allow more than one method, even a constructor,<br />to have the same name in a class. Therefore, you can’t implement<br />polymorphism as you’re used to doing. You can’t have two or more<br />methods with the same name in the same class that accept different<br />types or number of variables. Some people use switches and other mechanisms<br />to implement the functionality of polymorphism.<br /> Multiple inheritance: PHP does not allow multiple inheritance. A class<br />can inherit from only one parent class.<br />Developing an Object-Oriented Program<br />Object-oriented programs require a lot of planning, even more than procedural<br />programs that process statement from beginning to end, without using classes.<br />You need to plan your objects and their properties and what they can do. Your<br />objects need to cover all their responsibilities without encroaching on the<br />responsibilities of other objects. For complicated projects, you may have to do<br />some model building and testing before you can feel reasonably confident that<br />your project plan includes all the objects it needs.<br />Choosing objects<br />Your first task is to develop the list of objects needed for your programming<br />project. If you’re working alone and your project is small, the objects may be<br />obvious. However, if you’re working on a large, complex project, selecting the<br />list of objects can be more difficult. For example, if your project is developing<br />the software for a bank, your list of possible objects is large: account, teller,<br />money, checkbook, wastebasket, guard, vault, alarm system, customer, loan,<br />interest, and so on. But, do you need all those objects? What is your program<br />going to do with the wastebasket in the front lobby? Or the guard? Well, perhaps<br />your program needs to schedule shifts for the guards.<br />One strategy for identifying your objects is to list all the objects you can think<br />of — that is, all the nouns that may have anything to do with your project.<br />Sometimes programmers can take all the nouns out of the project proposal<br />documentation to develop a pretty comprehensive list of possible objects.<br />After you have a long list of possible objects, your next task is to cross off<br />as many as possible. You should eliminate any duplicates, objects that have<br />overlapping responsibilities and objects that are unrelated to your project.<br />For example, if your project relates to building a car, your car project probably<br />needs to have objects for every part in the car. On the other hand, if your<br />project involves traffic control in a parking garage, you probably only need a<br />car object that you can move around; the car’s parts don’t matter for this<br />project.<br />181 Chapter 9: Object-Oriented Programming Meets PHP<br />Selecting properties and<br />methods for each object<br />After you have a comprehensive list of objects, you can begin to develop the<br />list of properties for each object. Ask yourself what you need to know about<br />each object. For example, for your car repair project, you probably need to<br />know things like when the car was last serviced, its repair history, any accidents,<br />details about the parts, and so on. For your parking garage project,<br />you probably need to know only the car’s size. How much room does the car<br />take up in the parking garage?<br />You need to define the responsibilities of each object, and each object needs<br />to be independent. It needs methods for actions that handle all of its responsibilities.<br />For example, if one of your objects is a bank account, you need to<br />know what a bank account needs to do. Well, first, it needs to be created, so<br />you can define an openNewAccount method. It needs to accept deposits and<br />disburse withdrawals. It needs to keep track of the balance. It needs to report<br />the balance when asked. It may need to add interest to the account periodically.<br />Such activities come to mind quickly.<br />However, a little more thought, or perhaps testing, can reveal activities that<br />were overlooked. For example, the account stores information about its<br />owner, such as name and address. Did you remember to include a method to<br />update that information when the customer moves? It may seem trivial compared<br />to moving the money around, but it won’t seem trivial if you can’t do it.<br />Creating and using the class<br />After you have decided on the design of an object, you can create and then<br />use the object. The steps for creating and using an object are shown below:<br />1. Write the class statement.<br />The class statement is a PHP statement that is the blueprint for the<br />object. The class statement has a statement block that contains PHP<br />code for all the properties and methods that the object has.<br />2. Include the class in the script where you want to use the object.<br />The class statement can be written in the script itself. However, it is<br />more common to save the class statement in a separate file and use an<br />include statement to include the class at the beginning of the script<br />that needs to use the object.<br />3. Create an object in the script.<br />You use a PHP statement to create an object based on the class. This is<br />called instantiation.<br />182 Part III: Basic PHP Programming<br />4. Use the new object.<br />After you create a new object, you can use it to perform actions. You can<br />use any method that is inside the class statement block.<br />The rest of this chapter provides the details needed to complete these steps.<br />Defining a Class<br />After you’ve determined the objects, properties, and methods your project<br />requires, you’re ready to define classes. The class is the template (pattern)<br />for the object.<br />Writing a class statement<br />You write the class statement to define the properties and methods for the<br />class. The class statement has the following general format:<br />class className<br />{<br />Add statements that define the properties<br />Add all the methods<br />}<br />You can use any valid PHP identifier for the class name, except the name<br />stdClass. PHP uses the name stdClass internally, so you can’t use this<br />name.<br />All the property settings and method definitions are enclosed in the opening<br />and closing curly brackets. If you want a class to be a subclass that inherits<br />properties and methods, use a statement similar to the following:<br />class whiteRose extends Rose<br />{<br />Add the property statements<br />Add the methods<br />}<br />The object created from this class has access to all the properties and<br />methods of both the whiteRose class and the Rose class. The Rose class,<br />however, does not have access to properties or methods in the child class,<br />whiteRose. Imagine, the child owns everything the parent owns, but the<br />parent owns nothing of the child’s. What an idea.<br />183 Chapter 9: Object-Oriented Programming Meets PHP<br />The next few sections show you how to set properties, and define methods,<br />within the class statement. For a more comprehensive example of a complete<br />class statement, see the section, “Putting it all together,” later in this<br />chapter.<br />Setting properties<br />When you’re defining a class, you declare all the properties in the top of the<br />class, as follows:<br />class Car<br />{<br />var $color;<br />var $tires;<br />var $gas;<br />Method statements<br />}<br />PHP does not require you to declare variables. In the other PHP scripts discussed<br />in this book, variables are not declared; they’re just used. You can do<br />the same thing in a class. However, it’s much better to declare the properties<br />in a class. By including declarations, classes are much easier to understand.<br />It’s poor programming practice to leave this out.<br />If you want to set default values for the properties, you can, but the values<br />allowed are restricted. You can declare a simple value, but not a computed<br />one, as detailed in the following examples:<br /> The following variable declarations are allowed as default values:<br />var $color = “black”;<br />var $gas = 10;<br />var $tires = 4;<br /> The following variable declarations are not allowed as default values:<br />var $color = “blue”.” black”;<br />var $gas = 10-3;<br />var $tires = 2*2;<br />An array is allowed in the variable declaration, as long as the values are<br />simple, as follows:<br />var $doors = array(“front”,”back”);<br />184 Part III: Basic PHP Programming<br />You can set or change a variable’s value when you create an object, by using<br />the constructor (described in “Writing the constructor,” later in this chapter)<br />or a method you write for this purpose.<br />Using $this<br />Inside a class, $this is a special variable that refers to the properties of the<br />same class. $this can’t be used outside of a class. It’s designed to be used in<br />statements inside a class to access variables inside the same class.<br />The format for using $this is the following:<br />$this-&gt;varname<br />For example, in the Car class that has an attribute $gas, you would access<br />$gas in the following way:<br />$this-&gt;gas<br />Using $this refers to $gas inside the class. You can use $this in any of the<br />following statements as shown:<br />$this-&gt;gas = 20;<br />if($this-&gt;gas &gt; 10)<br />$product[$this-&gt;size] = $price<br />As you can see, you use $this-&gt;varname in all the same ways you would use<br />$varname.<br />Notice that a dollar sign ($) appears before this but not before gas. Don’t<br />use a dollar sign before gas — as in $this-&gt;$gas — because it changes your<br />statement’s meaning. You may or may not get an error message, but it isn’t<br />referring to the variable $gas inside the current class.<br />Adding methods<br />Methods define what an object can do and are written in the class by using<br />the function format. For example, your car may need a method that puts gas<br />in the gas tank. You can have a variable called gas that contains the amount<br />of gas currently in the gas tank. You can write a method that adds an amount<br />of gas to $gas. You could add such a method to your class as follows:<br />185 Chapter 9: Object-Oriented Programming Meets PHP<br />class Car<br />{<br />var $gas = 0;<br />function addGas($amount)<br />{<br />$this-&gt;gas = $this-&gt;gas + $amount;<br />echo “$amount gallons added to gas tank”;<br />}<br />}<br />This looks just like any other function, but it’s a method because it’s inside a<br />class.<br />PHP provides some special methods with names that begin with __ (two<br />underscores). These methods are handled differently by PHP internally.<br />This chapter discusses three of these methods: construct, destruct, and<br />clone. Don’t begin the names of any of your own methods with two underscores<br />unless you are taking advantage of a PHP special method.<br />Writing the constructor<br />The constructor is a special method that is executed when an object is created<br />using the class as a pattern. A constructor is not required, and you don’t need<br />to use a constructor if you don’t want to set any property values or perform<br />any actions when the object is created. Only one constructor is allowed.<br />The constructor has a special name so that PHP knows to execute the<br />method when an object is created. Constructors are named __construct.<br />(Note the two underscores.) A constructor method looks similar to the<br />following:<br />function __construct()<br />{<br />$this-&gt;gas = 10; # starts with a full gas tank<br />$this-&gt;openDoor();<br />}<br />This constructor defines the new car. When the car is created, it has a full gas<br />tank and an open door.<br />Prior to PHP 5, constructors had the same name as the class. You may run<br />across classes written in this older style. PHP 5 looks first for a method called<br />__construct() to use as the constructor. If it doesn’t find one, it looks for a<br />method that has the same name as the class and uses that method for the<br />constructor. Thus, older classes still run under PHP 5.<br />186 Part III: Basic PHP Programming<br />Putting it all together<br />Your class can have as few or as many properties and methods as it needs.<br />These methods can be very simple or very complicated, but the goal of<br />object-oriented programming is to make the methods as simple as is reasonable.<br />Rather than cram everything into one method, it’s better to have several<br />smaller methods and have one method call another.<br />The following is a simple class:<br />class MessageHandler<br />{<br />var $message = “No message”;<br />function __construct($message)<br />{<br />$this-&gt;message = $message;<br />}<br />function displayMessage()<br />{<br />echo $this-&gt;message.”\n”;<br />}<br />}<br />The class has one property — $message — that stores a message. The message<br />is stored in the constructor.<br />The class has one method — displayMessage. This is the only thing the<br />messageHandler object is able to do — echo the stored message.<br />Suppose you want to add a method that changes the message to lowercase<br />and then automatically displays the message. The best way to write that<br />expanded class is as follows:<br />class MessageHandler<br />{<br />var $message = “No message”;<br />function __construct($message)<br />{<br />$this-&gt;message = $message;<br />}<br />function displayMessage()<br />{<br />echo $this-&gt;message.”\n”;<br />}<br />function lowerCaseMessage()<br />{<br />$this-&gt;message = strtolower($this-&gt;message);<br />$this-&gt;displayMessage();<br />}<br />}<br />187 Chapter 9: Object-Oriented Programming Meets PHP<br />Note the lowerCaseMessage() method. Because the class already has<br />a method to display the message, this new method uses the existing<br />displayMessage() method rather than include the statements in the new<br />method. Any time you write a method and find yourself writing code that you<br />have already written elsewhere in a different method in the same class, you<br />need to redesign the methods. In general, you should not have any duplicate<br />code in the same class.<br />The Listing 9-1 example is a more complicated class that can be used to<br />create an HTML form. To simplify the example, the form contains only text<br />input fields.<br />Listing 9-1: A Script That Contains a Class for a Form Object<br />&lt;?php<br />/* Class name: Form<br />* Description: A class that creates a simple HTML form<br />* containing only text input fields. The<br />* class has 3 methods.<br />*/<br />class Form<br />{<br />var $fields=array(); # contains field names and labels<br />var $processor; # name of program to process form<br />var $submit = “Submit Form”; # value for the submit button<br />var $Nfields = 0; # number of fields added to the form<br />/* Constructor: User passes in the name of the script where<br />* form data is to be sent ($processor) and the value to show<br />* on the submit button.<br />*/<br />function __construct($processor,$submit)<br />{<br />$this-&gt;processor = $processor;<br />$this-&gt;submit = $submit;<br />}<br />/* Display form function. Displays the form.<br />*/<br />function displayForm()<br />{<br />echo “&lt;form action=’{$this-&gt;processor}’ method=’post’&gt;”;<br />echo “&lt;table width=’100%’&gt;”;<br />for($j=1;$j&lt;=sizeof($this-&gt;fields);$j++)<br />{<br />echo “&lt;tr&gt;&lt;td align=\”right\”&gt;<br />{$this-&gt;fields[$j-1][‘label’]}: &lt;/td&gt;\n”;<br />echo “&lt;td&gt;<br />&lt;input type=’text’<br />name=’{$this-&gt;fields[$j-1][‘name’]}’&gt;<br />&lt;/td&gt;&lt;/tr&gt;\n”;<br />}<br />188 Part III: Basic PHP Programming<br />echo “&lt;tr&gt;&lt;td colspan=2 align=’center’&gt;<br />&lt;input type=’submit’<br />value=’{$this-&gt;submit}’&gt;&lt;/td&gt;&lt;/tr&gt;\n”;<br />echo “&lt;/table&gt;”;<br />}<br />/* Function that adds a field to the form. The user needs to<br />* send the name of the field and a label to be displayed.<br />*/<br />function addField($name,$label)<br />{<br />$this-&gt;fields[$this-&gt;Nfields][‘name’] = $name;<br />$this-&gt;fields[$this-&gt;Nfields][‘label’] = $label;<br />$this-&gt;Nfields = $this-&gt;Nfields + 1;<br />}<br />}<br />?&gt;<br />This class contains four properties and three methods. The properties are as<br />follows:<br /> $fields: An array that holds the fields as they are added by the user.<br />The fields in the form are displayed from this array.<br /> $processor: The name of the script that the form is sent to. This variable<br />is used in the action attribute when the form tag is displayed.<br /> $submit: The text that the user wants displayed on the submit button.<br />This variable’s value is used when the submit button is displayed.<br /> $Nfields: The number of fields that have been added to the form so far.<br />The methods in this class are as follows:<br /> __construct: The constructor, which sets the values of $processor<br />and $submit from information passed in by the user.<br /> addField: Adds the name and label for the field to the $fields array. If<br />the user added fields for first name and last name to the form, the array<br />may look as follows:<br />$fields[1][name]=first_name<br />$fields[1][label]=First Name<br />$fields[2][name]=last_name<br />$fields[2][label]=Last Name<br />and so on<br /> displayForm: Displays the form. It echoes the HTML needed for the<br />form and uses the values from the stored variables for the name of the<br />field and the label that the user sees by the field.<br />The next section describes how to use a class, including the form class<br />shown in Listing 9-1.<br />189 Chapter 9: Object-Oriented Programming Meets PHP<br />Using a Class<br />The class code needs to be in the script that uses the class. Most commonly,<br />the class is stored in a separate include file and is included in any script that<br />uses the class.<br />To use an object, you first create the object from the class. Then that object<br />can perform any methods that the class includes. Creating an object is called<br />instantiating the object. Just as you can use a pattern to create many similar<br />but individual dresses, you can use a class to create many similar but individual<br />objects. To create an object, use statements that have the following format:<br />$objectname = new classname(value,value,&#8230;);<br />$Joe = new Person(“male”);<br />$car_Joe = new Car(“red”);<br />$car_Sam = new Car(“green”);<br />$customer1 = new Customer(“Smith”,”Joe”,$custID);<br />The object is stored in the variable name, and the constructor method is<br />executed. You can then use any method in the class with statements of the<br />following format:<br />$Joe-&gt;goToWork();<br />$car_Joe-&gt;park(“illegal”);<br />$car_Sam-&gt;paintCar(“blue”);<br />$name = $customer1-&gt;getName();<br />Different objects created from the same class are independent individuals.<br />Sam’s car gets painted blue, but Joe’s car is still red. Joe gets a parking ticket,<br />but it doesn’t affect Sam.<br />The script shown in Listing 9-2 shows how to use the form class that was created<br />in the previous section and shown in Listing 9-1.<br />Listing 9-2: A Script That Creates a Form By Using the Form Class<br />&lt;?php<br />/* Script name: buildForm<br />* Description: Uses the form to create a simple HTML form<br />*/<br />require_once(“form.inc”);<br />echo “&lt;html&gt;&lt;head&gt;&lt;title&gt;Phone form&lt;/title&gt;&lt;/head&gt;&lt;body&gt;”;<br />$phone_form = new Form(“process.php”,”Submit Phone”);<br />$phone_form-&gt;addField(“first_name”,”First Name”);<br />$phone_form-&gt;addField(“last_name”,”Last Name”);<br />$phone_form-&gt;addField(“phone”,”Phone”);<br />190 Part III: Basic PHP Programming<br />echo “&lt;h3&gt;Please fill out the following form:&lt;/h3&gt;”;<br />$phone_form-&gt;displayForm();<br />echo “&lt;/body&gt;&lt;/html&gt;”;<br />?&gt;<br />First, the script included the file containing the class into the script. The<br />class is stored in the file form.inc. The script creates a new form object called<br />$phone_form. Three fields are added. The form is displayed. Notice that some<br />additional HTML code was output in this script. That HTML could have been<br />added to the displayForm method just as easily.<br />The script creates a form with three fields, using the form class. Figure 9-1<br />shows the resulting Web page.<br />Making Properties and Methods Private<br />Properties and methods can be public or private. Public means that methods<br />or properties inside the class can be accessed by the script that is using the<br />class or from another class. For example, the following class has a public<br />attribute and a public method as shown:<br />class Car<br />{<br />var $gas = 0;<br />function addGas($amount)<br />{<br />$this-&gt;gas = $this-&gt;gas + $amount;<br />echo “$amount gallons added to gas tank”;<br />}<br />}<br />Figure 9-1:<br />The form<br />displayed by<br />the script in<br />Listing 9-2.<br />191 Chapter 9: Object-Oriented Programming Meets PHP<br />The public attribute in this class can be accessed by a statement in the script<br />outside the class, as follows:<br />$mycar = new Car;<br />$gas_amount = $mycar-&gt;gas;<br />After these statements are run, $gas_amount contains the value stored in<br />$car inside the object. The attribute can also be modified from outside the<br />class, as follows:<br />$mycar-&gt;gas = 20;<br />Allowing script statements outside the class to directly access the properties<br />of an object is poor programming practice. All interaction between the object<br />and the script or other classes should take place using methods. The example<br />class has a method to add gas to the car. All gas should be added to the car<br />using the addGas method, which is also public, using statements similar to<br />the following:<br />$new_car = new Car;<br />$new_car-&gt;addGas(5);<br />You can prevent access to properties by making them private. PHP provides<br />two options for making properties and methods private, as follows:<br /> private: No access from outside the class, either by the script or from<br />another class.<br /> protected: No access from outside except from a class that is a child of<br />the class with the protected attribute or method.<br />You can make an attribute private as follows:<br />private $gas = 0;<br />With the attribute specified as private, a statement like the previous statement<br />that attempts to access the attribute directly gets the following error message:<br />Fatal error: Cannot access private property car::$gas in<br />c:\testclass.php on line 17<br />Now, the only way gas can be added to the car is using the addGas method.<br />Because the addGas method is part of the class statement, it can access the<br />private attribute.<br />In the same way, you can make methods private or protected. In this case,<br />you want the outside world to use the addGas method. However, you may<br />want to be sure that people buy the gas that is added. You don’t want any<br />stolen gas in your car. You could write the following class:<br />192 Part III: Basic PHP Programming<br />class Car<br />{<br />private $gas = 0;<br />private function addGas($amount)<br />{<br />$this-&gt;gas = $this-&gt;gas + $amount;<br />echo “$amount gallons added to gas tank”;<br />}<br />function buyGas($amount)<br />{<br />$this-&gt;addGas($amount);<br />}<br />}<br />With this class, the only way gas can be added to the car from the outside is<br />with the buyGas method. The buyGas method uses the addGas method to<br />add gas to the car, but the addGas method can’t be used outside the class<br />because it is private. If a statement outside the class attempts to use addGas,<br />as follows, a fatal error is displayed, as it was for the private attribute:<br />$new_car = new Car;<br />$new_car-&gt;addGas(5);<br />However, you can now add gas to the car using the buyGas method, as follows:<br />$new_car = new Car;<br />$new_car-&gt;buyGas(5);<br />You see the following output:<br />5 gallons added to gas tank<br />It’s good programming practice to hide as much of your class as possible.<br />Make all properties private. Only make methods public that absolutely need<br />to be public.<br />PHP also provides an option to make properties and methods public. Although<br />you don’t need to use the public option, because public is the default, it helps<br />to make the class more readable. The following statement:<br />public $gas = 0;<br />has the same effect as:<br />var $gas = 0;<br />193 Chapter 9: Object-Oriented Programming Meets PHP<br />Using Exceptions<br />PHP provides an error-handling class called Exception. You can use this class<br />to handle undesirable things that happen in your script. When the undesirable<br />thing that you define happens, a routine you have written is performed. In<br />object-oriented talk, this is called throwing an exception.<br />In the car class, you keep track of the gas in the car and stop the car when it<br />runs out of gas. You expect your program to detect 0 gallons and react. You<br />don’t expect the gas in the gas tank to be a negative amount. You consider<br />that to be an exception, and you want to be sure that won’t happen in your<br />script. To deal with this, you can write a routine that uses the Exception<br />class to watch for a negative gas amount. The following statements check for<br />this situation:<br />$this-&gt;gas = $this-&gt;gas – 5;<br />try<br />{<br />if ($this-&gt;gas &lt; 0)<br />{<br />throw new Exception( “Negative amount of gas.”);<br />}<br />}<br />catch (Exception $e)<br />{<br />echo $e-&gt;getMessage();<br />echo “\n&lt;br /&gt;\n”;<br />exit();<br />}<br />The preceding script contains a try block and a catch block:<br /> In the try block, you test a condition. If the condition is TRUE, you throw<br />an exception — in other words, you create an Exception object. The<br />Exception object has a property that stores the message you sent when<br />you threw the exception.<br /> In the catch block, you catch the exception and call it $e. Then you execute<br />the statements in the catch block. One of the statements is a call to<br />a method called getMessage in the Exception class. The getMessage<br />function returns the message that you stored, and your statement echoes<br />the returned message. The statements then echo the end-of-line characters<br />so the message is displayed correctly. The script stops on the exit<br />statement.<br />If no exception is thrown, the catch block has nothing to catch, and it is<br />ignored. The script proceeds to the statements after the catch block.<br />194 Part III: Basic PHP Programming<br />Copying Objects<br />PHP provides a method you can use to copy an object. The method is __clone,<br />with two underscores. You can write your own __clone method in a class if<br />you want to specify statements to run when the object is copied. If you don’t<br />write your own, PHP uses it’s default __clone method that copies all the<br />properties as is. The two underscores indicate that the clone method is a<br />different type of method, and thus is called differently, as shown in the following<br />example.<br />For example, you could write the following class:<br />class Car<br />{<br />private $gas = 0;<br />private $color = “red”;<br />function addGas($amount)<br />{<br />$this-&gt;gas = $this-&gt;gas + $amount;<br />echo “$amount gallons added to gas tank”;<br />}<br />function __clone()<br />{<br />$this-&gt;gas = 0;<br />}<br />}<br />Using this class, you could create an object and copy it as follows:<br />$firstCar = new Car;<br />$firstCar-&gt;addGas(10);<br />$secondCar=clone $firstCar;<br />After these statements, you have two cars:<br /> $firstCar: This car is red and contains 10 gallons of gas. The 10 gallons<br />were added with the addGas method.<br /> $secondCar: This car is red, but contains 0 gallons of gas. The duplicate<br />car is created using the __clone method in the Car class. This method<br />sets gas to 0 and doesn’t set $color at all.<br />If you did not have a __clone method in the Car class, PHP would use a default<br />__clone method that would copy all the properties, making $secondCar both<br />red and containing 10 gallons of gas.<br />195 Chapter 9: Object-Oriented Programming Meets PHP<br />Destroying Objects<br />You can destroy an object with the following statement:<br />unset($objName);<br />For example, you could create and destroy an object of the Car class with the<br />following statements:<br />$myCar = new Car;<br />unset($myCar);<br />After $myCar is unset, the object no longer exists at all.<br />PHP provides a method that is automatically run when an object is destroyed.<br />You add this method to your class and call it __destruct. For example, the<br />following class contains a __destruct method:<br />class Bridge<br />{<br />function __destruct()<br />{<br />echo “The bridge is destroyed”;<br />}<br />}<br />If you use the following statements, the object is created and destroyed:<br />$bigBridge = new Bridge;<br />unset($bigBridge);<br />The output from these statements is:<br />The bridge is destroyed<br />The output is echoed by the __destruct method when the object is unset.<br />The __destruct method is not required. It’s just available for you to use if<br />you want to execute some statements when the object is destroyed. For<br />example, you might want to close some files or copy some information to<br />your database.<br />196 Part III: Basic PHP Programming<br />Part IV<br />Common PHP<br />Applications<br />In this part . . .<br />Part IV shows how to apply the features and functionality<br />of PHP to common programming tasks. You find<br />out how to write scripts to do the tasks that programmers<br />most often need to do, and you also discover how PHP<br />can interact with databases, operating systems, and e-mail<br />applications. When you finish this part, you will know how<br />to write scripts by using HTML forms to interact with your<br />user, how to handle data, and many other tasks commonly<br />performed with PHP.<br />Chapter 10<br />The Basics of Web Applications<br />In This Chapter<br /> Understanding Web site security<br /> Displaying static pages<br /> Collecting information from users with HTML forms<br /> Processing information received from users<br />PHP was originally designed for Web programming, and although its use<br />for general-purpose scripts is growing, PHP is still used most frequently<br />to develop dynamic Web sites. Static Web pages — pages where all users see<br />the same Web page — don’t allow for interaction between the user and the<br />Web page. Dynamic Web pages, on the other hand, allow users to interact<br />with the Web page. Users may see different Web pages, based on information<br />they type into the Web page. For example, users might be required to type in<br />valid usernames and passwords before they can see any Web pages on the<br />Web site, allowing the site to customize Web pages based on users’ previous<br />preferences or profiles. Alternatively, users may select a type of product from<br />an online catalog and see only the Web pages containing products of the type<br />they select.<br />A dynamic Web page collects information from the user with an HTML form.<br />The information that the user types into the form is then processed, depending<br />on what the information will be used for. The information may be stored<br />(see Chapter 12 for more on storing data using PHP) or used in a conditional<br />statement to display alternative Web pages.<br />In this chapter, I do not tell you about the HTML required to display a form; I<br />assume you already know HTML. (If you don’t know HTML or need a refresher,<br />check out HTML 4 For Dummies, 4th Edition, by Ed Tittel and Natanya Pitts<br />[Wiley Publishing, Inc.].) What I do tell you is what you need to consider to<br />keep your Web site secure and how to use PHP to display HTML forms and to<br />process the information that users type into the form.<br />Securing Your Web Site<br />Web applications are particularly vulnerable to attacks from the outside.<br />Most Web sites are open to the public, offering services, products, or information<br />to anyone who visits. Dynamic Web sites are particularly vulnerable<br />because they accept information from visitors to the site. Although the vast<br />majority of visitors are good guys, trying to use the Web site for its intended<br />purpose, a few people out have intentions that are not so pure, including the<br />following groups:<br /> People who want to steal things: These are the folks who hope to find a<br />file sitting around full of valid credit card numbers or a map to the pot of<br />gold at the end of the rainbow.<br /> People who want to destroy your Web site: These saboteurs may think<br />it’s funny to wreck your site, or they may cause damage just to prove<br />how smart they are.<br /> People who want to harm your users: These folks add things to your<br />Web site that harm or steal from the people who visit your site.<br />This is not a security book. Security is a large, complex issue, and I am not a<br />security expert. Nevertheless, I want to call a few issues to your attention and<br />make some suggestions to help you protect your Web site. The following measures<br />will increase the security of your Web site, but if your site handles really<br />important, secret information, read some security books and talk to some<br />experts:<br /> Ensure the security of the computer that hosts your Web site. This is the<br />responsibility of the system administrator, which may or may not be you.<br /> Keep information private. Don’t be more public than necessary. Store<br />your information so it can’t be easily accessed from the Web.<br /> Be cautious of information from users. Always clean any information<br />that you didn’t generate yourself.<br /> Use a secure Web server. This requires extra work, but it’s important if<br />you have top-secret information.<br />These topics are covered in more detail in the following sections.<br />Ensuring the security of the host computer<br />Your first line of defense is to make sure that the computer that hosts the Web<br />site is secure. The computer’s system administrator is responsible for keeping<br />unauthorized visitors and vandals out of the system. Security measures include<br />such things as firewalls, encryption, password shadowing, scan detectors, and<br />200 Part IV: Common PHP Applications<br />so on. In most cases, the system administrator is not you. If it is, you need to<br />do some serious investigation into security issues. If you’re using a Web hosting<br />company, you may want to discuss security with those folks, to reassure<br />yourself that they’re using sufficient security measures.<br />Keeping information private<br />Keep information as private as possible. Of course, the Web pages you want<br />visitors to see must be stored in your public Web space directory. However,<br />users don’t need to see the names of the files stored there. You may have<br />noticed that sometimes a site shows you a list of all the files in the directory.<br />This is generally not a good idea. Your Web site isn’t very secure if a visitor<br />can look at any file on your site.<br />This list of files is displayed when the URL that the visitor types in points at a<br />directory, rather than a specific file, and the directory doesn’t contain a file<br />with the default directory name. Most Web servers look first in a directory for<br />a default name, specified in the server configuration, often index.html. If the<br />directory doesn’t contain a file with this default name, the server may display<br />a list of files in the directory. A better choice is to have the Web server display<br />a message telling visitors that they can’t access the directory, similar to the<br />following message:<br />Forbidden<br />You don’t have permission to access /secretdirectory on this<br />server.<br />A setting in the configuration of the Web server determines whether users<br />see a list of files or a message. The Web server administrator can change the<br />behavior. For example, in Apache, you control what is displayed by using an<br />option called Indexes, which can be turned on or off in the httpd.conf file<br />as follows:<br />Options Indexes // turns file listing on<br />Options -Indexes // turns file listing off<br />See the documentation for your Web server to allow or not allow directory<br />listings in the user’s Web browser.<br />It’s also not wise to name a file an obvious, guessable name. For example, if<br />you have a file containing secret passwords, it’s not a good idea to name it<br />passwords.php. You may want to call the file something odd or boring, such<br />as vegetableRecipes.php. I know this suggestion violates other parts of<br />the book where I promote informative filenames, but this is a special case.<br />Malicious people sometimes do obvious things like typing www.yoursite.<br />com/passwords.html into their browsers to see what happens.<br />201 Chapter 10: The Basics of Web Applications<br />Not everything needs to be public. For example, your database should not be<br />stored in a public location. In fact, it can be stored on a totally different computer.<br />Also, as discussed in Chapter 8, include files can be stored in a separate<br />location, a space on the computer that can’t be accessed from the Web.<br />Being cautious of information from users<br />Users can enter dangerous information into forms, either accidentally or with<br />malicious intent. Therefore, never store or use information from forms without<br />checking it first. Check it for reasonable formats and dangerous characters.<br />Even characters entered accidentally can sometimes cause problems in your<br />database or scripts. In particular, you don’t want to accept HTML tags — such<br />as &lt;script&gt; tags — from forms. Using script tags, a user can enter an actual<br />script, perhaps a malicious one. If you accept the form field without checking<br />it and store it in your database, you could have any number of problems, particularly<br />if the stored script was sent in a Web page to a visitor to your Web<br />site. For more on checking data from forms, see the section “Checking the<br />information” later in this chapter.<br />Using a secure Web server<br />Communication between your Web site and its visitors is not totally secure.<br />When the files on your Web site are sent to the user’s browser, it is possible<br />for someone on the Internet between you and the user to read the contents of<br />these files as they pass by. For most Web sites, this isn’t an issue, but if your<br />site collects or sends credit card numbers or other secret information, use a<br />secure Web server to protect this data.<br />Secure Web servers use SSL (Secure Sockets Layer) to protect communication<br />sent to and received from browsers. This is similar to the scrambled telephone<br />calls you hear about in spy movies. The information is encrypted (translated<br />into coded strings) before it is sent across the Web. The receiving software<br />decrypts it into its original content. In addition, your Web site uses a certificate<br />that verifies your identity. Using a secure Web server is extra work, but<br />it’s necessary for some applications.<br />You can tell when you’re communicating using SSL because the URL begins<br />with https rather than http.<br />Information about secure Web servers is specific to the Web server you’re<br />using. To find out more about using SSL, look at the Web site for the Web server<br />you’re using. For example, if you’re using Apache, check out two open source<br />projects that implement SSL for Apache at www.modssl.org and www.apachessl.<br />org. Commercial software is also available that provides a secure server<br />202 Part IV: Common PHP Applications<br />based on the Apache Web server. If you’re using Microsoft IIS, search for SSL<br />on the Microsoft Web site at www.microsoft.com.<br />Displaying Static Web Pages<br />The simplest Web page design is a static Web page. If you need only static Web<br />pages on your Web site, you don’t need PHP. However, you may need static<br />Web pages interspersed with your dynamic pages.<br />PHP can be used to display any Web pages, including static pages. You simply<br />use echo statements to echo the appropriate HTML. If you have a Web page<br />containing only HTML that needs to be displayed in a PHP script, the most<br />efficient way to display the static Web page is to include it where it’s needed<br />with the following statement:<br />include(“filename”);<br />If you need to turn an existing static Web page into a PHP script, for some<br />unlikely reason, you can add PHP tags at the beginning and end of the file.<br />Then add echo at the top of the file and enclose the existing HTML code in<br />single quotes.<br />Working with HTML Forms<br />For a Web page to be interactive, it must collect information from the user,<br />which is done with HTML forms. The information collected may simply be a<br />username and password for a user login. A form can also be long and elaborate,<br />collecting a great deal of information from a user, such as shipping and<br />credit card information for an online purchase application or a survey form<br />asking many questions for research purposes.<br />To use HTML forms to collect information, your script displays the form on<br />the Web site, and the user types information into text fields or selects items<br />from a list. The user then clicks a button to submit the form information. When<br />the form is submitted, the information in the form is passed to a second separate<br />script, which processes the information.<br />This chapter provides basic information on using forms in a dynamic Web site.<br />Often the information collected is stored in a database, or the form is displayed<br />by using information retrieved from a database. If you’re planning to use HTML<br />forms teamed with a MySQL database, you can find more detailed information<br />and more complex solutions in PHP &amp; MySQL For Dummies by yours truly<br />(Wiley Publishing, Inc.).<br />203 Chapter 10: The Basics of Web Applications<br />Collecting information<br />from Web site visitors<br />HTML forms are used to collect information from Web site visitors. If you’re<br />unfamiliar with HTML forms, check out HTML 4 For Dummies, 4th Edition, by<br />Ed Tittel and Natanya Pitts.<br />Displaying HTML Forms<br />To display a form by using PHP, you can do one of the following:<br /> Use echo statements to echo the HTML for a form. The following statements<br />echo a form by using this method:<br />echo “&lt;form action=’processform.php’ method=’POST’&gt;\n<br />&lt;input type=’text’ name=’name’&gt;\n<br />&lt;input type=’submit’ value=’Submit Name’&gt;\n<br />&lt;/form&gt;\n”;<br /> Use plain HTML outside the PHP sections. For a plain static form, you<br />don’t need to include it in a PHP section. For example, the following<br />statements produce the same form as the preceding example:<br />&lt;?php<br />statements in PHP section<br />?&gt;<br />&lt;form action=”processform.php” method=”POST”&gt;<br />&lt;input type=”text” name=”fullname”&gt;<br />&lt;input type=”submit” value=”Submit Name”&gt;<br />&lt;/form&gt;<br />&lt;?php<br />statements in PHP section<br />?&gt;<br />Both of these examples display the same form, which is shown in Figure 10-1.<br />Figure 10-1:<br />A form<br />produced<br />by HTML<br />statements.<br />204 Part IV: Common PHP Applications<br />The form in Figure 10-1 has one text field, which is blank. It also has a button<br />labeled Submit Name. The user types a name into the text field and clicks the<br />button. When the user submits the form, the information in the form is passed<br />to the script designated in the action attribute of the form tag. In this example,<br />the action attribute is action=”processform.php”, so when the user clicks<br />the submit button, the script processform.php is called, and the information<br />in the form is passed to it. (I am using processform.php as an example name<br />here. You can name the script that processes the form with any name you<br />want.)<br />PHP allows you to use variables in PHP forms, making the forms more powerful.<br />Using variables, you can display information in the input text fields and<br />build dynamic lists for selection boxes, radio buttons, and check boxes.<br />Displaying information in text fields<br />In some cases, you may want to display information in the text fields rather<br />than just display blank fields. For example, you may want to display a default<br />value in a field. Or, when displaying a form to a user to reenter incorrect<br />information, you want to retain the correct information so that the user has<br />to retype information only in the field with the error.<br />To display text fields that contain information, you use the following format<br />for the input field HTML statements:<br />&lt;input type=”text” name=”fieldname” value=”content”&gt;<br />For example, suppose you’re displaying a form to collect a customer’s name<br />and address. You know that most of your customers live in the U.S., so you<br />decide to display the field with US as the default. If customers are from the<br />U.S., you save them some typing and avoid errors they may type in. If customers<br />are not from the U.S., they can just replace US with the correct country.<br />You can display the country field with the following statement:<br />&lt;input type=”text” name=”country” value=”US”&gt;<br />In some cases, you may want to display variable information in a text field.<br />You can use a PHP variable to display information. For example, suppose you<br />have customer information (such as a phone number) stored in a database,<br />and you want to display the information in a form so that the user can update<br />any incorrect or outdated information. First, you retrieve the customer information<br />from a database (see Chapter 12 for the lowdown on using a database)<br />and store the information in variables. Next, you can display the form by using<br />the information in the variables in one of two ways. You can create an input<br />field in an HTML section by using a short PHP section for the value only, as<br />follows:<br />&lt;input type=”text” name=”phone” value=”&lt;?php echo $phone ?&gt;”&gt;<br />205 Chapter 10: The Basics of Web Applications<br />Alternatively, you can create an input field by using an echo statement inside<br />a PHP section:<br />echo “&lt;input type=’text’ name=’phone’ value=’$phone’&gt;”;<br />If you’re using a long form with only an occasional variable, it’s more efficient<br />to use the first format. If your form uses many variables, it’s more efficient to<br />use the second format.<br />The script in Listing 10-1 displays a form containing customer information.<br />Figure 10-2 shows the output from this script.<br />Listing 10-1: A Script That Displays an HTML Form<br />&lt;?php<br />/* Script name: displayForm<br />* Description: Script displays a form and populates the<br />* form fields with the values of an array.<br />*/<br />echo “&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Customer Address&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;”;<br />$customer = array( “firstName”=&gt;”John”,<br />“midName”=&gt;”Jay”,<br />“lastName”=&gt;”Smith”,<br />“street”=&gt;”1234 Oak St.”,<br />“city”=&gt;”Smalltown”,<br />“state”=&gt;”ID”,<br />“zip”=&gt;”88888”);<br />Figure 10-2:<br />A form<br />showing a<br />customer’s<br />address.<br />206 Part IV: Common PHP Applications<br />$labels = array( “firstName”=&gt;”First Name:”,<br />“midName”=&gt;”Middle Name:”,<br />“lastName”=&gt;”Last Name:”,<br />“street”=&gt;”Street Address:”,<br />“city”=&gt;”City:”,<br />“state”=&gt;”State:”,<br />“zip”=&gt;”Zipcode:”);<br />echo “&lt;h2 align=’center’&gt;Address for<br />{$customer[‘firstName’]}<br />{$customer[‘midName’]}<br />{$customer[‘lastName’]}&lt;/h2&gt;\n”;<br />echo “&lt;p align=’center’&gt;<br />&lt;b&gt;Please check the information below and change any<br />information that is incorrect.&lt;/b&gt;<br />&lt;hr&gt;<br />&lt;form action=’processform.php’ method=’POST’&gt;<br />&lt;table width=’95%’ border=’0’ cellspacing=’0’<br />cellpadding=’2’&gt;\n”;<br />foreach($customer as $field=&gt;$value)<br />{<br />echo “&lt;tr&gt;<br />&lt;td align=’right’&gt; &lt;B&gt;{$labels[$field]} &lt;/br&gt;&lt;/td&gt;<br />&lt;td&gt;&lt;input type=’text’ name=’$field’ size=’65’<br />maxlength=’65’ value=’{$customer[$field]}’&gt;&lt;/td&gt;<br />&lt;/tr&gt;”;<br />}<br />echo “&lt;/table&gt;<br />&lt;div align=’center’&gt;&lt;p&gt;&lt;input type=’submit’<br />value=’Submit Address’&gt; &lt;/p&gt;&lt;/div&gt;<br />&lt;/form&gt;”;<br />?&gt;<br />&lt;/body&gt;&lt;/html&gt;<br />Notice the following in displayForm.php, shown in Listing 10-1:<br /> An array is created at the start of the script, which contains the information<br />that is displayed in the form. In real-life applications, you probably<br />obtain this information from a database, a file, or other sources.<br /> An array is created that contains the labels that are used in the form.<br /> The script processform.php is named as the script that runs when the<br />form is submitted. The information in the form is sent to processform.<br />php, which processes the information.<br /> The form is formatted with an HTML table. Tables are an important<br />part of HTML. If you’re not familiar with HTML tables, check out HTML 4<br />For Dummies, 4th Edition, by Ed Tittel and Natanya Pitts.<br /> The script loops through the $customer array with a foreach statement.<br />The HTML code for a table row is output in each loop. The appropriate<br />array values are used in the HTML code.<br />207 Chapter 10: The Basics of Web Applications<br />For security reasons, always include maxlength — which defines the number<br />of characters users are allowed to type into the field — in your HTML statement.<br />Limiting the number of characters helps prevent the bad guys from<br />typing malicious code into your form fields. If the information will be stored<br />in a database, set maxlength to the same number as the width of the column<br />in the database table.<br />Adding selection lists, radio buttons, and check boxes to forms<br />Other elements in HTML forms, such as selection lists, radio buttons, and<br />check boxes, can be used with variables. To use one of these elements in your<br />form, you echo the HTML that creates the form element and use variables for<br />information that changes. For example, you can use a selection list in your<br />form with the following statements:<br />echo “&lt;select name=’dinner’ &gt;<br />&lt;option&gt;$dinner1&lt;/option&gt;<br />&lt;option&gt;$dinner2&lt;/option&gt;<br />&lt;/select&gt;”;<br />The selections in this selection list are the values in the variables. For example,<br />$dinner1 could display chicken, and $dinner2 could display fish. When<br />the user submits the form, the selected value is passed to the next script.<br />Similarly, you can use radio buttons in your form, as follows:<br />echo “&lt;input type=’radio’ name=’dinner’<br />value=’$dinner1’&gt;$dinner1<br />&lt;input type=’radio’ name=’dinner’<br />value=’$dinner2’&gt;$dinner2”;<br />The radio buttons that users can select are chicken and fish.<br />Check boxes allow users to check more than one box. Therefore, when you<br />use check boxes, the name attribute must be an array, as in the following<br />example:<br />echo “&lt;input type=’checkbox’ name=’dinner[]’<br />value=’$dinner1’&gt;$dinner1<br />&lt;input type=’checkbox’ name=’dinner[]’<br />value=’$dinner2’&gt;$dinner2”;<br />The form stores all the checked boxes in an array called $dinner. If both of the<br />values above are selected, the form stores both values in the array as follows:<br />$dinner[0]=chicken<br />$dinner[1]=fish<br />The script in Listing 10-2 displays a Web page with a selection list that allows<br />the user to select a date. In this form, the current date is selected by default.<br />208 Part IV: Common PHP Applications<br />Listing 10-2: A Script That Displays a Date Selection List<br />&lt;?php<br />/* Script name: displayDate<br />* Description: Script displays a selection list, with<br />* three parts&#8211;months, days, and years. The<br />* current date is selected by default.<br />*/<br />echo “&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Date&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;”;<br />/* Create an array of month numbers and names */<br />$monthName = array(1=&gt; “January”, “February”, “March”,<br />“April”, “May”, “June”, “July”,<br />“August”, “September”, “October”,<br />“November”, “December”);<br />$today = Time(); #stores today’s date<br />echo “&lt;div align=’center’&gt;&lt;b&gt;Select a date:&lt;/b&gt;<br />&lt;form action=’processform.php’ method=’POST’&gt;\n”;<br />/* Build selection list for month */<br />$todayMO = date(“m”,$today); #get the month from $today<br />echo “&lt;select name=’dateMO’&gt;\n”;<br />for ($n=1;$n&lt;=12;$n++)<br />{<br />echo “&lt;option value=$n”;<br />if ($todayMO == $n) #adds selected attribute if today<br />{<br />echo “ selected”;<br />}<br />echo “&gt; $monthName[$n]\n”;<br />}<br />echo “&lt;/select&gt;”;<br />/* build selection list for the day */<br />$todayDay= date(“d”,$today); #get the day from $today<br />echo “&lt;select name=’dateDay’&gt;\n”;<br />for ($n=1;$n&lt;=31;$n++)<br />{<br />echo “ &lt;option value=$n”;<br />if ($todayDay == $n )<br />{<br />echo “ selected”;<br />}<br />echo “&gt; $n\n”;<br />}<br />echo “&lt;/select&gt;\n”;<br />/* build selection list for the year */<br />$startYr = date(“Y”, $today); #get the year from $today<br />echo “&lt;select name=’dateYr’&gt;\n”;<br />for ($n=$startYr;$n&lt;=$startYr+3;$n++)<br />(continued)<br />209 Chapter 10: The Basics of Web Applications<br />Listing 10-2 (continued)<br />{<br />echo “ &lt;option value=$n”;<br />if ($startYr == $n )<br />{<br />echo “ selected”;<br />}<br />echo “&gt; $n\n”;<br />}<br />echo “&lt;/select&gt;\n”;<br />echo “&lt;/form&gt;\n”;<br />?&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />The script creates $monthName, an array with elements that have all the<br />month numbers for keys and month names for values. Next it stores today’s<br />date in $today.<br />The rest of the script echoes a form that contains three selection lists, in drop<br />down boxes, for the three parts of the date: month, day, and year. For the<br />month, the foreach list creates a list of all the months, taken from the array<br />$monthName. Each month is compared with the month of today’s date stored<br />in $today. If the month is the same as today’s month, then the “selected”<br />attribute is added to the selection, so the month is the default selection.<br />Similar lists are created for day and year. These lists are just numbers, so a for<br />loop is used to create the list of numbers for the selection list. Again, each day<br />and year are compared to the day and year in today’s date and the current<br />day and year are selected as the default.<br />The form displayed by the script in Listing 10-2 is shown in Figure 10-3.<br />Figure 10-3:<br />A form that<br />allows a<br />user to<br />select<br />a date.<br />210 Part IV: Common PHP Applications<br />Receiving the information<br />In the form tag, you tell PHP which script to run when the user clicks the<br />submit button. You do this with the attribute action=”scriptname” in the<br />form tag. For example, in Listings 10-1 and 10-2 earlier in this chapter, I use<br />action=”processform.php”. When the user clicks the submit button, the<br />script runs and receives the information from the form.<br />The form data is available in the processing script in the PHP built-in arrays,<br />as described in Chapter 6. Information from forms that use the POST method<br />is available in the built-in array called $_POST. If your form uses the GET<br />method, the information is available in the array $_GET. Both types of form<br />information are also stored in an array called $_REQUEST. Each array index is<br />the name of the input field in the form. You get information from the array by<br />using the form field name as the array key. For example, suppose that you<br />echo the following field in your form that uses the POST method:<br />echo “&lt;input type=’text’ name=’firstName’&gt;”;<br />Setting name to firstName allows the processing script to use the variable<br />$_POST[‘firstName’], which contains the text the user typed into the field.<br />The information the user selects from selection drop-down lists or radio buttons<br />is similarly available for use. Because the user can check more than one<br />check box, information in check boxes is an array in the $_POST array and<br />available as a multidimensional array. For example, if two check boxes for<br />dinner choices (as described in the previous section) are both checked and<br />submitted, the information is available in the following array:<br />$_POST[‘dinner’][0] = chicken<br />$_POST[‘dinner’][1] = fish<br />The script in Listing 10-3 displays the values for all the fields in a form displayed<br />in Figure 10-2 earlier in the chapter.<br />Listing 10-3: A Script That Displays All the Fields from a Form<br />&lt;?php<br />/* Script name: displayFormFields<br />* Description: Script displays all the information passed<br />* from a form.<br />*/<br />echo “&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Customer Address&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;”;<br />foreach ($_POST as $field =&gt; $value)<br />{<br />echo “$field = $value&lt;br&gt;”;<br />}<br />?&gt;<br />&lt;/body&gt;&lt;/html&gt;<br />211 Chapter 10: The Basics of Web Applications<br />You can use this script to process the information from the form displayed<br />in Figure 10-2, which displays a customer’s address. To do so, you must use<br />the action attribute action=”displayFormFields.php” in the script<br />displayForm.php, which is shown in Listing 10-1. Then when the user clicks<br />the Submit Address button in the form, the script in Listing 10-3 runs and produces<br />the following output on a new Web page:<br />firstName = John<br />lastName = Smith<br />street = 1234 Oak St.<br />city = Smalltown<br />state = ID<br />zip = 88888<br />The script shown in Listing 10-3 displays all the values passed via the form in<br />Figure 10-2. In most cases, you don’t want to just display the values. Usually,<br />you want to use the values for a purpose. Either you use the values in a conditional<br />statement or you store the values, usually in a database.<br />212 Part IV: Common PHP Applications<br />POST versus GET<br />You use one of two methods to submit form<br />information. The methods pass the form data<br />differently and have different advantages and<br />disadvantages:<br /> GET method: The form data is passed by<br />adding it to the URL that calls the formprocessing<br />script. For example, the URL may<br />look like this:<br />processform.php?lname=Smith&amp;fname=Gol<br />iath<br />The advantages of this method are simplicity<br />and speed. The disadvantages are that<br />less data can be passed and the information<br />is displayed in the browser, which can<br />be a security problem in some situations.<br /> POST method: The form data is passed as a<br />package in a separate communication with<br />the processing script.<br />The advantages of this method are unlimited<br />information passing and security of the<br />data. The disadvantages are the additional<br />overhead and slower speed.<br />For CGI programs other than PHP, the program<br />that processes the form must find the information<br />and put the data into variables. In this case,<br />the GET method is much simpler and easier to<br />use. Many programmers use the GET method<br />for this reason. However, PHP does all this work<br />for you. The GET and POST methods are equally<br />easy to use in PHP scripts. Therefore, when<br />using PHP, it’s almost always better to use the<br />POST method, because you have the advantages<br />of the POST method (unlimited data passing,<br />better security) without its main disadvantage<br />(more difficult to use).<br />Checking the information<br />Before you use the values in your script, you need to check the variables to<br />make sure they contain what you expect them to contain. The user may have<br />left required fields blank when entering information. The user may have made<br />mistakes in typing information, so the information makes no sense. Or, the user<br />may even have typed in malicious information that can cause problems for<br />you or for visitors using your Web site. Thus, never trust information received<br />from outside sources. Always check any information received in a form.<br />Validating information<br />Checking the information is called validating the information and includes<br />checking for empty fields and checking the format of the information, as<br />described in the following list:<br /> Checking for empty fields: You can require users to enter information<br />in a field. If the field is blank, the user is told that the information is<br />required, and the form is displayed again so the user can type the missing<br />information.<br /> Checking the format of the information: Whenever users must type<br />information in a form, you can expect a certain number of typos. You<br />can detect some of these errors when the form is submitted and then<br />point out errors to users and request that they type the information<br />again. For example, ab3&amp;*xx is clearly not a valid zip code.<br />You can check for empty fields by using the following function:<br />empty($_POST[‘fieldname’])<br />For example, you could use the following code in your processing script:<br />if(empty($_POST[‘fieldname’]))<br />{<br />echo “Field is blank”;<br />statements that redisplay the field<br />}<br />Checking the format of information passed into a form can help identify typos.<br />For example, if the user types 8899776 in the zip code field, you know this is<br />not a valid zip code. This information is too long to be a zip code and too short<br />to be a zip + 4 code.<br />213 Chapter 10: The Basics of Web Applications<br />Checking the format also helps protect you from malicious users — users<br />who want to damage your Web site or your database or steal information<br />from you or your users. For example, you don’t want users to enter HTML<br />tags into a form field, something that can have unexpected results when sent<br />to a browser. (A script tag that allows a user to enter a script into a form field<br />is a particularly dangerous tag.)<br />If you check each field for its expected format, you can catch typos and prevent<br />most malicious content. However, checking information is a balancing<br />act. You want to catch as much incorrect data as possible, but you don’t want<br />to block legitimate information. For example, when you’re checking a phone<br />number, you limit it to numbers. The problem with this check is that it would<br />screen out legitimate phone numbers in the form such as 555-5555 or (888)<br />555-5555. So, you also need to allow hyphens parentheses, and spaces. You<br />could limit the field to a length of 14 characters, including parentheses, spaces,<br />and hyphens, but this screens out overseas numbers or numbers that include<br />an extension. The bottom line: You need to think carefully about what information<br />you want to accept or screen out for any field.<br />Using regular expressions to check user input<br />You can check field information by using regular expressions, which are<br />described in Chapter 7. You compare the information in the field to a pattern<br />to see if it matches. If it does not match, you have determined that the information<br />in the field is incorrect, and you can ask the user to reenter it.<br />For example, suppose you want to check an input field that contains the user’s<br />last name. You can expect names to contain letters, not numbers, and possibly<br />apostrophes (O’Hara), hyphens (Smith-Jones), and spaces (Van Dyke). Also,<br />it’s difficult to imagine a name longer than 50 characters. Thus, you can use<br />the following statements to check a name:<br />$last_name = trim($_POST[‘last_name’]);<br />if ( !ereg(“[A-Za-z’ -]{1,50}”,$last_name)<br />{<br />do stuff to require user to reenter last name;<br />}<br />First, use the trim function to remove any beginning or trailing blank spaces —<br />they’re not needed. Notice that the condition in the if statement is negative.<br />That is, the exclamation mark (!) means not. So, the if statement says: If the<br />variable does not match the pattern, execute the if block.<br />If you want to list a hyphen (-) as part of a set of allowable characters surrounded<br />by square brackets ([ ]), you must list the hyphen at the beginning<br />or at the end of the list. Otherwise, if you put it between two characters, the<br />script will interpret it as the range between the two characters, such as A-Z.<br />214 Part IV: Common PHP Applications<br />Using a script to create, display, and validate a form<br />The script in Listing 10-4 validates data received from a form. The script displays<br />the empty form when it is first run. When the user submits the form, the<br />same script is run again, and the form information is passed to it. The script<br />checks the form fields for blank fields and for incorrectly formatted fields. If it<br />finds errors, it displays an error message and redisplays the form. If all the<br />form information passes the checks, the script displays the user’s name and<br />address.<br />The script requires two include files. One file, shown in Listing 10-5, creates<br />an array that is used to build the form. The other include file, shown in Listing<br />10-6, displays the form.<br />Listing 10-4: A Script That Checks All the Data in the Form Fields<br />&lt;?php<br />/* Script name: validateForm<br />* Description: Displays and validates a form that<br />* collects a name and address.<br />*/<br />include(“info.inc”); #6<br />#################################<br />## First display of empty form ##<br />#################################<br />if(!isset($_POST[‘Submit’])) #10<br />{<br />include(“addressForm.inc”);<br />}<br />########################################################<br />## Check information when form is submitted. Build ##<br />## arrays of blank and incorrectly formatted fields. ##<br />## If any errors are found, display error messages ##<br />## and redisplay form. If no errors found, display ##<br />## the submitted information. ##<br />########################################################<br />else #21<br />{<br />foreach($_POST as $field=&gt;$value) #23<br />{<br />if(empty($_POST[$field])) #25<br />{<br />if($field != “midName”)<br />{<br />$blanks[$field] = “blank”; #29<br />}<br />}<br />(continued)<br />215 Chapter 10: The Basics of Web Applications<br />Listing 10-4 (continued)<br />else #33<br />{<br />$value = trim($value);<br />if($field != “zipcode”)<br />{<br />if(!ereg(“^[A-Za-z0-9’ .-]{1,65}$”,$value))<br />{<br />$formats[$field] = “bad”;<br />}<br />}<br />elseif($field == “zipcode”)<br />{<br />if(!ereg(“^[0-9]{5}(\-[0-9]{4})?”,$value))<br />{<br />$formats[$field] = “bad”;<br />}<br />}<br />}<br />} #51<br />### if any fields were not okay, display error ###<br />### message and redisplay form ###<br />if (@sizeof($blanks) &gt; 0 or @sizeof($formats) &gt; 0) #54<br />{<br />if (@sizeof($blanks) &gt; 0)<br />{<br />echo “&lt;b&gt;You didn’t fill in one or more<br />required fields. You must enter:&lt;/b&gt;&lt;br&gt;”;<br />foreach($blanks as $field =&gt; $value)<br />{<br />echo “&amp;nbsp;&amp;nbsp;&amp;nbsp;{$labels[$field]}&lt;br&gt;”;<br />}<br />}<br />if (@sizeof($formats) &gt; 0)<br />{<br />echo “&lt;b&gt;One or more fields have information that<br />appears to be incorrect. Correct the<br />format for:&lt;/b&gt;&lt;br&gt;”;<br />foreach($formats as $field =&gt; $value)<br />{<br />echo “&amp;nbsp;&amp;nbsp;&amp;nbsp;{$labels[$field]}&lt;br&gt;”;<br />}<br />}<br />echo “&lt;hr&gt;”;<br />include(“addressForm.inc”);<br />}<br />else #78<br />{<br />216 Part IV: Common PHP Applications<br />### If no errors in the form, display the ###<br />### name and address submitted by user ###<br />echo “&lt;html&gt;&lt;head&gt;&lt;title&gt;Name and Address<br />&lt;/title&gt;&lt;/head&gt;&lt;body&gt;\n”;<br />foreach($_POST as $field=&gt;$value)<br />{<br />if($field != “Submit”)<br />{<br />echo “{$labels[$field]} $value&lt;br&gt;\n”;<br />}<br />}<br />echo “&lt;/body&gt;&lt;/html&gt;”;<br />}<br />}<br />?&gt;<br />I have added line numbers at the end of some of the lines in Listing 10-4 to<br />point out some important points in the script, as described in the following<br />list:<br /> Line 6: This statement includes a file called info.inc that creates<br />an array called labels with information used later in the script. The<br />included file is shown in Listing 10-5. (See Chapter 8 for more on including<br />files in scripts.)<br /> Line 10: This if statement checks for the existence of Submit in the<br />$_POST array. The submit button in the form is given the name Submit.<br />Therefore, if the form has been submitted, Submit will be in $_POST. The<br />condition is negative, so if Submit does not exist, the block is executed.<br />The block just includes a file called addressForm.inc that displays the<br />form. The include file is shown in Listing 10-6. This block is executed the<br />first time the script is called and displays a blank form.<br /> Line 21: This line starts the else block in which Submit does exist in<br />$_POST. This section executes when the user submits a form and validates<br />the data.<br /> Line 23: This line starts a loop through each element in $_POST. This<br />foreach block checks each field in the form.<br /> Line 25: This if statement checks whether each field is empty. If the<br />field is not blank, the script goes to line 33, which begins a block that<br />checks the format of the field.<br /> Line 29: This statement adds an element to the array $blanks for each<br />field that is blank. However, notice that this line does not execute if<br />the field name is midName. That is because Middle Name is not a required<br />field, so it can be blank.<br />217 Chapter 10: The Basics of Web Applications<br /> Line 33: This is an else statement. If a field is not blank, this else statement<br />checks whether the format is acceptable. It checks all the fields,<br />except zip code, to look for unacceptable characters. Acceptable characters<br />are letters, numbers, an apostrophe, a space, a dot, and a hyphen.<br />The zip code field is checked separately for its exact format. If any fields<br />have unacceptable characters or the zip code doesn’t have the correct<br />format, an element for the field is added to the $formats array.<br /> Line 51: This is the end of the section that checks the form fields. At this<br />point, the script has created two arrays, $blanks and $formats, that<br />contain entries for any errors that were found. If no errors were found,<br />the arrays were not created.<br /> Line 54: This if statement checks to see if any errors were found by<br />checking to see if the arrays $blanks and $formats were created. If<br />either array is found, the error message is displayed, and the form is<br />redisplayed, retaining the information that the user typed so it can be<br />corrected.<br /> Line 78: This else statement executes if no errors were found in the<br />form information. The else block displays all the information that the<br />user submitted in the form.<br />Notice that the script in Listing 10-4 is quite generic. That is, it processes information<br />from any form, with the exception of the section that checks the format<br />of the data in the fields. The section between lines 33 and 50 is customized<br />for the specific form being validated. However, the other sections remain the<br />same for most forms.<br />Listing 10-5 shows the file that is included, which creates the array used to<br />display the form and the error messages.<br />Listing 10-5: An Include File That Creates the Array<br />&lt;?php<br />/* Script name: info.inc<br />* Description: creates an array of labels for use in a<br />* form.<br />*/<br />$labels = array( “firstName”=&gt;”First Name:”,<br />“midName”=&gt;”Middle Name:”,<br />“lastName”=&gt;”Last Name:”,<br />“street”=&gt;”Street Address:”,<br />“city”=&gt;”City:”,<br />“state”=&gt;”State:”,<br />“zipcode”=&gt;”Zipcode:”);<br />?&gt;<br />218 Part IV: Common PHP Applications<br />Listing 10-6 shows the script that displays the form. This is based on the<br />script shown in Listing 10-1 that displays the form shown in Figure 10-2.<br />Listing 10-6: An Include File That Displays the Form<br />&lt;?php<br />/* Script name: addressForm.inc<br />* Description: Script displays a form.<br />*/<br />echo “&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Customer Address&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;”;<br />echo “&lt;p align=’center’&gt;<br />&lt;form action=’validateForm.php’ method=’POST’&gt;<br />&lt;table width=’95%’ border=’0’ cellspacing=’0’<br />cellpadding=’2’&gt;\n”;<br />foreach($labels as $field=&gt;$value)<br />{<br />if(isset($_POST[$field])) #13<br />{<br />$value = $_POST[$field];<br />}<br />else<br />{<br />$value = “”;<br />}<br />echo “&lt;tr&gt;&lt;td align=’right’&gt;{$labels[$field]}&lt;/br&gt;&lt;/td&gt;<br />&lt;td&gt;&lt;input type=’text’ name=’$field’ size=’65’<br />maxlength=’65’<br />value=’$value’&gt; &lt;/td&gt; &lt;/tr&gt;”;<br />}<br />echo “ &lt;/table&gt;<br />&lt;div align=’center’&gt;<br />&lt;p&gt;&lt;input type=’Submit’ name=’Submit’<br />value=’Submit Address’&gt;&lt;/p&gt;&lt;/div&gt;<br />&lt;/form&gt;”;<br />?&gt;<br />&lt;/body&gt;&lt;/html&gt;<br />Notice that an if-else block begins on line 13. The block sets the values<br />that are displayed in the form fields. The first time the form is displayed, the<br />$_POST array does not exist, because the form has not been submitted yet.<br />Therefore, the if statement on line 13 checks whether the $_POST element<br />for the field exists. If it does not exist, $value is set to blank. If the $_POST<br />entry does exist, $value is set to the information that the user typed in. The<br />variable $value is then used when the form is displayed.<br />219 Chapter 10: The Basics of Web Applications<br />Notice that the line that creates the submit button includes a name attribute,<br />in this case, name=’Submit’, as follows:<br />&lt;p&gt;&lt;input type=’Submit’ name=’Submit’<br />value=’Submit Address’&gt;&lt;/p&gt;&lt;/div&gt;<br />This causes the submit value to be included in the $_POST array. You can<br />include two submit buttons in your form, with the same name but different<br />values, and perform different actions based on which submit button the user<br />clicked. That is, you can use an if statement such as if($_POST[‘Submit’]<br />== “Submit Address”).<br />The Web page in Figure 10-4 results when users accidentally type their first<br />names into the middle name field and also type nonsense for their zip codes.<br />Notice that two error messages appear, indicating that the First Name field is<br />blank and that the zip code field contains incorrect information.<br />Cleaning information<br />If you check the format of the data carefully, you can often prevent the bad<br />guys from typing malicious characters into your form fields. If you can limit the<br />format of the input you accept, such as checking for a format for a zip code<br />or a telephone number, or limit the input characters to letters and numbers,<br />you can protect yourself fairly well. However, sometimes you need to accept<br />anything the user enters. Your users might need to type in mathematical symbols<br />or HTML code. For example, you might be writing a script for a bulletin<br />board and want users to be able to enter anything into their messages.<br />When user input can’t be restricted much, bad guys are able to enter malicious<br />code into your form fields. For example, they could enter an actual script by<br />using script tags. Depending on what you do with the information from the<br />form, the malicious script can run on your system or be downloaded to run<br />on the system of a visitor to your Web site.<br />PHP provides two functions that can clean the data, rendering it harmless:<br /> strip_tags: This function removes all tags from the text, although you<br />can tell it to allow specific tags.<br /> htmlspecialchars: This function changes some special characters with<br />meaning to HTML into an HTML format that allows them to be displayed<br />without any special meaning. The changes are as follows:<br />• &lt; becomes &amp;lt;<br />• &gt; becomes &amp;gt;<br />• &amp; becomes &amp;amp;<br />220 Part IV: Common PHP Applications<br />It’s safest to remove all tags from the user input. To remove all tags, use the<br />following type of statement:<br />$last_name = strip_tags($last_name);<br />PHP looks for an opening &lt; and removes it and everything else, until it finds a<br />closing &gt; or reaches the end of the string. You can tell PHP that specific tags<br />are okay by using a statement like the following:<br />$last_name = strip_tags($last_name,”&lt;b&gt;&lt;i&gt;”);<br />This statement tells PHP to remove all tags from the string in $last_name<br />except &lt;b&gt; and &lt;i&gt;.<br />You may need to allow users to enter &lt; or &gt; characters. For example, if users<br />are entering text that will be displayed in a Web page and they need to display<br />&lt; or &gt;, such as in a mathematical formula or to display HTML code, you don’t<br />want to remove the tags. You can change the tags to HTML entities, which<br />HTML will display on a Web page as symbols and will not interpret as tags.<br />You can change the tags with the following type of statement:<br />$message = htmlspecialchars($message);<br />The following example shows the difference between the two functions.<br />Suppose $message contains the following text, typed into your form by a user:<br />Use the &lt;?php ?&gt; tags to enclose PHP statements.<br />Figure 10-4:<br />The result of<br />processing<br />a form<br />with both<br />missing and<br />incorrect<br />information.<br />221 Chapter 10: The Basics of Web Applications<br />You can use the following statements to strip the tags from $message and<br />then echo the updated value:<br />$message = strip_tags($message);<br />echo $message;<br />The output of the echo statement is as follows:<br />Use the tags to enclose PHP statements.<br />However, you can use the following statements instead:<br />$message = htmlspecialchars($message);<br />echo $message;<br />In this case, the output is different:<br />Use the &amp;lt;?php ?&amp;gt; tags to enclose PHP statements.<br />This output displays in the browser as follows:<br />Use the &lt;?php ?&gt; tags to enclose PHP statements.<br />This source is displayed correctly, but because the browser does not interpret<br />it as a tag, the browser doesn’t try to process the text as a PHP section. It just<br />displays the source.<br />Another function useful for cleaning input is the trim function. Users often<br />accidentally add spaces to the beginning or ending of a form field. These extra<br />spaces sometimes cause problems, such as when you compare the input to a<br />pattern. Use a statement like the following to remove these spaces:<br />$last_name = trim($last_name);<br />222 Part IV: Common PHP Applications<br />Chapter 11<br />Other Web Applications<br />In This Chapter<br /> Passing information from page to page<br /> Using cookies<br /> Using hidden fields in HTML forms<br /> Using PHP session functions<br /> Adding JavaScript to PHP scripts<br />The simplest Web applications collect information from users in HTML forms<br />and then utilize the information by displaying it, storing it, or using it in<br />conditional statements. (Some simple applications are shown in Chapter 10.)<br />However, Web applications can be much more complex than this. For example,<br />a shopping cart must collect different types of information; display this information;<br />keep track of what users have ordered; calculate prices, taxes, and<br />shipping; charge credit cards; and perform other tasks. Such complex applications<br />consist of several scripts that share information. And applications<br />may also accept complete files from users rather than just information in a<br />form.<br />This chapter discusses the basics of these complex Web applications.<br />Overcoming Statelessness<br />HTML pages are stateless. That is, HTML pages are independent from one<br />another. When a user clicks a link, the Web server sends a new page to the<br />user’s browser, but the browser doesn’t know anything about the previous<br />page. As far as the browser knows, this could be the first Web page ever in<br />the history of the world. For static Web pages, where the user simply views a<br />document, statelessness works fine. However, many dynamic Web applications<br />need information to pass from page to page. For example, you may want to<br />save a user’s name and then display the name on another page.<br />The next few sections discuss methods of passing information from page<br />to page.<br />Navigating Web Sites<br />with Multiple Pages<br />Most Web sites consist of more than one Web page. A static multipage Web<br />site provides a navigation system, consisting of links (which sometimes look<br />like buttons) that users click to move around in the Web site and to find the<br />desired page. A dynamic Web page can use links to move from one page to<br />another, but uses additional methods as well. The following methods are<br />used in PHP scripts to move users from one page to another on a Web site:<br /> Echoing links: Links send users to a new page when the user clicks<br />the link.<br /> Using forms: Forms move users from one page to another when the user<br />clicks the submit button.<br /> Relocating users: PHP provides the header function that takes the user<br />to a new page without needing an action from the user.<br />These methods are described in more detail in the following sections.<br />Echoing links<br />Using PHP, you can echo HTML links, which the user can then click to see various<br />pages in your Web site. This is no different than echoing any other HTML<br />code. Just send the HTML for the links, as in the following:<br />echo “&lt;a href=’newpage.php’&gt;New Page&lt;/a&gt;”;<br />Using forms<br />You can also use an HTML form to display another page, as described in<br />Chapter 10. The form tag specifies a script that processes the form information.<br />When the submit button is clicked, the specified script receives the data<br />from the form and displays a new Web page.<br />The form does not have to collect information in order to display a new page.<br />You can use an empty form on a Web page to provide a button that a user can<br />click to move to another page. For example, you may want to provide a button<br />labeled Cancel or Next for the user to click, even when you don’t want to collect<br />any information from the user. To do so, just use the HTML form tags and<br />include only an input statement for a submit button. The button then appears<br />by itself on the Web page, and the script specified in the form tag displays<br />when the user clicks the submit button.<br />224 Part IV: Common PHP Applications<br />Relocating users<br />PHP also provides a method to move a user from one page to another in your<br />Web site without requiring the user to click a link or a button. You can send a<br />message to the Web server that tells it to send a new page by using the PHP<br />header statement. The format of the header function that sends the user to<br />a new page is as follows:<br />header(“Location: URL”);<br />225 Chapter 11: Other Web Applications<br />Statements that must come before output<br />Some PHP statements can only be used before<br />sending any output to the browser. Header<br />statements, setcookie statements, and<br />session functions, all described in this chapter,<br />must all come before any output is sent. If<br />you use one of these statements after sending<br />output, you may see the following message:<br />Warning: Cannot modify header<br />information &#8211; headers<br />already sent by (output<br />started at /test.php:2) in<br />/test.php on line 3<br />The message provides the name of the file and<br />indicates which line sent the previous output. Or<br />you may not see a message at all; the new page<br />may just not appear. (Whether you see an error<br />message depends on what error message level<br />is set in PHP; see Chapter 4 for details.) The following<br />statements fail because the header message<br />is not the first output (an HTML section<br />comes before the header statement):<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;testing<br />header&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;?php<br />header(“Location:<br />http://janetscompany.com”);<br />?&gt;<br />&lt;/body&gt;&lt;/html&gt;<br />As you can see, three lines of HTML code<br />are sent before the header statement. The<br />following statements work, although they don’t<br />make much sense, because the HTML lines are<br />after the header statement — that is, after the<br />user has already been taken to another page:<br />&lt;?php<br />header(“Location:<br />http://janetscompany.com”);<br />?&gt;<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;testing<br />header&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />The following statements fail:<br />&lt;?php<br />header(“Location:<br />http://company.com”);<br />?&gt;<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;testing<br />header&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;/body&gt;&lt;/html&gt;<br />The reason these statements fail is not easy to<br />see, but if you look closely, you will notice a<br />single blank space before the opening PHP tag.<br />This blank space is output to the browser,<br />although the resulting Web page looks empty.<br />Therefore, the header statement fails because<br />there is output before it. This is a common mistake<br />and difficult to spot.<br />The header statement sends the message, Location: URL, to the Web server.<br />In response, the file located at URL is sent to the user’s browser. Either of the<br />following statements are valid header statements:<br />header(“Location: newpage.php”);<br />header(“Location: http://company.com/catalog/catalog.php”);<br />The header function has a major limitation. The header statement can only<br />be used before any other output is sent. You can’t echo output — such as<br />some HTML code — to the Web page and then send a message requesting a<br />new page in the middle of the script. The header statement is not the only<br />PHP statement that has this restriction. See the nearby sidebar for a discussion<br />of the header statement and other statements like it that must come<br />before output.<br />In spite of its limitations, the header statement is useful. It’s the only way to<br />move users to a new page without requiring an action from the user. Therefore,<br />it’s really the only statement that can be used in conditional statements to<br />display alternate pages to different users. The following example shows how<br />to display alternate pages based on the type of user account:<br />&lt;?php<br />if ($typeAcct == “admin”)<br />{<br />header(“Location: AdminPage.php”);<br />}<br />else<br />{<br />header(“Location: SiteHomePage.php”);<br />}<br />?&gt;<br />These statements run a script that displays an admin page for users with an<br />admin account, but displays a general page for other users. You can have as<br />many PHP statements as you want before the header function, as long as<br />they don’t send output. You can’t have any HTML sections before the header,<br />because HTML is always sent to the browser.<br />Moving Information from Page to Page<br />No matter how the user gets from one page to the next, you may need information<br />from the first page to be available on the next page. With PHP, you can<br />move information from page to page by using any of the following methods:<br />226 Part IV: Common PHP Applications<br /> Adding information to the URL: You can add specific information to the<br />end of the URL of the new page. This method is most appropriate when<br />you need to pass only a small amount of information.<br /> Storing information via cookies: You can store cookies — small amounts<br />of information containing variable=value pairs — on the user’s computer.<br />After the cookie is stored, you can retrieve it from any Web page.<br />However, users can refuse to accept cookies, so this method doesn’t<br />work in all environments.<br /> Passing information using HTML forms: You can pass information that<br />is in a form. When the user clicks the submit button, the information in<br />the form is sent to the next script. This method is useful when you need<br />to collect information from users.<br /> Using PHP session functions: Beginning with PHP 4, PHP functions are<br />available that set up a user session and store session information on the<br />server; this information can be accessed from any Web page. This method<br />is useful for sessions in which you expect users to view many pages.<br />The next few sections discuss these options in greater detail.<br />Adding information to the URL<br />A simple way to move any information from one page to the next is to add the<br />information to the URL you’re linking to. To do so, you put the information in<br />the following format:<br />variable=value<br />In this case, the variable is a variable name, but you do not use a dollar sign<br />($) in it. The value is the value to be stored in the variable. You can add the<br />variable=value pairs anywhere you use a URL. You signal the start of the<br />information with a question mark (?). The following statements are all valid<br />ways of passing information in the URL:<br /> &lt;a href=”nextpage.php?age=14”&gt;go to next page&lt;/a&gt;<br /> header(“Location: nextpage.php?age=14”);<br /> &lt;form action=”nextpage.php?age=14” method=”POST”&gt;<br />These examples all send the variable $age with the value 14 assigned to it.<br />The variable/value pair is sent to nextpage.php by adding the pair to the<br />end of the URL.<br />227 Chapter 11: Other Web Applications<br />You can add several variable=value pairs, separating each pair with an<br />ampersand (&amp;) as follows:<br />&lt;form action=”nextpage.php?state=CA&amp;city=Mall” method=”POST”&gt;<br />Any information passed into a URL is available in the built-in array $_GET. In<br />the preceding example, the script nextpage.php could use the following<br />statements to display the information passed to it:<br />echo “{$_GET[‘city’]}, {$_GET[‘state’]};<br />The output is as follows:<br />Mall, CA<br />The information is also available in the built-in array $_REQUEST. You can use<br />the following statements to get the same result:<br />echo “{$_REQUEST[‘city’]}, {$_REQUEST[‘state’]};<br />Passing information in the URL is easy, especially for small amounts of information.<br />However, this method has some disadvantages, including some<br />important security issues. Here are some reasons you may not want to pass<br />information in the URL:<br /> The whole world can see it. The URL is shown in the address line of the<br />browser, which means that the information you attach to the URL is also<br />shown. If the information needs to be secure, you don’t want it shown so<br />publicly. For example, if you’re moving a password from one page to the<br />next, you probably don’t want to pass it in the URL.<br /> A user can send information in the URL, just as easily as you can. For<br />example, suppose that after a user logs into your restricted Web site, you<br />add auth=yes to the URL. On each Web page, you check to see if $_GET<br />[‘auth’] = yes. If so, you let the user see the Web page. However, any<br />user can type http://www.yoursite.com/page.php?auth=yes into<br />his browser and be allowed to enter without logging in.<br /> The user can bookmark the URL. You may not want your users to save<br />the information you add to the URL.<br /> The length of the URL is limited. The limit differs for various browsers<br />and browser versions, but a limit always exists. Therefore, if you’re passing<br />a lot of information, the URL may not have room for it.<br />228 Part IV: Common PHP Applications<br />Passing information via cookies<br />You can store information as cookies, which are small amounts of information<br />containing variable=value pairs, similar to the pairs you can add to a URL.<br />The user’s browser stores cookies on the user’s computer. Your scripts can<br />then use the cookie information.<br />At first glance, cookies seem to solve the problem of moving data from page<br />to page. Just stash a cookie on the user’s computer and get it whenever you<br />need it. In fact, the cookie can be stored so that it remains there after the user<br />leaves your site and will still be available when the user enters your Web site<br />a month later. Problem solved? Well, not exactly. Cookies are not under your<br />control. They are under the user’s control. The user can at any time delete the<br />cookie. In fact, users can set their browsers to refuse to allow any cookies,<br />and many users do refuse cookies or routinely delete them. Many users are<br />not comfortable with the idea of a stranger storing things on their computers,<br />especially files that remain after they leave the stranger’s Web site. This is an<br />understandable attitude. However, it definitely limits the usefulness of cookies.<br />If your application depends on cookies and the user has cookies shut off,<br />your application won’t work for that user.<br />Cookies were originally designed for storing small amounts of information for<br />short periods of time. Unless you specifically set the cookie to last a longer<br />period of time, the cookie will disappear when the user leaves your Web site.<br />Although cookies are useful in some situations, consider the following points<br />before deciding to use them:<br /> Users may set their browsers to refuse cookies. Unless you know for<br />sure that all your users will have cookies turned on or you can request<br />that they turn on cookies and expect them to follow your request, cookies<br />are a problem. If your application depends on cookies, it won’t run if<br />cookies are turned off.<br /> PHP has features that work better than cookies. Beginning with<br />PHP 4, PHP sessions can store information that is available for the<br />entire session — in other words, as long as the user stays at your Web<br />site. Session functions store information on the server, where it is not<br />at the mercy of the user. Sessions, however, don’t work for long-term<br />storage of information.<br /> You can store data in a database. If you have access to a database where<br />you can store and retrieve data, this is often a better solution than cookies.<br />Users can’t delete the data in your database unexpectedly.<br />229 Chapter 11: Other Web Applications<br />Storing and retrieving information in cookies<br />You store cookies by using the setcookie function. The general format is as<br />follows:<br />setcookie(“variable”,”value”);<br />The variable is the variable name, but you do not include the dollar sign<br />($).This statement stores the information only until the user leaves your Web<br />site. For example, the following statement stores the pair state=CA in the<br />cookie file on the user’s computer:<br />setcookie(“state”,”CA”);<br />When the user moves to the next page, the cookie information is available in<br />the built-in array called $_COOKIE. The next Web page can display the information<br />from the cookie by using the following statement.<br />echo “Your home state is “.$_COOKIE[‘state’];<br />The output from this statement is as follows:<br />Your home state is CA<br />The cookie is not available in the script where it is set. The user must go to<br />another page or redisplay the current page before the cookie information is<br />available.<br />Setting expiration dates<br />If you want the information stored in a cookie to remain in a file on the user’s<br />computer after the user leaves your Web site, set your cookie with an expiration<br />time, as follows:<br />setcookie(“variable”,”value”,expiretime);<br />The expiretime value sets the time when the cookie expires. The value for<br />expiretime is usually set by using either the time or mktime function as<br />follows:<br /> time: This function returns the current time in a format the computer can<br />understand. You use the time function plus a number of seconds to set<br />the expiration time of the cookie, as shown in the following statements:<br />setcookie(“state”,”CA”,time()+3600); #expires in one hour<br />setcookie(“Name”,$Name,time()+(3*86400)) #expires 3 days<br />230 Part IV: Common PHP Applications<br /> mktime: This function returns a date and time in a format that the computer<br />can understand. You must provide the desired date and time in<br />the following order: hour, minute, second, month, day, and year. If any<br />value is not included, the current value is used. You use the mktime<br />function to set the expiration time of the cookie, as shown in the following<br />statements:<br />setcookie(“state”,”CA”,mktime(3,0,0,4,1,2003)); #expires<br />at 3:00 AM on April 1, 2003<br />setcookie(“state”,”CA”,mktime(13,0,0,,,)); /#expires at<br />1:00 PM<br />today<br />You can remove a cookie by setting its value to nothing. Either of the following<br />statements removes the cookie:<br />setcookie(“name”);<br />setcookie(“name”,””);<br />The setcookie function has a major limitation, however. The setcookie<br />function can only be used before any other output is sent. You cannot set a<br />cookie in the middle of a script, after you have echoed some output to the<br />Web page. For more information, see the see the sidebar in this chapter<br />called “Statements that must come before output.”<br />Passing information using HTML forms<br />The most common way to pass information from one page to another is by<br />using HTML forms. An HTML form is displayed with a submit button. When<br />the user clicks the submit button, the information in the form fields is passed<br />to the script included in the form tag. The general format is as follows:<br />&lt;form action=”processform.php” method=”POST”&gt;<br />tags for one or more fields<br />&lt;input type=”submit” value=”string”&gt;<br />&lt;/form&gt;<br />The most common use of a form is to collect information from users and pass<br />it to the next page (discussed in detail in Chapter 10). However, forms can also<br />be used to pass other types of information.<br />Hidden fields are fields in forms that send information to the next page without<br />appearing in the form on the Web page. Hidden fields can be included in<br />the form along with other types of fields, or can be the only type of field in the<br />form. When the user clicks the submit button, the information in the hidden<br />231 Chapter 11: Other Web Applications<br />field is sent to the next page. For example, the following statements pass the<br />user’s account type to the next page when the user clicks a button that says<br />Next Page:<br />&lt;?php<br />$acct = “admin”;<br />echo “&lt;form action=’nextpage.php’ method=’POST’&gt;<br />&lt;input type=’hidden’ name=’acct’ value=’$acct’&gt;<br />&lt;input type=’submit’ value=’Next Page’&gt;<br />&lt;/form&gt;\n”;<br />?&gt;<br />The Web page shows a submit button that says Next Page, but it doesn’t ask<br />the user for any information. When the user clicks the button, nextpage.php<br />runs, and the account type is available in $_POST[‘acct’]. In this way, you<br />can pass information that you need to use other places in the Web site from<br />page to page. In this example, you could use this code as part of a script that<br />displays some products. When the user clicks the Next Page button, the<br />account type is sent to the new page for use in that script.<br />Using PHP sessions<br />A session is the time that a user spends at your Web site. Users may view many<br />Web pages between the time they enter your site and leave it. Often you want<br />information to be available for a complete session. Beginning with version 4.0,<br />PHP provides a way to do this.<br />Understanding how PHP sessions work<br />PHP allows you to set up a session and store session variables. After you<br />create a session, the session variables are available for your use on any other<br />Web page. To make session information available, PHP does the following:<br />1. PHP assigns a session ID number.<br />The number is a really long nonsense number that is unique for the user<br />and that no one could possibly guess. The session ID is stored in a PHP<br />system variable named PHPSESSID.<br />2. PHP stores the variables that you want saved for the session in a file on<br />the server.<br />The file is named with the session ID number. It’s stored in a directory<br />specified by session.save_path in the php.ini file. The session directory<br />must exist before session files can be saved in it.<br />3. PHP passes the session ID number to every page.<br />232 Part IV: Common PHP Applications<br />If the user has cookies turned on, PHP passes the session ID by using<br />cookies. If the user has cookies turned off, PHP behavior depends on<br />whether trans-sid is turned on in php.ini. (You find out more about<br />trans-id in the section “Using sessions without cookies,” later in this<br />chapter.)<br />4. PHP gets the variables from the session file for each new session page.<br />Whenever a user opens a new page that is part of the session, PHP<br />gets the variables from the file by using the session ID number that<br />was passed from the previous page. The variables are available in the<br />$_SESSION array.<br />For PHP 4.1.2 or earlier, trans-sid is not available unless it was enabled by<br />using the option &#8211;enable-trans-sid when PHP was compiled.<br />Opening and closing sessions<br />You should open a session at the beginning of each Web page. Open the session<br />with the session_start function, as follows:<br />session_start();<br />The function first checks for an existing session ID number. If it finds one, it<br />sets up the session variables. If it doesn’t find one, it starts a new session by<br />creating a new session ID number.<br />Because sessions use cookies, if the user has them turned on, session_start<br />is subject to the same limitation as cookies. That is, to avoid an error, the<br />session_start function must be called before any output is sent. For complete<br />details, see the sidebar in this chapter called “Statements that must<br />come before output.”<br />You can tell PHP that every page on your site should automatically start with a<br />session_start statement. You can do this with a setting in the configuration<br />file php.ini. If you’re the PHP administrator, you can edit this file; otherwise,<br />ask the administrator to edit it. Look for the variable session.auto_start<br />and set its value to 1. You may have to restart the Web server before this<br />setting takes effect. With auto_start turned on, you do not need to add a<br />session_start at the beginning of each page.<br />You may want to restrict your site to users with a valid user ID and password.<br />For restricted sessions that users log into, you often want users to log out<br />when they’re finished. To close a session, use the following statement wherever<br />to want to close the session:<br />session_destroy();<br />233 Chapter 11: Other Web Applications<br />This statement gets rid of all the session variable information that is stored in<br />the session file. PHP no longer passes the session ID number to the next page.<br />However, the statement does not affect the variables set on the current page;<br />they still hold the same values. If you want to remove the variables from the<br />current page, as well as prevent them from being passed to the next page,<br />unset them by using this statement:<br />unset($variablename1,$variablename2,&#8230;);<br />Using PHP session variables<br />To save a variable in a session so that it’s available on later Web pages, store<br />the value in the $_SESSION array, as follows:<br />$_SESSION[‘varname’] = “John Smith”;<br />When you open a session on any subsequent Web page, the values stored in<br />the $_SESSION array are available.<br />If you want to stop storing any variable at any time, you can unset the variable<br />by using the following statement:<br />unset($_SESSION[‘varname’];<br />The following two scripts show how to use sessions to pass information from<br />one page to the next. The script in Listing 11-1 shows the first page of a session.<br />Listing 11-2 shows the second page in a session.<br />Listing 11-1: Starting a Session<br />&lt;?php<br />/* Script name: sessionTest1.php<br />* Description: Starts a session. Saves a session variable.<br />*/<br />session_start();<br />$_SESSION[‘session_var’] = “testing”;<br />?&gt;<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Testing Sessions page 1&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;p&gt;This is a test of the sessions feature.<br />&lt;form action=”sessionTest2.php” method=”POST”&gt;<br />&lt;input type=”text” name=”form_var” value=”testing”&gt;<br />&lt;input type=”submit” value=”Go to Next Page”&gt;<br />&lt;/form&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />234 Part IV: Common PHP Applications<br />In this script, a session is started and one session variable is stored called<br />session_var. A form is also displayed with one text field where the user can<br />enter some text. When the submit button from this form, labeled “Go to Next<br />Page” is clicked, the sessionTest2.php script runs.<br />Listing 11-2: The Second Page of a Session<br />&lt;?php<br />/* Script name: sessionTest2.php<br />* Description: Gets a variable from an existing session.<br />*/<br />session_start();<br />?&gt;<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Testing Sessions page 2&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;?php<br />$session_var = $_SESSION[‘session_var’];<br />$form_var = $_POST[‘form_var’];<br />echo “session_var = $session_var&lt;br&gt;\n”;<br />echo “form_var = $form_var&lt;br&gt;\n”;<br />?&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;<br />This script displays the variables that were passed from the previous script<br />(sessionTest1.php).<br />If users pointed their browsers at sessionTest1.php and clicked the submit<br />button that says Go to Next Page, they’d see the following output from<br />sessionTest2.php:<br />session_var = testing<br />form_var = testing<br />As you can see, both the session variable, session_var and the form variable,<br />form_var are available in the built-in arrays to be echoed from this script.<br />Using sessions without cookies<br />Many users turn off cookies in their browsers. PHP checks the user’s browser<br />to see whether cookies are allowed and behaves accordingly. If the user’s<br />browser allows cookies, PHP does the following:<br /> It sets the variable $PHPSESSID equal to the session ID number.<br /> It uses cookies to move $PHPSESSID from one page to the next.<br />235 Chapter 11: Other Web Applications<br />If the user’s browser is set to refuse cookies, PHP behaves differently:<br /> It sets a constant called SID. The constant contains a variable=value<br />pair that looks like PHPSESSID=longstringofnumbers. (The long string<br />of numbers is the session ID.)<br /> It may or may not move the session ID number from one page to the<br />next, depending on whether trans-sid is turned on. If trans-sid is<br />turned on, PHP passes the session ID number; if it is not turned on, PHP<br />does not pass the session ID number.<br />trans-sid is turned off by default. You can turn it on by editing your php.<br />ini file. Search for the line that begins with session.use_trans_id = . If<br />the setting is 0, trans_id is off; if the setting is 1, trans_id is on. To turn the<br />setting on when it is off, change 0 to 1. You may have to restart your Web<br />server before the new setting takes effect.<br />Turning trans-sid on has advantages and disadvantages:<br /> Advantages: Sessions work seamlessly even when users turn cookies<br />off. You can script sessions easier, without being concerned about the<br />user’s browser setting for cookies.<br /> Disadvantages: The session ID number is often passed in the URL. In<br />some situations, for security reasons, the session ID number should not<br />be shown in the browser address. Also, when the session ID number is<br />in the URL, it can be bookmarked by the user. Then, if the user returns to<br />your site by using the bookmark with the session ID number in it, the new<br />session ID number from the current visit can get confused with the old<br />session ID number from the previous visit and possibly cause problems.<br />Sessions with trans-sid turned on<br />When trans-sid is turned on and the user has cookies turned off, PHP automatically<br />sends the session ID number in the URL or as a hidden form field.<br />If the user moves to the next page by using a link, a header function, or a<br />form with the GET method, the session ID number is added to the URL. If the<br />user moves to the next page by using a form with the POST method, the session<br />ID number is passed in a hidden field. PHP recognizes PHPSESSID as the<br />session ID number and handles the session without any special programming<br />on your part.<br />The session ID number is added only to the URLs for pages on your Web site.<br />If the URL of the next page includes a server name, PHP assumes that the URL<br />is on another Web site and does not add the session ID number. For example,<br />suppose your link statement is as follows:<br />&lt;a href=”newpage.php”&gt;<br />PHP will add the session ID number. However, suppose your statement is as<br />follows:<br />236 Part IV: Common PHP Applications<br />&lt;a href=”HTTP://www.janetscompany.com/newpage.php”&gt;<br />PHP will not add the session ID number.<br />Sessions without trans-sid turned on<br />When trans-sid is not turned on and the user has cookies turned off, PHP<br />does not send the session ID number to the next page. Instead, you must send<br />the session ID number yourself.<br />Fortunately, PHP provides a constant that you can use to send the session ID<br />yourself. This constant is named SID and contains a variable=value pair<br />that you can add to the URL, as follows:<br />&lt;a href=”nextpage.php?&lt;?php echo SID?&gt; &gt; next page &lt;/a&gt;<br />This link statement includes the question mark (?) at the end of the filename<br />and the constant SID added to the URL. SID contains the session ID number.<br />The output from echo SID looks something like this:<br />PHPSESSID=877c22163d8df9deb342c7333cfe38a7<br />Therefore, the URL of the next page looks as follows:<br />nextpage.php?PHPSESSID=877c22163d8df9deb342c7333cfe38a7<br />The session ID is added to the end of the URL. For one of several reasons<br />(discussed earlier in this chapter), you may not want the session ID number<br />to appear on the URL shown by the browser. To prevent this, you can send<br />the session ID number in a hidden field in a form by using the POST method.<br />First, get the session ID number, and then send it in a hidden field. The following<br />statements do this:<br />&lt;?php<br />$PHPSESSID = session_id();<br />echo “&lt;form action=’nextpage.php’ method=’POST’&gt;<br />&lt;input type=’hidden’ name=’PHPSESSID’<br />value=’$PHPSESSID’&gt;<br />&lt;input type=’submit’ value=’Next Page’&gt;<br />&lt;/form&gt;”;<br />?&gt;<br />These statements do the following:<br />1. The function session_id, which returns the current session ID number,<br />stores the session ID number in the variable $PHPSESSID.<br />2. $PHPSESSID is sent in a hidden form field.<br />On the new page, PHP automatically finds PHPSESSID without any special<br />programming needed from you.<br />237 Chapter 11: Other Web Applications<br />Creating sessions for members only<br />PHP session functions are ideal for Web sites that are restricted and require<br />users to login with a login name and password. These types of Web sites<br />undoubtedly have many pages, and you don’t want the user to have to login<br />to each page. PHP sessions can keep track of whether the user has logged in<br />and refuse access to users who aren’t logged in. Using PHP sessions, you can<br />do the following:<br />1. Show users a login page.<br />2. If a user logs in successfully, set and store a session variable.<br />3. Whenever a user goes to a new page, check the session variable to see if<br />the user has logged in.<br />4. If the user has logged in, show the page.<br />5. If the user has not logged in, bring up the login page.<br />To check whether a user has logged in, add the following statements to the<br />top of every page:<br />&lt;?php<br />session_start()<br />if ( @$_SESSION[‘login’] != “go” )<br />{<br />header(“Location: loginPage.php”);<br />exit();<br />}<br />?&gt;<br />In these statements, PHP checks a session variable called login — which was<br />set at login — to see whether $_SESSION[‘login’] is equal to “go”. If it is<br />not, it means the user is not logged in, and the user is sent to the login page.<br />If $_SESSION[‘login’] equals “go”, the script proceeds with the rest of the<br />statements on the Web page.<br />Uploading Files<br />You may want users to upload files to your Web site. For example, you may<br />want users to be able to upload resumes to your job-search Web site or pictures<br />to your photo album Web site.<br />238 Part IV: Common PHP Applications<br />Using a form to upload a file<br />You can display a form that allows a user to upload a file by using an HTML<br />form designed for that purpose. The general format of the form is as follows:<br />&lt;form enctype=”multipart/form-data”<br />action=”processfile.php” method=”POST”&gt;<br />&lt;input type=”hidden” name=”MAX_FILE_SIZE” value=”30000”&gt;<br />&lt;input type=”file” name=”user_file”&gt;<br />&lt;input type=”submit” value=”Upload File”&gt;<br />&lt;/form&gt;<br />Notice the following points regarding the form:<br /> The enctype attribute is used in the form tag. You must set this attribute<br />to multipart/form-data when uploading a file to ensure the file arrives<br />correctly.<br /> A hidden field is included that sends a value (in bytes) for MAX_FILE_<br />SIZE. If the user tries to upload a file that is larger than this value, it<br />won’t upload. When sending the value for MAX_FILE_SIZE in your form,<br />you need to consider two size settings in php.ini, as follows<br />• upload_max_filesize: The MAX_FILE_SIZE you send in your<br />upload form can’t be larger than the value of upload_max_<br />filesize. If you are uploading a larger file and need to send a MAX_<br />FILE_SIZE larger than the current value of upload_max_filesize,<br />you need to increase the value of upload_max_filesize by editing<br />the php.ini file. The default value for this setting is 2M.<br />• post_max_size: The total amount of information you send in a<br />POST form can’t be larger than the value of post_max_size. The<br />default value for this setting is 8M. You can increase this value if<br />necessary by editing your php.ini file.<br /> The input field that uploads the file is of type file.<br />The value for MAX_FILE_SIZE must be sent before the file is uploaded if you<br />want the file size limit to apply to the uploading file.<br />When the user submits the form, the file is uploaded to a temporary location.<br />The script that processes the form needs to copy the file to another location<br />because the temporary file is deleted as soon as the script is finished. You<br />can use phpinfo() to see where the temporary files are stored. If you don’t<br />like the location of the temporary directory, you can change it by changing<br />upload_tmp_dir in the php.ini file. If no directory is specified in php.ini,<br />a default temporary directory is used. Because the temporary files are deleted<br />almost immediately, the location of the temporary directory is not likely to<br />be very important.<br />239 Chapter 11: Other Web Applications<br />Accessing information about<br />an uploaded file<br />Along with the file, information about the file is sent with the form. This information<br />is stored in the PHP built-in array called $_FILES. An array of information<br />is available for each file that was uploaded. As with any other form, you<br />can obtain the information from the array by using the name of the field. For<br />example, you can get information about the uploaded file from the following<br />array:<br />$_FILES[‘fieldname’][‘name’]<br />$_FILES[‘fieldname’][‘type’]<br />$_FILES[‘fieldname’][‘tmp_name’]<br />$_FILES[‘fieldname’][‘size’]<br />For example, suppose you use the following field to upload a file:<br />&lt;input type=”file” name=”user_file”&gt;<br />If the user uploads a file named test.txt by using the form, the resulting<br />array that can be used by the processing script looks something like this:<br />$_FILES[user_file][name] = test.txt<br />$_FILES[user_file][type] = text/plain<br />$_FILES[user_file][tmp_name] = D:\WINNT\php92C.tmp<br />$_FILES[user_file][size] = 435<br />In this array, name is the name of the file that was uploaded, type is the type<br />of file, tmp_name is the path/filename of the temporary file, and size is the<br />size of the file. Notice that name contains only the filename, while tmp_name<br />includes the path to the file as well as the filename.<br />If the file is too large to upload, the tmp_name in the array is set to none, and<br />the size is set to 0.<br />By default, PHP stores the temporary uploaded file in your system directory<br />on Windows (Windows for Win98/XP and Winnt for Win2000) or /tmp on Unix/<br />Linux. You can change the location where the temporary files are stored by<br />setting the location in php.ini. Look in your php.ini file for the following<br />line:<br />;upload_tmp_dir =<br />240 Part IV: Common PHP Applications<br />Remove the semicolon at the beginning of the line so that the line becomes<br />active. Add the path to the directory where you want the temporary files to<br />be stored. Your active line looks similar to the following:<br />upload_tmp_dir = d:\tempfiles<br />The directory tempfiles must exist. If it doesn’t, PHP ignores the setting and<br />continues to save the files in the default location.<br />Moving uploaded files to their destination<br />The general format of the statement that moves the file is as follows:<br />move_uploaded_file(path/tempfilename,path/permfilename);<br />The tmp_file element in $_FILES stores the temporary filename and location,<br />so you can use the following statement to move the file to your desired<br />location, in this case, c:\data\new_file.txt:<br />move_uploaded_file($_FILES[‘user_file’][‘tmp_name’],<br />‘c:\data\new_file.txt’);<br />The destination directory (in this case, c:\data) must exist before the file<br />can be moved to it. This statement doesn’t create the destination directory.<br />Security can be an issue when uploading files. Allowing strangers to load files<br />onto your computer is risky; malicious files are possible. So, you probably<br />want to check the files for as many factors as possible after they are uploaded,<br />using conditional statements to check file characteristics, such as checking<br />for the expected file type and for the size. In some cases, for even more security,<br />it may be a good idea to change the name of the file to something else so<br />users don’t know where their files are or what they’re called.<br />Putting it all together<br />A complete example script is shown in Listing 11-3. This script displays a<br />form for the user to upload an image file, saves the uploaded file, and then<br />displays a message after the file has been successfully uploaded. This script<br />expects the uploaded file to be an image file, and tests to make sure that it is<br />an image file, but any type of file can be uploaded. The form displayed by this<br />script is shown in Figure 11-1.<br />241 Chapter 11: Other Web Applications<br />Listing 11-3: A Script That Uploads a File Using a POST Form<br />&lt;?php<br />/* Script name: uploadFile.php<br />* Description: Uploads a file via HTTP using a POST form.<br />*/<br />if(!isset($_POST[‘Upload’])) #5<br />{<br />include(“form_upload.inc”);<br />} # endif<br />else #9<br />{<br />if($_FILES[‘pix’][‘tmp_name’] == “none”) #11<br />{<br />echo “&lt;b&gt;File did not successfully upload. Check the<br />file size. File must be less than 500K.&lt;br&gt;”;<br />include(“form_upload.inc”);<br />exit();<br />}<br />if(!ereg(“image”,$_FILES[‘pix’][‘type’])) #16<br />{<br />echo “&lt;b&gt;File is not a picture. Please try another<br />file.&lt;/b&gt;&lt;br&gt;”;<br />include(“form_upload.inc”);<br />exit();<br />}<br />else #23<br />{<br />$destination = ‘c:\data’.”\\”.$_FILES[‘pix’][‘name’];<br />$temp_file = $_FILES[‘pix’][‘tmp_name’];<br />move_uploaded_file($temp_file,$destination);<br />echo “&lt;p&gt;&lt;b&gt;The file has successfully uploaded:&lt;/b&gt;<br />{$_FILES[‘pix’][‘name’]}<br />({$_FILES[‘pix’][‘size’]})&lt;/p&gt;”;<br />}<br />}<br />?&gt;<br />I have added line numbers at the end of some of the lines in the script. The<br />script is discussed below with reference to these line numbers:<br /> Line 5: This line is an if statement that tests whether the form has been<br />submitted. If not, the form is displayed by including the file containing<br />the form code. The include file is shown in Listing 11-4.<br /> Line 9: This line starts an else block that executes if the form has been<br />submitted. This block includes the rest of the script and processes the<br />submitted form and uploaded file.<br /> Line 11: This line is an if statement that tests whether the file was successfully<br />uploaded. If not, an error message is displayed, and the form is<br />redisplayed.<br />242 Part IV: Common PHP Applications<br /> Line 16: This line is an if statement that tests whether the file is a picture.<br />If not, an error message is displayed, and the form is redisplayed.<br /> Line 23: This line starts an else block that executes if the file has been<br />successfully uploaded. The file is moved to its permanent destination,<br />and a message is displayed that the file has been uploaded.<br />Listing 11-4 shows the include file used to display the upload form.<br />Listing 11-4: An Include File That Displays the File Upload Form<br />&lt;!&#8211; Script Name: form_upload.inc<br />Description: Displays a form to upload a file &#8211;&gt;<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;File Upload&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;ol&gt;&lt;li&gt;Enter the name of the picture you want to upload<br />to our picture archive or use the browse button<br />to navigate to the picture file.&lt;/li&gt;<br />&lt;li&gt;When the path to the picture file shows in the text<br />field, click the Upload Picture button.&lt;/li&gt;<br />&lt;/ol&gt;<br />&lt;div align=”center”&gt;&lt;hr&gt;<br />&lt;form enctype=”multipart/form-data”<br />action=”uploadFile.php” method=”POST”&gt;<br />&lt;input type=”hidden” name=”MAX_FILE_SIZE” value=”500000”&gt;<br />&lt;input type=”file” name=”pix” size=”60”&gt;<br />&lt;p&gt;&lt;input type=”submit” name=”Upload”<br />value=”Upload Picture”&gt;<br />&lt;/form&gt;<br />&lt;/body&gt;&lt;/html&gt;<br />Figure 11-1:<br />A form that<br />allows users<br />to upload an<br />image file.<br />243 Chapter 11: Other Web Applications<br />Notice that the include file doesn’t contain PHP code, just HTML code.<br />The form that allows users to select a file to upload is shown in Figure 11-1.<br />The form has a text field for inputting a filename and a browse button that<br />enables the user to navigate to the file and select it.<br />Using JavaScript with PHP<br />You may want to use JavaScript in your Web page. For example, you may want<br />your Web page to change based on the position of the mouse pointer or a click<br />of the mouse. Or you may want to modify some information on your Web page<br />without redisplaying the entire page. You can’t achieve these effects with PHP<br />because it’s strictly a server-side scripting language. PHP doesn’t know what<br />is happening on the user’s PC; it only knows what’s happening on the Web site<br />server. If you want to make changes to the Web page display without resending<br />the Web page from the server, you need to use a client-side scripting language,<br />like JavaScript.<br />The user can turn off JavaScript so that the browser doesn’t execute the<br />JavaScript statements. It’s not wise for your Web application to depend<br />on JavaScript unless you can ensure that all your users have JavaScript<br />enabled in their browsers.<br />I don’t talk about the JavaScript language in this chapter. I assume that you<br />either know JavaScript or can learn the actual JavaScript code elsewhere. In<br />this chapter, I talk about how to use JavaScript in a PHP script. (For more<br />information on JavaScript, check out JavaScript For Dummies, 3rd Edition, by<br />Emily A. Vander Veer.)<br />Adding JavaScript code to a PHP script<br />JavaScript code, just like HTML code, is understood and executed by the<br />browser on the user’s computer (the client side). Therefore, you add<br />JavaScript to a PHP script in the same way that you add HTML to a PHP<br />script. In fact, JavaScript is basically part of the HTML code for the Web<br />page. You add JavaScript to the HTML by using an HTML tag, as follows:<br />&lt;script language=”JavaScript”&gt;<br />JavaScript code<br />&lt;/script&gt;<br />244 Part IV: Common PHP Applications<br />JavaScript code is used in your PHP script in the same way HTML code is<br />used — namely, it is echoed. For example, the following statements send<br />some JavaScript to the browser:<br />&lt;?php<br />echo “&lt;script language=\”JavaScript\”&gt;<br />&lt;!&#8211;<br />document.write(‘This page last updated: ‘<br />+ document.lastModified + ‘&lt;br&gt;’)<br />// &#8211;&gt;<br />&lt;/script&gt;”;<br />?&gt;<br />When a browser receives these JavaScript statements, it executes them and<br />produces the following output:<br />This page last updated: 03/24/2003 12:01:47<br />This is the date and time that the file containing the script was last modified.<br />You can use JavaScript statements alone, outside of PHP tags, just as you can<br />HTML code. You could add the preceding statements to a PHP file without<br />using PHP tags or an echo statement. If the JavaScript statement is not added<br />in a PHP section, it is sent to the browser exactly as is, without being passed<br />to the PHP script, just as HTML code is when it’s outside of a PHP section.<br />Using PHP variables with JavaScript<br />You can use PHP variables with JavaScript the same way you do with HTML.<br />You can add the variable to the JavaScript code. For example, the JavaScript<br />example in the preceding section can include a PHP variable, as follows:<br />&lt;?php<br />$string = “This page last updated: “;<br />echo “&lt;script language=\”JavaScript\”&gt;<br />&lt;!&#8211;<br />document.write(‘$string’<br />+ document.lastModified + ‘&lt;br&gt;’)<br />// &#8211;&gt;<br />&lt;/script&gt;”;<br />?&gt;<br />245 Chapter 11: Other Web Applications<br />The JavaScript language itself uses variables. You can set a JavaScript variable<br />to the value of a PHP variable to use in your JavaScript code. For example, the<br />JavaScript could be sent as follows:<br />&lt;?php<br />$string = “This page last updated: “;<br />echo “&lt;script language=\”JavaScript\”&gt;<br />&lt;!&#8211;<br />var message = \”$string\”;<br />document.write( message<br />+ document.lastModified + ‘&lt;br&gt;’)<br />// &#8211;&gt;<br />&lt;/script&gt;”;<br />?&gt;<br />Because JavaScript code is not executed until it reaches the browser on the<br />client side, passing values from JavaScript variables to PHP variables can’t<br />take place in the current page. The JavaScript value must be passed on to the<br />next PHP script before PHP can receive it. JavaScript can pass the values on<br />so that PHP can use them by adding them to the URL, by storing them in a<br />cookie that PHP can read, or by sending them as a form element.<br />246 Part IV: Common PHP Applications<br />Chapter 12<br />Storing Data with PHP<br />In This Chapter<br />Writing and reading flat files<br /> Exchanging data between PHP and other programs<br /> Understanding database support in PHP<br /> Using PHP to interact with a database<br /> Handling database-connection errors<br />Many applications require the long-term storage of information. In PHP<br />scripts, you can make information available within sessions — periods<br />of time that users spend at your Web site — by using methods such as PHP<br />session functions and by submitting forms. However, eventually you need to<br />store information for use tomorrow or next week. You can store it in a cookie<br />that you set to last after the session is ended (as discussed in Chapter 11), but<br />the information is vulnerable. It’s not under your control. The user can delete<br />or change the information at any time or can refuse to accept the cookie. To be<br />available and stable, the information needs to be stored somewhere secure,<br />where no one can access or tamper with it. The information needs to be stored<br />on the server.<br />Information can be stored on the server in flat files or in databases. Flat files<br />are text files stored in the computer file system. Humans can read flat files by<br />using the operating system commands that display files, such as cat in Linux<br />and Unix. You can access and edit these files by using any text file editor, such<br />as Notepad or vi. The information in the flat file is stored as strings, and the<br />PHP script that retrieves the data needs to know how the data is stored. For<br />example, to retrieve a customer name from a file, the PHP script needs to<br />know that the customer name is stored in the first 20 characters of every line.<br />Using a database for data storage requires you to install and learn to use database<br />software, such as MySQL or Oracle. The data is stored in files created by<br />the database software and can only be accessed by the database software.<br />Databases can store very complex information that you can retrieve easily.<br />You don’t need to know how the data is stored, just how to interact with the<br />database software. For example, to retrieve a customer name, the PHP script<br />needs to know only how to tell the database software that it wants the customer<br />name, using a standard communication language called SQL, The database<br />software handles the storage and delivers the data, without the script<br />needing to know exactly where or how the customer name is stored.<br />Flat files have some advantages over databases:<br /> Available and versatile: You can create and save data in any operating<br />system’s file system. You don’t need to install any extra software.<br />Additionally, text data stored in flat files can be read by a variety of<br />software programs, such as word processors or spreadsheets.<br /> Easy to use: You don’t need to do any extra preparation, such as install<br />database software, design a database, create a database, and so on. Just<br />create the file and store the data with statements in your PHP script.<br /> Smaller: Flat files store data by using less disk space than databases.<br />In summary, a flat file is quick and easy and takes less space than a database.<br />It is ideal for storing small amounts of information quickly, such as a simple<br />list or small piece of information. Flat files are particularly useful for making<br />information available to other software, such as an editing program or a<br />spreadsheet. Flat files can be looked at by anyone with access to the computer<br />directory where they are stored, so they are useful when information<br />needs to be made available to other people.<br />Databases have some advantages as well:<br /> Security: A database provides a security layer of its own, in addition to<br />the security provided by the operating system. A database protects the<br />data from outside intrusion better than a flat file.<br /> Accessibility of data: You can store data in a database by using a very<br />complex data structure, specifying data types and relationships among<br />the data. The organization of the data makes it easy to search the data<br />and retrieve what you need.<br /> Ability to handle multiple users: When many users store or access data<br />in a single file, such as a file containing names and addresses, a database<br />ensures that users take their turn with the file to avoid overwriting each<br />other’s data.<br />In summary, databases require more start-up effort and use more space than<br />a flat file, but are much more suitable for handling complex information. The<br />database handles the internal organization of the data, making data retrieval<br />248 Part IV: Common PHP Applications<br />much simpler. A database provides more security, making it more suitable for<br />sensitive, private information. Databases can more easily and efficiently handle<br />high traffic when many users may try to access the data almost simultaneously.<br />In PHP 5, SQLite, an extension for data storage that combines the main advantages<br />of flat files and databases, is included by default. SQLite stores the data<br />in a flat file, so you don’t need to install database software, but you store data<br />using SQL, the standard database communication language. SQLite is a quick<br />option for storing and retrieving small amounts of data in a flat file using SQL.<br />SQLite is not a good option for really huge, complicated databases.<br />Using Flat Files<br />Flat files are simple to use, simpler than databases. You don’t need any other<br />software, such as database software. You just use PHP statements to read<br />from or write to the file.<br />Using a flat file requires three steps:<br />1. Open the file.<br />2. Write data into the file or retrieve data from the file.<br />3. Close the file.<br />These steps are discussed in detail in the following sections.<br />Accessing files<br />The first step, before you can write information into or read information from<br />a file, is to open the file. The following is the general format for the statement<br />that opens a file:<br />$fh = fopen(“filename”,”mode”)<br />The variable, $fh, referred to as a file handle, is used in the statements that<br />write data to or read data from the open file so that PHP knows which file<br />to write into or read from. $fh contains the information that identifies the<br />location of the open file.<br />You use a mode when you open the file to let PHP know what you intend to<br />do with the file. Table 12-1 shows the modes you can use.<br />249 Chapter 12: Storing Data with PHP<br />Table 12-1 Modes for Opening a File<br />Mode What it does What happens when the file doesn’t exist<br />r Read only. If the file does not exist, a warning message<br />is displayed.<br />r+ Reading and writing. If the file does not exist, a warning message<br />is displayed.<br />w Write only. If the file does not exist, PHP attempts to<br />create it. If the file exists, PHP overwrites it.<br />w+ Reading and writing. If the file does not exist, PHP attempts to<br />create it. If the file exists, PHP overwrites it.<br />a Append data at the end If the file does not exist, PHP attempts to<br />of the file. create it.<br />a+ Reading and appending. If the file does not exist, PHP attempts to<br />create it.<br />The filename can be a simple filename (filename.txt), a path to the file<br />(c:/data/filename.txt), or a URL (http://yoursite.com/filename.txt).<br />Opening files in read mode<br />You can open the file file1.txt to read the information in the file with the<br />following statement:<br />$fh = fopen(“file1.txt”,”r”);<br />Based on this statement, PHP looks for file1.txt in the current directory,<br />which is the directory where your PHP script is located. If the file can’t be<br />found, a warning message, similar to the following, may or may not be displayed,<br />depending on the error level set, as described in Chapter 4:<br />Warning: fopen(file1.txt): failed to open stream: No such<br />file or directory in d:\test2.php on line 15<br />Remember, a warning condition does not stop the script. The script continues<br />to run, but the file doesn’t open, so any later statements that read or<br />write to the file aren’t executed.<br />You probably want the script to stop if the file can’t be opened. You need to<br />do this yourself with a die statement, as follows:<br />250 Part IV: Common PHP Applications<br />$fh = fopen(“file1.txt”,”r”)<br />or die(“Can’t open file”);<br />As explained in Chapter 8, the die statement stops the script and displays the<br />specified message.<br />Opening files in write mode<br />You can open a file in a specified directory to store information by using the<br />following type of statement:<br />$fh = fopen(“c:/testdir/file1.txt”,”w”);<br />If the file does not exist, it is created in the indicated directory. However, if<br />the directory doesn’t exist, the directory is not created, and a warning is displayed.<br />(You must create the directory first, before you try to write a file into<br />the directory.)<br />You can check whether a directory exists before you try to write a file into it<br />by using the following statements:<br />If(is_dir(“c:/tester”))<br />{<br />$fh = fopen(“c:/testdir/file1.txt”,”w”);<br />}<br />With these statements, the fopen statement is executed only if the directory<br />exists and is a directory.<br />Opening files on another Web site<br />You can also open a file on another Web site by using a statement such as the<br />following:<br />$fh = fopen(“http://janet.valade.com/index.html”,”r”);<br />You can use a URL only with a read mode, not with a write mode.<br />Closing a file<br />To close a file after you have finished reading or writing it, use the following<br />statement:<br />fclose($fh);<br />In this statement, $fh is the file handle variable you created when you<br />opened the file.<br />251 Chapter 12: Storing Data with PHP<br />Writing to a file<br />After you open the file, you can write into it by using the fwrite statement,<br />which has the following general format:<br />fwrite($fh,datatosave);<br />In this statement, $fh is the file handle that you created when you opened<br />the file, containing the pointer to the open file, and datatosave is the information<br />to be stored in the file. The information can be a string or a variable.<br />For example, you can use the following statements:<br />$today = date(“Y-m-d”);<br />$fh = fopen(“file2.txt”,”a”);<br />fwrite($fh,$today);<br />fclose($fh);<br />These statements store the current date in a file called file2.txt. Notice<br />that the file is opened in append mode. If the file doesn’t exist, it is created,<br />and the date is written as the first line. If the file exists, the data is added to<br />the end of the file. In this way, you create a log file, which stores a list of the<br />dates on which the script is run. The fwrite statement stores exactly what<br />you send, so the second time these statements are run, file2.txt contains<br />the following:<br />2003-04-222003-04-22<br />You probably want the two dates to be stored on separate lines. To do so, use<br />the following fwrite statement rather than the previous one:<br />fwrite($fh,$today”\n”);<br />With the new line character added, file2.txt contains the following:<br />2003-04-22<br />2003-04-22<br />Be sure to open the file with the a mode if you want to add information to a<br />file. If you use a write mode, the file is overwritten each time it’s opened.<br />Reading from a file<br />You can read from a file by using the fgets statement, which has the following<br />general format:<br />$line = fgets($fh)<br />252 Part IV: Common PHP Applications<br />In this statement, $fh holds the pointer to the open file. This statement reads<br />a string until it encounters the end of the line or the end of the file, whichever<br />comes first, and stores the string in $line. To read an entire file, you keep<br />reading lines until you get to the end of the file. PHP recognizes the end of the<br />file, and provides a function feof to tell you when you reach the end of the<br />file. The following statements read and display all the lines in the file:<br />while(!feof($fh))<br />{<br />$line = fgets($fh);<br />echo “$line;<br />}<br />In the first line, feof($fh) returns TRUE when the end of the file is reached.<br />The exclamation point negates the condition being tested, so that the while<br />statement continues to run as long as the end of the file is not reached. When<br />the end of the file is reached, while stops.<br />If you use these statements to read the log file created in the preceding section,<br />you get the following output:<br />2003-04-22<br />2003-04-22<br />As you can see, the new line character is included when the line is read. In<br />some cases, you don’t want the end of line included. If so, you need to remove<br />it by using the following statements:<br />while(!feof($fh))<br />{<br />$line = rtrim(fgets($fh));<br />echo “$line;<br />}<br />The rtrim function removes any trailing blank spaces and the new line character.<br />The output from these statements is as follows:<br />2003-04-222003-04-22<br />Reading files piece by piece<br />Sometimes you want to read strings of a certain size from a file. You can tell<br />fgets to read a certain number of characters by using the following format:<br />$line = fgets($fh,n)<br />This statement tells PHP to read a string that is n-1 characters long until it<br />reaches the end of the line or the end of the file.<br />253 Chapter 12: Storing Data with PHP<br />For example, you can use the following statements:<br />while(!feof($fh))<br />{<br />$char4 = fgets($fh,5);<br />echo “$char4\n”;<br />}<br />These statements read each four-character string until the end of the file. The<br />output is as follows:<br />2003<br />-04-<br />22<br />2003<br />-04-<br />22<br />Notice that there is a new line at the end of each line of the file.<br />Reading a file into an array<br />It’s often handy to have the entire file in an array. You can do that with the<br />following statements:<br />$fh = fopen(“file2.txt”,”r”);<br />while(!feof($fh))<br />{<br />$content[] = fgets($fh);<br />}<br />fclose($fh);<br />The result is the array $content with each line of the file as an element of<br />the array. The array keys are numbers.<br />PHP provides a shortcut function for opening a file and reading the entire<br />contents into an array, one line in each element of the array. The following<br />statement produces the same results as the preceding five lines:<br />$content = file(“file2.txt”);<br />The statement opens file2.txt, puts each line into an element of the array<br />$content, and then closes the file.<br />The file function can slow down your script if the file you’re opening is really<br />large. How large depends on the amount of available computer memory. If<br />your script seems slow, try reading the file with fgets rather than file and<br />see if that speeds up the script.<br />254 Part IV: Common PHP Applications<br />You can direct the file function to automatically open files in your include<br />directory (described in Chapter <img src='http://s0.wp.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> by using the following statement:<br />$content = file(“file2.txt”,1);<br />The 1 tells PHP to look for file2.txt in the include directory rather than in<br />the current directory.<br />Reading a file into a string<br />Sometimes it’s useful to put the entire contents of a file into one long string.<br />For example, you may want to send the file contents in an e-mail message.<br />PHP provides a function for reading a file into a string, as follows:<br />$content = file_get_contents(“file2.txt”,1);<br />The file_get_contents function works the same as the file function,<br />except that it puts the entire contents of the file into a string rather than an<br />array. After this statement, you can echo $content as follows:<br />echo $content;<br />The output is the following:<br />2003-04-22<br />2003-04-22<br />The output appears on separate lines because the end of line characters are<br />read and stored as part of the string. Thus, when you echo the string, you<br />also echo the end of line characters, which start a new line.<br />The file_get_contents function was introduced in version 4.3.0. It isn’t<br />available in older versions of PHP.<br />Exchanging data with other programs<br />Flat files are particularly useful for providing information to other programs<br />or reading information into PHP from other programs. Almost all software has<br />the ability to read information from flat files or write information into flat files.<br />For example, by default your word processor saves your documents in its own<br />format, which only the word processor can understand. However, you can<br />choose to save the document in text format instead. The text document is a<br />flat file containing text that can be read by other software. Your word processor<br />can also read text files, even ones that were written by other software.<br />255 Chapter 12: Storing Data with PHP<br />When your PHP script saves information into a text file, the information can be<br />read by any software that has the capability of reading text files. For example,<br />any text file can be read by most word processing software. However, some<br />software requires a specific format in the text file. For example, an address<br />book software application may read data from a flat file but require the information<br />to be in specified locations — for example, the first 20 characters in a<br />line are read as the name, and the second 20 characters are read as the street<br />address, and so on. You need to know what format the software requires in<br />a flat file. Then write the flat file in the correct format in your PHP script by<br />using fwrite statements, as discussed in the section “Writing to a file,” earlier<br />in this chapter.<br />A CSV (comma-separated values) file — also called a comma-delimited file —<br />is a common format used to transfer information between software programs.<br />A CSV file is used to transfer information that can be structured as a table,<br />organized as rows and columns. For example, spreadsheet programs organize<br />data as rows and columns and can read and write CSV files. A CSV file is also<br />often used to transfer data between different database software, such as<br />between MySQL and MS Access. Many other software programs can read and<br />write data in CSV files.<br />A CSV file is organized with each row of the table on a separate line in the file,<br />and the columns in the row are separated by commas. For example, an address<br />book can be organized as a CSV file as follows:<br />John Smith,1234 Oak St.,Big City,OR,99999<br />Mary Jones,5678 Pine St.,Bigger City,ME,11111<br />Luis Rojas,1234 Elm St.,Biggest City,TX,88888<br />Excel can read this file into a table with five columns. The comma signals the<br />end of one column and the start of the next. Outlook can also read this file<br />into its address book. And many other programs can read this file.<br />The following PHP statements create the CSV file:<br />$address[] = “John Smith,1234 Oak St.,Big City,OR,99999”;<br />$address[] = “Mary Jones,5678 Pine St.,Bigger City,ME,11111”;<br />$address[] = “Luis Rojas,1234 Elm St.,Biggest City,TX,88888”;<br />$fh = fopen(“addressbook.txt”,”a”);<br />for ($i=0;$i&lt;3;$i++)<br />{<br />fwrite($fh,$address[$i].”\n”);<br />}<br />fclose($fh);<br />PHP can read the CSV file by using either the file or the fgets function, as<br />described in the section “Reading a file into an array,” earlier in this chapter.<br />However, PHP provides a function called fgetcsv that is designed specifically<br />to read CSV files. When you use this function to read a line in a CSV file, the<br />line is stored in an array, with each column entry in an element of the array.<br />256 Part IV: Common PHP Applications<br />For example, you can use the function to read the first line of the address<br />book CSV file, as follows:<br />$address = fgetcsv($fh,1000);<br />In this statement, $fh is the file handle, and 1000 is the number of characters<br />to read. To read an entire line, use a number of characters that is longer than<br />the longest line. The result of this statement is an array as follows:<br />$address[0] = John Smith<br />$address[1] = 1234 Oak St.<br />$address[2] = Big City<br />$address[3] = OR<br />$address[4] = 99999<br />The CSV file works well for transferring data in many cases. However, if a<br />comma is part of the data, commas can’t be used to separate the columns.<br />For example, suppose one of data lines is as follows:<br />Smith Company, Inc.,1234 Fir St.,Big City,OR,99999<br />The comma in the company name would divide the data into two columns —<br />Smith Company in the first and Inc. in the second — making six columns<br />instead of five. When the data contains commas, you can use a different character<br />to separate the columns. For example, tabs are commonly used to separate<br />columns. This file is called a TSV file or a tab-delimited file. You can write<br />a tab-delimited file by storing “\t” in the output file rather than a comma.<br />You can read a file containing tabs by specifying the column separator in the<br />statement, as follows:<br />$address = fgetcsv($fh,1000,”\t”);<br />You can use any character to separate columns.<br />The script in Listing 12-1 contains a function that converts any CSV file into a<br />tab-delimited file.<br />Listing 12-1: A Script That Converts a CSV File into a Tab-Delimited File<br />&lt;?php<br />/* Script name: Convert<br />* Description: Reads in a CSV file and outputs a<br />* tab-delimited file. The CSV file must have a .<br />* CSV extension.<br />*/<br />$myfile = “testing”; #7<br />function convert($filename) #8<br />(continued)<br />257 Chapter 12: Storing Data with PHP<br />Listing 12-1 (continued)<br />{<br />if(@$fh_in = fopen(“{$filename}.csv”,”r”)) #10<br />{<br />$fh_out = fopen(“{$filename}.tsv”,”a”); #12<br />while(!feof($fh_in)) #13<br />{<br />$line = fgetcsv($fh_in,1024); #15<br />if($line[0] == “”) #16<br />{<br />fwrite($fh_out,”\n”);<br />}<br />else { #20<br />fwrite($fh_out,implode($line,”\t”).”\n”); #21<br />}<br />}<br />fclose($fh_in);<br />fclose($fh_out);<br />}<br />else { #27<br />echo “File doesn’t exist\n”;<br />return FALSE;<br />}<br />echo “Conversion completed!\n”;<br />return TRUE; #32<br />}<br />convert($myfile); #34<br />?&gt;<br />Listing 12-1 has numbers at the end of some lines. The following points refer<br />to the line numbers in the listing:<br /> Line 7: This line defines the filename as testing.<br /> Line 8: This line defines a function named convert() with one parameter,<br />$filename.<br /> Line 10: This line opens a file that has the filename that was passed to<br />the function with a .csv extension. The file is opened in read mode. If the<br />file is opened successfully, the conversion statements in the if block<br />are executed. If the file is not found, the else block beginning on line 27<br />is executed.<br /> Line 12: This line opens a file that has the filename that was passed to<br />the function with a .tsv extension. The file is opened in append mode.<br />The file is in the current directory in this script. If the file is in another<br />directory where you think there is any possibility the file might not open<br />in write mode, use an if statement here to test where the file opened<br />and perform some action if it did not.<br /> Line 13: This line starts a while loop that continues to the end of the file.<br />258 Part IV: Common PHP Applications<br /> Line 15: This statement reads one line from the input file into the array<br />$line. Each column entry is stored in an element of the array.<br /> Line 16: This statement tests whether the line from the input file has any<br />text on it. If the line doesn’t have any text, a new line character is stored<br />in the output file. Thus, any empty lines in the input file are stored in the<br />output file.<br /> Line 20: If the line from the input file is not empty, it’s converted to a<br />tab-delimited format and written into the output file.<br /> Line 21: This statement converts the line and writes it to the output file<br />in one statement. The implode function converts the array $line into a<br />string, with the elements separated by a tab.<br /> Line 27: This else block executes when the input file can’t be found. An<br />error message is echoed, and the function returns FALSE.<br /> Line 32: The function has completed successfully, so it returns TRUE.<br /> Line 34: This line calls the function, passing a filename to the function in<br />the variable $myfile.<br />Working with Databases<br />If you need to store complex information, keep the information very secure,<br />or handle many users accessing the data at once, a database is much better<br />than a flat file for long-term storage. Also, if you already know and use database<br />software, it’s almost as simple to use a database as a flat file.<br />Understanding database software<br />A database is an electronic file cabinet that stores information in an organized<br />manner so that you can find it when you need it. A database can be small,<br />with a simple structure, such as a database containing the names, addresses,<br />and phone numbers of all your friends. Or a database can be huge with an<br />extremely complex structure, such as the database Amazon must have to<br />hold all its information.<br />Technically, the term database refers to the file or group of files that holds the<br />actual data. The data is accessed by using a set of programs called a Database<br />Management System (DBMS). Almost all DBMSs these days are Relational<br />Database Management Systems (RDBMSs), in which data is organized and<br />stored in a set of related tables.<br />259 Chapter 12: Storing Data with PHP<br />One of PHP’s strengths is its support for many different DBMSs. PHP supports<br />over 20 databases. It supports the following popular RDBMSs, as well as others<br />that are less well known:<br /> IBM DB2<br /> Informix<br /> Ingres<br /> Microsoft SQL Server (MS SQL)<br /> mSQL<br /> MySQL<br /> Oracle<br /> PostgreSQL<br /> Sybase<br />In addition, PHP offers support for ODBC, which stands for the Open Database<br />Connectivity standard, a standard database access method developed by<br />Microsoft. Many DBMSs understand ODBC, particularly Windows DBMSs. Using<br />ODBC support in PHP, you can access some databases that are not specifically<br />supported, such as DB2 and Access. Also, you can use ODBC to access several<br />different databases with the same code. To use ODBC to communicate with a<br />database, the database needs to have an ODBC driver installed. See the documentation<br />for your database to find out how to install ODBC support for your<br />database.<br />If you currently have a database set up and know how to use it, you can<br />undoubtedly store and retrieve data from your existing database by using<br />PHP scripts. If you don’t have an existing database, you need to choose one.<br />Selecting and installing a database is independent of PHP. You install the database,<br />make sure it’s working, and learn to use it. After your database is working,<br />you can store and retrieve data with PHP scripts.<br />Choosing a RDBMS depends on your needs. The RDBMS that is right for you<br />may not be the best option for someone else. You need to research your<br />options and choose the one with the characteristics that suit your situation.<br />You may need to consider some of the following issues:<br /> Cost: The cost of the RDBMS software ranges from free to quite pricey.<br />MySQL, mSQL, and PostgreSQL are open source software, meaning they’re<br />free. Other RDBMSs, such as Sybase, MS SQL Server, and Oracle, are commercial<br />software with prices that range from moderate to astronomical.<br />260 Part IV: Common PHP Applications<br /> Features: The features provided by an RDBMS vary. For example, mSQL<br />has a small set of features, but this may be enough for some purposes.<br />On the other hand, Oracle can do everything but drive your car. In general,<br />the more features the RDBMS has, the more computer resources it<br />requires and the higher its cost. Therefore, you may not want to install<br />software with a huge feature set that you don’t need.<br /> Resources: Some RDBMSs require more resources, such as disk space and<br />memory, than others. For example, mSQL is very small and lightweight,<br />requiring very little overhead. MySQL was also developed to be small.<br />On the other hand, Oracle, depending on which products and tools you<br />install, can require many resources.<br /> Support: Commercial software and open source software provide support<br />differently:<br />• Commercial: Commercial software provides a method for customers<br />to get technical support from the company that sold them the software.<br />Sometimes customers have to pay for the technical support<br />or wait in phone queues, but the company answers their questions<br />and assists with troubleshooting.<br />• Open source: Open source software does not provide a direct phone<br />line to a software company. Open source software is supported by<br />the community of users. E-mail lists and forums offer access to many<br />people who are using the software and who are willing to answer<br />questions and assist each other with problems. Sometimes asking<br />a question on an e-mail list gets you an answer faster than phoning<br />a technical-support phone number at a software company.<br />After you choose which database you’re going to use, you need to install<br />the database software and figure out how to use it. You need to know how to<br />design and create a database that you can then access from a PHP script. In<br />general, a database has two parts: a structure to hold the data and the data<br />itself.<br />The structure consists of the database itself and tables within the database<br />that hold the data. You need to design the database structure before you can<br />store data in it. RDBMS tables are organized like other tables you’re used to —<br />in rows and columns. For example, suppose you want to provide an online catalog,<br />containing all your products, so users can see what you have and place<br />orders. You create a database called Catalog. In the Catalog database, you<br />create a table called Product that contains all your products. The Product table<br />has a different product in each row. The columns of the row contain information<br />about each product. For example, if the product is a shirt, each row of the<br />table contains information about a different shirt you sell. The columns contain<br />information about the shirt, such as the name of the shirt (T-shirt, dress<br />shirt, polo shirt, and so on), the description, the size, the color, and so on.<br />261 Chapter 12: Storing Data with PHP<br />When you create a table, you give each column a name, called the field name.<br />For your Product table containing shirts, you name the columns as follows:<br /> Type<br /> Description<br /> Size<br /> Color<br /> Price<br />Your Catalog database can have other tables in it, such as a table containing<br />shipping costs and a table containing sales tax information.<br />In addition to the database design and creation, you need to understand the<br />security used by your RDBMS. One of the advantages of databases is the security<br />provided for the data, but the security makes storing and retrieving data<br />more complicated. The RDBMS doesn’t allow just anyone to get data from your<br />database. You need to have a valid account name and password before you<br />can use the database. If you’re using a database on a Web hosting company,<br />those folks need to provide you with a valid account and password. If you’re<br />installing the database software yourself, you need to understand how to<br />administer the accounts.<br />After you have designed and created the database structure, you can add<br />data to the tables and retrieve stored data from the tables. PHP makes data<br />storage and retrieval quite simple.<br />Understanding database support in PHP<br />PHP communicates with databases by using functions designed specifically<br />to interact with databases. PHP includes a set of functions for each database<br />it supports. For example, to communicate with MySQL 4.0 or earlier, you use<br />functions such as mysql_connect() and mysql_query() and to communicate<br />with MySQL 4.1 or later, you use functions such as mysqli_connect()<br />and mysqli_query(). To communicate with Sybase, you use functions such<br />as sybase_connect() and sybase_query().<br />By default, PHP includes support for ODBC. For database support other than<br />ODBC, you must add support for the database you plan to use. If you’re using<br />a Web hosting company, those folks must provide the database support. If<br />you’re running your Web site on your own computer, you need to add database<br />support to PHP. You can include database support by using the methods<br />described in the following sections.<br />262 Part IV: Common PHP Applications<br />Setting up database support in Unix/Linux/Mac<br />Support for a database is an installation option that is included in the configure<br />step during installation. Appendix A includes a section that discusses<br />the installation options. For example, to include support for mSQL, use the<br />following command line options in the configuration step during installation:<br />./configure &#8211;with-msql=/usr/msql<br />Table 12-2 shows many of the database installation options available. If the<br />database is installed in the default location, you don’t need to include the<br />DIR parameter. You can use the option without the parameter, as follows:<br />./configure &#8211;with-msql<br />Table 12-2 PHP Database Installation Options<br />Database Installation Option Default DIR<br />IBM DB2 with-ibm-db2=DIR /home/db2inst1/sqllib<br />Informix with_informix=DIR No default<br />Ingres II with-ingres=DIR /II/ingres<br />mSQL with-msql=DIR /usr/local/Hughes<br />MySQL 4.0 or earlier with-mysql=DIR /usr/local/mysql<br />MySQL 4.1 or greater with-mysqli=DIR No default. DIR must be the<br />path to the file mysql_<br />config that is installed with<br />MySQL 4.1 or greater.<br />Oracle 7 and newer with-oci8 Default DIR is contained in<br />versions the environmental variable,<br />ORACLE_HOME<br />Earlier versions of with-oracle=DIR Default DIR is contained in<br />Oracle the environmental variable,<br />ORACLE_HOME<br />PostgreSQL with-pgsql=DIR /usr/local/pgsql<br />Sybase with-sybase=DIR /home/sybase<br />Sybase-CT with-sybase-ct=DIR /home/sybase<br />263 Chapter 12: Storing Data with PHP<br />After you compile PHP using the appropriate installation option, you can check<br />that database support was correctly activated with the phpinfo function. The<br />database support and settings appears in the output from phpinfo.<br />Setting up database support in Windows<br />Enabling PHP support for a database in Windows requires two steps:<br />1. Copy the dll (Dynamic Link Library) file for the database into the<br />main directory.<br />2. Activate the database support.<br />After performing the steps, as described below, you can use the phpinfo<br />function to check that the database support has been activated. Information<br />and settings for the database are displayed in the output from phpinfo.<br />Copying the dll<br />The dlls are included in the zip file you download from the PHP Web site.<br />Downloading and installing PHP manually from the zip file is described in<br />Appendix A. After installing manually, a directory called ext is in the directory<br />where PHP is installed. The path will be something like c:\php\ext, and<br />the dlls for the databases are in this directory.<br />Copy the dll you need into the main directory where PHP is installed, such as<br />c:\php. For example, to add support for PostgreSQL to PHP on a Windows<br />2000 system, copy c:\php\ext\php_pgsql.dll into the main directory<br />where PHP is installed. To do this, CD into c;\php\ext and type:<br />copy php_pgsql.dll<br />If you used the installer to install PHP, the database dlls were not downloaded.<br />You need to download the zip file, as described for installing PHP manually.<br />Then unzip the file, find the appropriate dll, and copy it into the system<br />directory.<br />Activating the database support<br />Database support is activated in the php.ini file. Look for a list of statements<br />that have the following form:<br />;extension=php_pgsql.dll<br />;extension=php_msql.dll<br />This list includes a statement for every database that is supported. Notice<br />the semicolon at the beginning of each line. The semicolon is the comment<br />character in the php.ini file, so the statements in the list are comments and<br />are not active. Find the statement for the database support you need and<br />then remove the semicolon from the statement for the database support you<br />want to activate, as in the following example<br />264 Part IV: Common PHP Applications<br />extension=php_pgsql.dll<br />This statement activates PostgreSQL support. After you save the php.ini file,<br />you may need to restart your Web server before the database support goes<br />into effect.<br />If you activate the database support line in php.ini, but haven’t copied the<br />dll into the main directory, you will see an error message similar to the following<br />when you try to run a PHP script:<br />Unknown(): Unable to load dynamic library ‘php_pgsql.dll’.<br />The specified module could not be found.<br />If you perform both steps correctly (copy the dll into the main directory and<br />activate the correct line in php.ini), but the database software isn’t<br />installed, you will get an error message similar to the following when you try<br />to run a PHP script:<br />The dynamic link library msql.dll could not be found in the<br />specified path<br />For MS SQL users only: You need to install the MS SQL Server Client Tools,<br />as well as the database server. Microsoft provides these tools on the CD.<br />For MySQL users only: Be sure you use the correct dll: php_mysql.dll for<br />MySQL 4.0 or earlier or php_mysqli.dll for MySQL 4.1 or later.<br />Communicating with your database<br />Most database software understands SQL (Structured Query Language), a<br />computer language you use to communicate with a database. You send an SQL<br />statement, called a query, to the RDBMS that tells it what you want to do. SQL<br />queries can instruct the RDBMS to create a database, create tables in a database,<br />store data, retrieve data, delete data, and perform many other actions.<br />Although most databases understand SQL, there may be differences in the<br />SQL you can use with different databases. For example, mSQL understands a<br />limited set of SQL queries, but Oracle and Sybase each have an extended set<br />of SQL queries they understand, beyond the standard SQL.<br />A complete description of SQL is beyond the scope of this book. If you’re<br />using MySQL as your database, you may want to look at my other book, PHP<br />&amp; MySQL For Dummies (Wiley Publishing, Inc.). A description of the SQL you<br />need to work with databases is contained in this book. Or, for a complete<br />description of SQL and all its capabilities and features, see SQL For Dummies,<br />5th Edition, by Allen Taylor (Wiley Publishing, Inc.).<br />265 Chapter 12: Storing Data with PHP<br />Although I do not discuss SQL in detail, I will describe a couple of simple SQL<br />queries so that I can use some real examples in this book to show you how to<br />use your database. To get data from your database, you can use the following<br />query:<br />SELECT * FROM tablename<br />This query retrieves all the data that is contained in the table. The * is a special<br />character called a wild card that selects all the fields in the table. Suppose<br />you want to retrieve data from the Catalog database discussed in the section<br />“Understanding database software,” earlier in this chapter. This database has<br />a table named Product that contains the information for all the products in<br />the catalog. You can use the following SQL query to retrieve all the data from<br />the Product table:<br />SELECT * FROM Product<br />To add a new record to a table, you can use the following query:<br />INSERT INTO tablename (fieldname1,fieldname2, &#8230;) VALUES<br />(value1,value2, &#8230;)<br />This query creates a new row in the table with the specified values and adds<br />the values provided to the named fields. For example, for the Catalog database<br />discussed previously, you can add a new product with the following query:<br />INSERT INTO Product (Type,Description,Size,Color,Price)<br />VALUES (“T-shirt”,”100% cotton”,”L”,”Black”,20)<br />Notice that there are quotes around the strings, but not around the number.<br />Also, notice that there is a value listed for every field named. The database<br />gives an error message if the number of values is not equal to the number of<br />fields.<br />In the next section, I discuss how to use a PHP script to interact with a<br />database.<br />Using PHP with a database<br />Whichever database you’re using, the steps to interact with a database are<br />similar:<br />1. Connect to the database.<br />2. Send an SQL query that contains instructions for the database software.<br />3. If you retrieved data from the database, process the data.<br />4. Close the connection to the database.<br />266 Part IV: Common PHP Applications<br />These steps are discussed in more detail in the following sections.<br />Connecting to the database<br />The first step in a database interaction is connecting to the database. You use<br />a PHP function to connect to the database. To make the connection, you need<br />to supply the function with four things:<br /> Location: The database does not need to be on the same computer where<br />PHP is installed. Therefore, you need to tell the PHP connect function the<br />name of the computer where the database is located (the hostname).<br />You can supply either a domain name (such as mycompany.com) or an<br />IP address (such as 172.17.204.2). If the database is on the same computer<br />as PHP, you can use localhost for the hostname.<br /> Account name: You must provide a valid account name that can be used<br />to access the database. The database administrator sets this up. If you’re<br />using a Web hosting company, you will be given a valid account name.<br /> Password: You have to have a valid password to access the database.<br />The database administrator sets this up. If you’re using a Web hosting<br />company, you will be given a valid password for your account.<br /> Database name: An RDBMS can create and maintain many databases, so<br />you need to tell it which database you want to use.<br />For security reasons, it’s best to keep your database connection information<br />in a separate file and use it in your PHP script with an include statement.<br />As long as your include files are stored in a secure location, as discussed in<br />Chapter 8, your information is more secure than if it were stored in the PHP<br />script itself. For the following examples, I create an include file called info.<br />inc with the following statements:<br />$host = “localhost”;<br />$account = “admin”;<br />$password = “secret”;<br />$dbname = “Catalog”;<br />Then I can include this file in any PHP script that needs to access the database<br />by using the following statement:<br />include(“info.inc”);<br />The PHP function to connect to the database software is not the same for all<br />RDBMSs. That would be too simple. However, although the functions may<br />differ for different databases, the form is similar. For example, the most popular<br />software for Web site database applications is MySQL. For MySQL 4.0 or<br />earlier you use two statements as follows, to connect to the database,:<br />$connect = mysql_connect($host,$account,$password);<br />$db = mysql_select_db(“Catalog”,$connect);<br />267 Chapter 12: Storing Data with PHP<br />The first statement connects to the database management software and the<br />second statement tells it which database you want to access. For MySQL 4.1<br />or later, the format is slightly different, as follows:<br />$connect = mysqli_connect($host,$account,$password);<br />$db = mysqli_select_db($connect,&#8221;Catalog&#8221;);<br />Notice that the order of the items passed in the function is reversed for the<br />second line. Mysql passes (&#8220;Catalog&#8221;,$connect) and mysqli passes<br />($connect,&#8221;Catalog&#8221;).<br />Several databases,require two separate functions to connect to the database,<br />as shown for MySQL above. For example, mSQL and Sybase use similar statements,<br />as shown in the following statements:<br />$connect = msql_connect($host,$account,$password);<br />$db = msql_select_db(“Catalog”,$connect);<br />$connect = sybase_connect($host,$account,$password);<br />$db = sybaseselect_db(“Catalog”,$connect);<br />For other databases, only one function is needed, as shown in the following<br />statement for postgreSQL:<br />$connect = pg_connect(“host=$host user=$user<br />password=$password dbname=Catalog”);<br />The format for connecting to other database management systems is similar<br />with small variations. Connecting to Oracle using the OCI8 interface differs<br />even more, as follows:<br />$connect = OCILogon($account,$password);<br />The Oracle connection also requires an environment variable ORACLE_SID<br />set to the desired Oracle instance.<br />To determine the correct format to connect to the database that you’re using,<br />see the PHP manual on the PHP Web site (www.php.net) for the appropriate<br />function for your RDBMS.<br />Sending a query to the database<br />After PHP has established a connection to the database, you can perform<br />whatever action you desire, such as get data, change data, or insert new data.<br />The SQL query tells the database what action you want to perform. You<br />send the SQL query to the by using another PHP function for your RDBMS.<br />Again, the format of these statements varies, but they are similar. For example,<br />for MySQL, you can send the query by using the following statements:<br />268 Part IV: Common PHP Applications<br />$sql = “SELECT * FROM Product”;<br />$result = mysql_query($sql,$connect);<br />The first statement stores the SQL query in a variable $sql. The SQL statement<br />gets all the data in the table Product. The mysql_query function sends<br />the query in $sql to the database over the database connection established<br />earlier and stored in $connect. The data is stored in a temporary table l, with<br />rows and columns, and $result (or whatever you chose to call this variable)<br />contains a pointer to the temporary table.<br />For PostgreSQL, the statements are similar, as follows:<br />$sql = “SELECT * FROM Product”;<br />$result = pg_query($connect,$sql);<br />The first statement creates the SQL query and stores it in $sql. The second<br />statement executes the query and returns the data. For Oracle, two PHP functions<br />are needed to execute a query, as follows:<br />$sql = “SELECT * FROM Product”;<br />$query = OCIParse($connect,$sql);<br />$result = OCIExecute($query);<br />The first statement creates the SQL query. Notice that the first statement is<br />the same for all three databases. For Oracle, the second two statements are<br />required to execute the statement and return the results.<br />Any SQL query is sent by using the same functions. The query in these three<br />examples returns data, but queries that don’t return data are sent with the<br />same function, as in the following example:<br />$first_name = “John”;<br />$last_name = “Smith”;<br />$sql = “INSERT INTO Customer (firstName,lastName) VALUES<br />(‘$first_name’,’$last_name’)”;<br />$result = mysql_query($sql);<br />When no data is returned by the query, $result contains TRUE, rather than a<br />pointer to the retrieved data.<br />To determine the correct way to send the query, see the PHP manual on the<br />PHP Web site (www.php.net) for the appropriate functions for your RDBMS.<br />Processing data<br />If you send a query that retrieves data, you undoubtedly intend to use that<br />data in your PHP script. You may want to display a list of check boxes based<br />on data taken from the database, display data in a Web page so users can edit<br />it, use the data from the database as default text in an HTML form, and so on.<br />269 Chapter 12: Storing Data with PHP<br />To process the returned data, you need to get it from the temporary table<br />where it was placed when the SQL query was executed. You use PHP database<br />functions to get the data from the temporary table.<br />The data is stored in the temporary table in rows and columns. You can use<br />PHP functions to retrieve one row from the table and store it in an array, with<br />the field names as the array keys. For MySQL, the statement is as follows:<br />$row = mysql_fetch_array($result);<br />In the previous section, we saved the results and stored the location in a variable<br />named $result. In this statement, we tell PHP which results to fetch by<br />using $result. The mysql_fetch_array returns one row of data from the<br />temporary table specified by $result.<br />After this statement, $row is an array containing all the fields in the temporary<br />table, such as the following:<br />$row[‘firstName’] = John<br />$row[‘lastName’] = Smith<br />To process all the data in the temporary table, you can use a loop to get one<br />row at a time, processing each row until the end of the table is reached. For<br />PostgreSQL, the while loop looks like this:<br />while($row=pg_fetch_asoc($result))<br />{<br />foreach($row as $value)<br />{<br />echo “$value&lt;br&gt;”;<br />}<br />}<br />The while loop executes once for each row in the temporary table. An array<br />called $row is created in each loop, containing the data in that row. The<br />foreach loop travels through the $row array and displays each field name<br />and the data in each field.<br />The following example for PostgreSQL uses a for loop to process the data,<br />giving the same result as the preceding example that uses a while loop:<br />$Nrows = pg_num_rows($result);<br />for($i=0;$i&lt;$Nrows;$i++)<br />{<br />$row = pg_fetch_row($result,$i);<br />foreach($row as $value)<br />{<br />echo “$value&lt;br&gt;”;<br />}<br />}<br />270 Part IV: Common PHP Applications<br />In this example, the function pg_num_rows returns the number of rows that<br />are in the temporary table. (MySQL has a similar function, mysql_num_rows<br />($result).) The for loop is set up to loop once for each row in the temporary<br />table. Inside the for loop, a row is selected from the table, and foreach<br />is used to process each row. Notice that $i is passed to pg_fetch_row to tell<br />it which row to fetch.<br />The following example produces the same results with Oracle:<br />$Nfields = OCINumCols($result);<br />while (OCIFetch($result))<br />{<br />for($i=1;$i&lt;=$Nfields;$i++)<br />{<br />$value = OCIResult($result,$i);<br />echo “$value&lt;br&gt;”;<br />}<br />}<br />In this example, $Nfields is the number of fields in the result table. OCIFetch<br />gets one row from the result table. The while loop continues looping until<br />there are no more rows to get. OCIResult returns the value from one field<br />in the row. The for loop travels through the row, getting the value for each<br />field in the row and displaying it.<br />The previous examples show the bare-minimum PHP functions that you need<br />for interacting with an RDBMS. PHP offers many functions for each RDBMS,<br />such as mysql_affect_rows, which returns the number of rows changed by<br />the query, or pg_field_name, which returns the names of the fields.<br />Although the PHP database functions are similar, they are different enough<br />that you need to learn the correct functions to use for your RDBMS. Read<br />through the documentation on the PHP Web site for the functions for your<br />RDBMS. The documentation includes some examples. If you’re using MySQL,<br />PHP &amp; MySQL For Dummies contains details and many examples.<br />Closing the connection<br />Any open database connections are closed when the script ends. However, it<br />is good programming practice to close the connections in the script, to avoid<br />any possible problems. You close database connections the same way you<br />open them — with a PHP function. For example, for MySQL, use the following<br />function to close a database connection:<br />mysql_close($connect);<br />The following are examples of other closing functions:<br />271 Chapter 12: Storing Data with PHP<br />ocilogoff($connect); # Oracle<br />pg_close($connect); # PostgreSQL<br />mssql_close($connect); # MS SQL<br />Handling errors<br />When you use a connect function in PHP, the function attempts to make a<br />connection to the database, but it is not always successful. For example, the<br />database software may be down, or you may be using an invalid account name<br />or password. For example, if you attempt to connect to a MySQL database<br />with an invalid password, the following message is displayed:<br />Warning: mysql_connect(): Access denied for user:<br />‘root@localhost’ (Using password: YES) in<br />c:\test12.php on line 10<br />The message shows the account name you’re attempting to use and indicates<br />whether you’re using a password. In this case, it shows that you used a password,<br />but it doesn’t show what password you used. The statement means that<br />MySQL will not allow you to access the database because the account name<br />and password are not valid.<br />The message is a warning, not an error. Therefore, after displaying the message,<br />PHP continues to execute the rest of the script. This is not usually what<br />you want. In general, if you are unable to connect to the database, the rest of<br />the script will fail as well. So, you can use a die statement to stop the script if<br />the script fails to connect to the database. The following example shows the<br />use of a die statement when connecting to a PostgreSQL database:<br />$connect = pg_connect(“host=$host user=$user<br />password=$password dbname=Catalog”)<br />or die(“Can’t connect to database”);<br />Using this statement, the script stops if the connection attempt fails, and the<br />message in the die statement is displayed. It’s a good idea to use a die statement<br />with all the database functions so the script stops if the function is<br />unable to execute successfully.<br />When you use a function to get data from the temporary result table, you<br />may see a warning message. For example, suppose you include the following<br />statements in your script:<br />$sql = “SELECT * FROM Productt”;<br />$result = mysql_query($sql);<br />$row = mysql_fetch_array($result);<br />In this case, the typo in the table name (notice the tt in Product) results in<br />the following message:<br />272 Part IV: Common PHP Applications<br />Warning: mysql_fetch_array(): supplied argument is not a<br />valid MySQL result resource in test.php on line 9<br />The warning tells you that $result does not contain a valid result resource.<br />That is, $result does not contain a pointer to a table with rows and columns.<br />The warning usually means that the SQL query did not execute as intended<br />or that the results were different than you expected. For this example, the<br />incorrect table name caused the query to fail to execute, returning FALSE.<br />Thus, $result contains FALSE, an invalid result when used in the mysql_<br />fetch_array function.<br />No warning was displayed when the mysql_query function was executed,<br />even though the SQL query failed. A MySQL error message is generated when<br />the SQL fails, but it is not displayed unless your script specifically displays it.<br />A better format for your script is to stop the script if the SQL query fails and<br />display the MySQL error message to see what the problem is. You can display<br />the MySQL error message by using the mysql_error function. Therefore, you<br />might modify the previous statements as follows:<br />$sql = “SELECT * FROM Productt”;<br />$result = mysql_query($sql)<br />or die(“Query failed: “.mysql_error());<br />$row = mysql_fetch_array($result);<br />The output from these statements is as follows:<br />Query failed: Table ‘Catalog.productt’ doesn’t exist<br />With these statements, when the query fails to execute, the die statement displays<br />its message, which includes the MySQL error message that is displayed<br />by mysql_error, and the script stops.<br />The general error-handling procedures recommended for PHP apply to the<br />database functions as well. For example, you may not want to display errors<br />to users but send errors to a log file instead. (Error handling is described in<br />Chapter 4.)<br />Putting it all together<br />The previous sections describe the separate functions needed to interact with<br />a database in your PHP application scripts. This section provides examples<br />that put the functions together into complete scripts.<br />273 Chapter 12: Storing Data with PHP<br />For the first example, assume you have a PostgreSQL database called Sales<br />with a table called Customer. The first name, last name, and phone number<br />for each customer are stored in the table. The script in Listing 12-2 displays<br />all the names and phone numbers in a Web page.<br />Listing 12-2: A Script That Displays a Customer List<br />&lt;?php<br />/* Script name: DisplayCustomers<br />* Description: Gets all customer records from a<br />* PostgreSQL database and displays the<br />* Customer list in a Web page.<br />*/<br />include(“info.inc”); # contains connect variables<br />$connect = pg_connect(“host=$host user=$user<br />password=$password dbname=Sales”)<br />or die(“Can’t connect to database”);<br />$sql = “SELECT * from Customer”;<br />$result = pg_query($sql)<br />or die(“Query failed: “.mysql_error());<br />$Nrows = pg_num_rows($result);<br />echo “&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Customer List&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;table width=\”100%\” border=\”0\”&gt;\n”;<br />for($i=0;$i&lt;$Nrows;$i++)<br />{<br />echo “&lt;tr&gt;”;<br />$row = pg_fetch_row($result,$i);<br />echo “&lt;td&gt;{$row[1]}, {$row[0]}&lt;/td&gt;<br />&lt;td&gt;{$row[2]}&lt;/td&gt;”;<br />echo “&lt;/tr&gt;\n”;<br />}<br />echo “&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;”;<br />?&gt;<br />The script gets all the customer information from the Customer table. It then<br />uses a for loop to output the customer information to the Web page in an<br />HTML table.<br />The second example creates a list of check boxes in a Web page where users<br />can select the type of product they want to view. The script shown in Listing<br />12-3 gets the list of product types from a MySQL database. The table has two<br />fields: ProductType and Description.<br />274 Part IV: Common PHP Applications<br />Listing 12-3: A Script That Creates Check Boxes<br />&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Testing Files&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;?php<br />/* Script name: DisplayCheckboxes<br />* Description: Gets all items for check boxes from a<br />* MySQL database and creates the list of<br />* check boxes in a Web page.<br />*/<br />include(“info.inc”); # contains connect variables<br />$connection = mysql_connect($host,$user,$password)<br />or die (“Couldn’t connect to server”);<br />$db = mysql_select_db(“Catalog”,$connection)<br />or die (“Couldn’t select database”);<br />$query = “SELECT * FROM ProductType”;<br />$result = mysql_query($query)<br />or die(“Query failed: “.mysql_error());<br />echo “&lt;html&gt;&lt;head&gt;&lt;title&gt;Product Type&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;&lt;div style=’margin-left: .2in’&gt;<br />&lt;h3&gt;Which product are you interested in?&lt;/h3&gt;\n”;<br />## create form containing check boxes ##<br />echo “&lt;form action=’processform.php’ method=’post’&gt;\n”;<br />echo “&lt;hr&gt;&lt;table width=’100%’&gt;”;<br />while ($row = mysql_fetch_array($result))<br />{<br />echo “&lt;tr&gt;”;<br />echo “&lt;td width=’20%’&gt;&lt;b&gt;&lt;input type=’checkbox’<br />name=\”interest[‘ProductType’]\”<br />value=\”{$row[‘ProductType’]}\”&gt;{$row[‘ProductType’]}<br />&lt;/b&gt;&lt;/td&gt;\n”;<br />echo “&lt;td&gt;{$row[‘Description’]}&lt;/td&gt;”;<br />echo “&lt;/tr&gt;\n”;<br />}<br />echo “&lt;/table&gt;”;<br />echo “&lt;p&gt;&lt;input type=’submit’ value=’Select Product’&gt;<br />&lt;/form&gt;\n”;<br />?&gt;<br />&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;<br />The script creates an HTML form, containing an HTML table. A while loop<br />creates each row of the table and populates the table with the information<br />retrieved from the database. Notice the while condition etches a row from<br />the temporary table stored at the location contained in $result. The while<br />loop will continue to execute as long as there are rows in the table. When the<br />loop reaches the last row, the while loop will end.<br />275 Chapter 12: Storing Data with PHP<br />Notice the array variables that are echoed into the table cells. The name of<br />the array elements needs to be enclosed in curly brackets; otherwise, a parse<br />error results.<br />The script in Listing 12-3 produces the Web page shown in Figure 12-1. The<br />list of check boxes contains all the types in the database table. If more product<br />types are added to the database, they will be displayed by this script.<br />Using SQLite<br />SQLite allows you to interact with your data as if it were a database, using functions,<br />without requiring you to install database software. You use SQL, as you<br />do when you store your data in a database, but the data is actually stored in<br />a flat file. Thus, SQLite has the advantages of a flat file — fewer resources<br />required. In addition, it provides the advantage of using SQL — you don’t need<br />to learn the operating system commands required to open and manipulate a<br />flat file directly. SQLite is also faster than a database for some of the most<br />common tasks. However, it has the flat file disadvantages: poor security and<br />inability to handle really complex data. In summary, SQLite provides a quick,<br />easy way to store data in a flat file, but is not a replacement for a database if<br />you have really large amounts or really complex data or need to keep your<br />data secure.<br />Storing and retrieving data with SQLite is very similar to the methods<br />described in the preceding section for using databases with PHP. You use SQL<br />to communication with the data file and use PHP functions to send the SQL<br />and retrieve the data. You interact with the data using the same steps that<br />you use with a database, as follows:<br />Figure 12-1:<br />A Web page<br />with check<br />boxes<br />produced by<br />the script in<br />Listing 12-3.<br />276 Part IV: Common PHP Applications<br />1. Connect to the data file.<br />As with a database, first you establish a connection to the data file. To<br />connect to the data file, use the following PHP function:<br />$db = sqlite_open(“testdb”);<br />This statement opens the data file testdb. If the file doesn’t exist, it is<br />created.<br />2. Send an SQL query.<br />To send an SQL query, use the sqlite_query function, as follows:<br />$sql = “SELECT * FROM Product”;<br />$result = sqlite_query($db,$sql);<br />3. If you retrieved data from the data file, process the data.<br />As with a database, the retrieved data is stored in ae temporary table in<br />rows and columns. You can use PHP functions to retrieve one row from<br />the temporary data table and store it in an array, with the field names as<br />the array keys. The statement is as follows:<br />$row = sqlite_fetch_array($result);<br />After this statement, $row is an array containing all the fields in the temporary<br />table, such as the following:<br />$row[‘firstName’] = John<br />$row[‘lastName’] = Smith<br />To process all the data in the temporary table, you can use a loop to<br />get one row at a time, processing each row until the end of the table is<br />reached, as follows.<br />while($row=sqlite_fetch_array($result))<br />{<br />foreach($row as $value)<br />{<br />echo “$value&lt;br&gt;”;<br />}<br />}<br />4. Close the connection to the data file.<br />When you finish storing and/or retrieving data, you can close the data<br />file with the following statement:<br />sqlite_close($db);<br />Error handling as discussed in the previous section refers to SQLite, as well as<br />to databases. For instance, the die statement discussed in the Error Handling<br />section is useful with SQLite. Also, as discussed, when the query fails, an<br />277 Chapter 12: Storing Data with PHP<br />SQLite error message is generated, but not displayed unless you use a function<br />developed specifically to display it. Thus, the following statements<br />handle errors, as well as send the SQL query:<br />$sql = “SELECT * FROM Product”;<br />$result = sqlite_query($sql)<br />or die(“Query failed: “.sqlite_error());<br />$row = sqlite_fetch_array($result);<br />Read the preceding section that describes using databases with PHP. Most of<br />the information applies to the use of SQLite as well. What makes SQLite different<br />is that the data is stored in a flat file, rather than stored by the database<br />software in files that are unique to the specific database used.<br />278 Part IV: Common PHP Applications<br />Chapter 13<br />PHP and Your Operating System<br />In This Chapter<br /> Manipulating files<br /> Running programs outside PHP<br /> Transferring files from one machine to another<br /> Sending e-mail and e-mail attachments<br />PHP provides all the file-handling features that any full-featured language<br />offers. Using PHP, you can do anything you need to do with the information<br />on your system. You can manage your information in files — you can<br />create, copy, delete, find, move, and more. You can run any program that’s<br />on your computer, regardless of whether it’s a PHP program. You can transfer<br />files between computers. Or you can send information via e-mail. This chapter<br />gives you the information you need to use PHP to do pretty much anything<br />you can think of on your computer.<br />Managing Files<br />The information you save on your hard disk is organized into files. Rather<br />than storing files in one big “file drawer,” making them difficult to find, files<br />are stored in many drawers, called directories or folders. The system of files<br />and directories is called a file system. A file system is organized in a hierarchical<br />structure. A file system has a top level that is a single directory called<br />root, such as c:\ on Windows or / on Linux. The root directory contains<br />other directories, and each directory can contain other directories, and so<br />on. The file system’s structure can go down as many levels as you want.<br />A directory is a specific type of file that you use to organize other files. A directory<br />contains a list of files and the information needed for the operating system<br />to find those files. A directory can contain both files and other directories.<br />PHP includes functions that allow you to open files and read what’s in them<br />or write information into them (as discussed in Chapter 12). Files also can be<br />checked, copied, deleted, and renamed, among other things. Functions for<br />performing these additional file-management tasks are described in the following<br />sections. You also find out about functions that allow you to manage<br />directories and discover what’s inside them.<br />In this chapter, I cover the most useful functions for managing files, but more<br />functions are available. When you need to perform an action on a file or directory,<br />check the documentation on the PHP Web site to see if there’s a function<br />that does what you need to do. If such a function does not exist, you can use<br />your operating system commands or a program in another language, as<br />described in “Using Operating System Commands,” later in this chapter.<br />Getting information about files<br />Often you want to know information about a file. PHP has functions that allow<br />you to find out file information from within a script.<br />You can find out whether a file exists with the file_exists statement, as<br />follows:<br />$result = file_exists(“stuff.txt”);<br />After this statement, $result contains either TRUE or FALSE. The function is<br />often used in a conditional statement, such as the following:<br />if(!file_exists(“stuff.txt”))<br />{<br />echo “File not found!\n”;<br />}<br />After you know the file exists, you can find out information about it.<br />Table 13-1 shows many of the functions that PHP provides for checking files.<br />Table 13-1 Functions That Get Information about a File<br />Function What It Does Output<br />is_file Tests whether the file is a TRUE or FALSE<br />(“stuff.txt”) regular file, rather than a<br />directory or other special<br />type of file<br />is_dir Tests whether the file is a TRUE or FALSE<br />(“stuff.txt”) directory<br />is_executable Tests whether the file is TRUE or FALSE<br />(“do.txt”) executable<br />280 Part IV: Common PHP Applications<br />Function What It Does Output<br />is_writable Tests whether you can write TRUE or FALSE<br />(“stuff.txt”) to the file<br />is_readable Tests whether you can read TRUE or FALSE<br />(“stuff.txt”) the file<br />fileatime Returns the time when the UNIX timestamp (like<br />(“stuff.txt”) file was last accessed 1057196122) or FALSE<br />filectime Returns the time when the UNIX timestamp or FALSE<br />(“stuff.txt”) file was created<br />filemtime Returns the time when the UNIX timestamp or FALSE<br />(“stuff.txt”) file was last modified<br />filegroup Returns the group ID of the Integer that is a group<br />(“stuff.txt”) file ID or FALSE<br />fileowner Returns the user ID of the Integer that is a user ID<br />(“stuff.txt”) owner of the file or FALSE<br />filesize Returns the file size in bytes Integer or FALSE<br />(“stuff.txt”)<br />filetype Returns the file type File type (such as file, dir,<br />(“stuff.txt”) file, dir, link, char), or<br />FALSE if error or can’t identify<br />type<br />basename Returns the filename from do.txt<br />(“/t1/do.txt”) the path<br />dirname Returns the directory name /t1<br />(“/t1/do.txt”) from the path<br />Some of the information is relevant only for Linux/Unix/Mac, and some is<br />returned on Windows as well.<br />A function that returns useful info about a path/filename is pathinfo(). You<br />can use the following statement:<br />$pinfo = pathinfo(“/topdir/nextdir/stuff.txt”);<br />After the statement, $pinfo is an array that contains the following three<br />elements:<br />$pinfo[dirname] = /topdir/nextdir<br />$pinfo[basename] = stuff.txt<br />$pinfo[extension] = txt<br />281 Chapter 13: PHP and Your Operating System<br />When you’re testing a file with one of the is_something functions, any typing<br />error, such as a misspelling of the filename, gives a FALSE result. For example,<br />is_dir(“tyme”) returns FALSE if “tyme” is a file, not a directory. But, it also<br />returns FALSE if “tyme” does not exist, because you meant to type “type”.<br />Unix timestamps are returned by some of the functions in the list. You can<br />convert these timestamps to dates with the date function, as described in<br />Chapter 5.<br />Copying, renaming, and deleting files<br />Chapter 12 describes how to create a file and write information into it. In this<br />section, I describe some other things you can do with a file, such as copy it<br />or delete it.<br />You can copy an existing file into a new file. After copying, you have two<br />copies of the file with two different names. Copying a file is often useful for<br />backing up important files. To copy a file, use the copy statement, as follows:<br />copy(“fileold.txt”,”filenew.txt”);<br />This statement copies fileold.txt, an existing file, into filenew.txt. If a<br />file with the same name as filenew.txt already exists, it is overwritten. If<br />you don’t want to overwrite an existing file, you can prevent it by using the<br />following statements:<br />If(!file_exists(“filenew.txt”))<br />{<br />copy(“fileold.txt”,”filenew.txt”);<br />}<br />else<br />{<br />echo “File already exists!\n”;<br />}<br />You can rename a file by using the rename statement, as follows:<br />rename(“oldname.txt”,”newname.txt”);<br />If you attempt to rename a file with the name of a file that already exists, a<br />warning is displayed, as follows, and the file is not renamed.<br />Warning: rename(fileold.txt,filenew.txt): File exists in<br />c:test.php on line 17<br />282 Part IV: Common PHP Applications<br />To remove an unwanted file, use the unlink statement, as follows:<br />unlink(“badfile.txt”);<br />After this statement, the file is deleted. However, if the file doesn’t exist to start<br />with, unlink doesn’t complain. It acts the same as if it had deleted the file.<br />PHP does not let you know if the file doesn’t exist. So, watch out for typos.<br />Organizing files<br />Files are organized into directories, also called folders. This section describes<br />how to create and remove directories and how to get a list of the files in a<br />directory.<br />Creating a directory<br />To create a directory, use the mkdir function, as follows:<br />mkdir(“testdir”);<br />This statement creates a new directory named testdir in the same directory<br />where the script is located. That is, if the script is /test/test.php, the new<br />directory is /test/testdir. If a directory already exists with the same name,<br />a warning is displayed, as follows, and the new directory is not created:<br />Warning: mkdir(): File exists in d:/test/test.php on line 5<br />You can check first to see whether the directory already exists by using the<br />following statements:<br />If(!is_dir(“mynewdir”))<br />{<br />mkdir(“mynewdir”);<br />}<br />else<br />{<br />echo “Directory already exists!”;<br />}<br />After the directory is created, you can organize it’s contents by copying files<br />into and out of the directory. Copying files is described in the section “Copying,<br />renaming, and deleting files,” earlier in this chapter.<br />To create a directory in another directory, use the entire path name, as follows:<br />mkdir(“/topdir/nextdir/mynewdir”);<br />283 Chapter 13: PHP and Your Operating System<br />You can use a relative path to create a new directory, as follows:<br />mkdir(“../mynewdir”);<br />With this statement, if your script is /topdir/test/makedir.php, the new<br />directory is /topdir/mynewdir.<br />To change to a different directory, use the following statement:<br />chdir(“../anotherdir”);<br />Building a list of all the files in a directory<br />It’s often useful to get a list of the files in a directory. For example, you may<br />want to provide a list of files for users to download or want to display images<br />from files in a specific directory.<br />PHP provides functions for opening and reading directories. To open a directory,<br />use the opendir statement, as follows:<br />$dh = opendir(“/topdir/testdir”);<br />If you attempt to open a directory that doesn’t exist, a warning is displayed,<br />as follows:<br />Warning: opendir(testdir): failed to open dir: Invalid<br />argument in test13.php on line 5<br />In the previous statement, the variable $dh is a directory handle, a pointer to<br />the open directory that you can use later to read from the directory. To read<br />a filename from the directory, use the readdir function, as follows:<br />$filename = readdir($dh);<br />After this statement, $filename contains the name of a file. Only the filename<br />is stored in $filename, not the entire path to the file. To read all the<br />filenames in a directory, you can use a while loop, as follows:<br />while($filename = readdir($dh))<br />{<br />echo $filename.”\n”;<br />}<br />The readdir function does not provide any control over the order in which<br />filenames are read, so you don’t always get the filenames in the order you<br />expect.<br />Suppose you want to create a gallery that displays in a Web page all the images<br />in a specified directory. You can use the opendir and readdir functions to<br />do this. Listing 13-1 shows a script that creates an image gallery.<br />284 Part IV: Common PHP Applications<br />Listing 13-1: A Script That Creates an Image Gallery<br />&lt;?php<br />/* Script name: displayGallery<br />* Description: Displays all the image files that are<br />* stored in a specified directory.<br />*/<br />echo “&lt;html&gt;&lt;head&gt;&lt;title&gt;Image Gallery&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;”;<br />$dir = “../test1/testdir/”; #8<br />$dh = opendir($dir); #9<br />while($filename = readdir($dh)) #10<br />{<br />$filepath = $dir.$filename; #12<br />if(is_file($filepath) and ereg(“\.jpg$”,$filename)) #13<br />{<br />$gallery[] = $filepath;<br />}<br />}<br />sort($gallery); #16<br />foreach($gallery as $image) #17<br />{<br />echo “&lt;hr&gt;”;<br />echo “&lt;img src=’$image’&gt;&lt;br&gt;”;<br />}<br />?&gt;<br />&lt;/body&gt;&lt;/html&gt;<br />Notice the line numbers at the end of some of the lines in Listing 13-1. The following<br />discussion of the script and how it works refers to the line numbers in<br />the script listing:<br /> Line 8: This line stores the name of the directory in $dir for use later in<br />the program. Notice that the / is included at the end of the directory name.<br />Don’t use \, even with Windows.<br /> Line 9: This line opens the directory.<br /> Line 10: This line starts a while loop that reads in each file name in the<br />directory.<br /> Line 12: This line creates the variable $filepath, which is the complete<br />path to the file.<br />If the / is not included at the end of the directory name on line 8,<br />$filepath will not be a valid path.<br /> Line 13: This line checks to see whether the file is a graphics file by looking<br />for the .jpg extension. If the file has a .jpg extension, the complete<br />file path is added to an array called $gallery.<br /> Line 16: This line sorts the array so the images are displayed in alphabetical<br />order.<br /> Line 17: This line starts the foreach loop that displays the images in<br />the Web page.<br />285 Chapter 13: PHP and Your Operating System<br />Using Operating System Commands<br />Your operating system has many commands you can use by typing the commands<br />at the command-line prompt. If you want to see what files are in a<br />directory, for example, you can use the dir command in a Windows command<br />prompt window or the ls command in Unix/Linux. Or to make a copy of a file,<br />you can use the copy command in the Windows command prompt window or<br />the cp command in Unix/Linux. (To access the command prompt window in<br />Windows 2000, choose Start➪Programs➪Accessories➪Command Prompt.)<br />In this section, I assume that you know the format and use of the system commands<br />for your operating system. Describing operating system commands is<br />outside the scope of this book. If you know that you need to run an operating<br />system command from your PHP script, this section shows you how.<br />PHP has functions to perform the most widely used actions. For example, you<br />can see what files are in a directory by using the opendir and readdir functions,<br />as described earlier in the chapter. Or, you can make a copy of a file with<br />the copy function.<br />286 Part IV: Common PHP Applications<br />Error messages from system commands<br />None of the methods for executing system commands<br />displays or returns an informational error<br />message when the system command fails. You<br />know the system command didn’t work because<br />you didn’t get the outcome you expected. But<br />because the functions don’t return error messages,<br />you don’t know what went wrong.<br />You can return or display the operating system<br />error message by adding a few extra characters<br />to the system command you’re executing. On<br />most operating systems, if you add the characters<br />2&gt;&amp;1 after the system command, the error<br />message is sent to wherever the output is<br />directed. For example, you can use the following<br />statement:<br />$result = system(“di c:\php”);<br />The system function displays the directory<br />when the system command executes. However,<br />notice that dir is mistyped. It is di rather than<br />dir. No system command called di exists, so<br />the system command can’t execute, and nothing<br />is displayed. Suppose you used the following<br />statement instead:<br />$result = system(“di c:\php<br />2&gt;&amp;1”);<br />In this case, the error message is displayed. On<br />Windows 2000, the error message displayed is<br />as follows:<br />‘di’ is not recognized as an<br />internal or external command,<br />operable program or<br />batch file.<br />Be sure you don’t include any spaces in 2&gt;&amp;1.<br />The format requires the characters together,<br />without any spaces.<br />However, you may want to perform an action not provided by PHP, such as<br />making a copy of an entire directory, including files; looking at or changing<br />your path; or clearing the screen. Or, you may think it’s easier to use a system<br />command, such as using ls or dir to see your directory, rather than write<br />the loop required with opendir and readdir. Or, you may want to run a<br />program in another language. You may have a program written in Perl, for<br />example, that does exactly what you need, and you don’t want to write a new<br />program in PHP to do the same thing. No problem. You can do all of these<br />things through PHP.<br />PHP allows you to use system commands or run programs in other languages<br />by using any of the following methods:<br /> backticks: PHP executes the system command that is between two<br />backticks ( `) and displays the result.<br /> system function: This function executes a system command, displays<br />the output, and returns the last line of the output.<br /> exec function: This function executes a system command, stores the<br />output in an array, and returns the last line of the output.<br /> passthru function: This function executes a system command and displays<br />the output.<br />You can execute any command that you can type into the system prompt. The<br />command is executed exactly as is. You can execute simple commands: ls or<br />dir. rename or mv, rm or del. If your operating system allows you to pipe or<br />redirect output, you can pipe or redirect in the system command you’re executing<br />in PHP. If your operating system allows you to enter two commands on<br />one line, you can put two commands into the single command you’re executing<br />from PHP. The following sample commands are valid to execute from PHP,<br />depending on the operating system:<br />dir<br />rm badfile.txt<br />dir | sort<br />cd c:\php ; dir (Not valid in Windows)<br />“cd c:\php &amp;&amp; dir” (Windows 2000)<br />dir &gt; dirfile<br />sort &lt; unsortedfile.txt<br />On some occasions, you want to run a system command that takes a long<br />time to finish. You can run the system command in the background (if your<br />operating system supports such things) while PHP continues with the script.<br />If you do this, you need to redirect the output to a file, rather than return it to<br />the script, so that PHP can continue before the system command finishes.<br />The following sections describe the preceding methods in greater detail.<br />287 Chapter 13: PHP and Your Operating System<br />Using backticks<br />A simple way to execute a system command is to put the command between<br />two backticks ( `), as follows:<br />$result = `dir c:\php`;<br />The variable $result contains the statement’s output, in this case a list of<br />the files in the c:\php directory. If you echo $result, the following output is<br />displayed:<br />Volume in drive C has no label.<br />Volume Serial Number is 394E-15E5<br />Directory of c:\php<br />02/25/2004 10:48a &lt;DIR&gt; .<br />02/25/2004 10:48a &lt;DIR&gt; ..<br />02/25/2004 04:30p &lt;DIR&gt; dev<br />02/25/2004 04:30p &lt;DIR&gt; ext<br />02/25/2004 04:30p &lt;DIR&gt; extras<br />02/25/2004 04:30p 417,792 fdftk.dll<br />02/25/2004 04:30p 90,112 fribidi.dll<br />02/25/2004 04:30p 346,624 gds32.dll<br />02/25/2004 04:30p 70 go-pear.bat<br />02/25/2004 04:30p 32,081 install.txt<br />02/25/2004 04:30p 876,544 libeay32.dll<br />02/25/2004 04:30p 47,027 libintl-1.dll<br />02/25/2004 04:30p 165,643 libmhash.dll<br />02/25/2004 04:30p 233,472 libmysql.dll<br />02/25/2004 04:30p 3,208 license.txt<br />02/25/2004 04:30p 57,344 msql.dll<br />02/25/2004 04:30p 18,151 news.txt<br />02/25/2004 04:30p 278,800 ntwdblib.dll<br />02/25/2004 04:30p &lt;DIR&gt; PEAR<br />02/25/2004 04:30p 53,248 php-cgi.exe<br />02/25/2004 04:30p 28,672 php-win.exe<br />02/25/2004 04:30p 28,672 php.exe<br />02/25/2004 04:30p 3,872 php.gif<br />02/25/2004 04:30p 39,284 php.ini-dist<br />02/25/2004 04:30p 40,899 php.ini-recommended<br />02/25/2004 04:30p 40,960 php5activescript.dll<br />02/25/2004 04:30p 36,864 php5apache.dll<br />02/25/2004 04:30p 36,864 php5apache2.dll<br />02/25/2004 04:30p 53,248 php5apache_hooks.dll<br />02/25/2004 04:30p 503,320 php5embed.lib<br />02/25/2004 04:30p 28,672 php5isapi.dll<br />02/25/2004 04:30p 28,672 php5nsapi.dll<br />02/25/2004 04:30p 3,452,928 php5ts.dll<br />02/25/2004 04:30p 1,224 snapshot.txt<br />288 Part IV: Common PHP Applications<br />02/25/2004 04:30p 159,744 ssleay32.dll<br />02/25/2004 04:30p 49,152 php_mysql.dll<br />30 File(s) 7,153,163 bytes<br />6 Dir(s) 251,727,872 bytes free<br />The backtick operator is disabled when safe_mode is enabled. safe_mode is<br />set to Off by default when PHP is installed. safe_mode is not set to On unless<br />the PHP administrator deliberately turns it on.<br />Using the system function<br />The system function executes a system command, displays the output, and<br />returns the last line of the output from the system command. To execute a<br />system command, use the following statement:<br />$result = system(“dir c:\php”);<br />When this statement executes, the directory listing is displayed, and $result<br />contains the last line that was output from the command. If you echo $result,<br />you see something like the following:<br />11 Dir(s) 566,263,808 bytes free<br />The contents of $result with the system function is the last line of the<br />output from the dir command.<br />Using the exec function<br />The exec function executes a system command but does not display the<br />output. Instead, the output can be stored in an array, with each line of<br />the output becoming an element in the array. The last line of the output is<br />returned.<br />Perhaps you just want to know how many files and free bytes are in a directory.<br />You can execute a command without saving the output in an array with<br />the following statement:<br />$result = exec(“dir c:\php”);<br />The command executes, but the output is not displayed. The variable $result<br />contains the last line of the output. If you echo $result, the display looks<br />something like this:<br />11 Dir(s) 566,263,808 bytes free<br />289 Chapter 13: PHP and Your Operating System<br />The output is the last line of the output of the dir command. If you want to<br />store the entire output from the dir command in an array, use the following<br />command:<br />$result = exec(“dir c:\php”,$dirout);<br />After this statement, the array $dirout contains the directory listing, with<br />one line per item. You can display the directory listing as follows:<br />foreach($dirout as $line)<br />{<br />echo “$line\n”;<br />}<br />The loop displays the following:<br />Volume in drive D has no label.<br />Volume Serial Number is 394E-15E5<br />Directory of d:\php<br />02/25/2004 10:48a &lt;DIR&gt; .<br />02/25/2004 10:48a &lt;DIR&gt; ..<br />02/25/2004 04:30p &lt;DIR&gt; dev<br />02/25/2004 04:30p &lt;DIR&gt; ext<br />02/25/2004 04:30p &lt;DIR&gt; extras<br />02/25/2004 04:30p 417,792 fdftk.dll<br />You can also use the following statements to get specific elements from the<br />output array:<br />echo $dirout[3];<br />echo $dirout[7];<br />The output is as follows:<br />Directory of C:\PHP<br />02/25/2004 04:30p &lt;DIR&gt; dev<br />Using the passthru function<br />The passthru function executes a system command and displays the output<br />exactly as it is returned. To execute a system command, use the following<br />statement:<br />passthru(“dir c:\php”);<br />290 Part IV: Common PHP Applications<br />The statement displays the directory listing but does not return anything.<br />Therefore, you don’t use a variable to store the returned data because nothing<br />is returned.<br />The output is displayed in raw form; it is not processed. Therefore, this function<br />can be used when binary output is expected.<br />Understanding security issues<br />When you execute a system command, you allow a user to perform an action<br />on your computer. If the system command is dir c:\php, that’s okay.<br />However, if the system command is rm /bin/* or del c:\*.*, you won’t be<br />happy with the results. You need to be careful when using the functions that<br />execute system commands outside your script.<br />As long as you only execute commands that you write yourself, such as dir<br />or ls, you’re okay. But when you start executing commands that include data<br />sent by users, you need to be extremely careful. For example, suppose you<br />have an application in which users type a name into a form and your application<br />then creates a directory with the name sent by the user. The user types<br />Smith into the form field named directoryName. Your script that processes<br />the form has a command as follows:<br />$directoryName = $_POST[‘directoryName’];<br />exec(“mkdir $directoryName”);<br />Because $directoryName = Smith, mkdir Smith is the system command<br />that is executed. The directory is created, and everybody is happy.<br />However, suppose the user types Smith; rm * into the form. In this case,<br />$directoryName =Smith;rm *. The system command that executes is now<br />mkdir Smith;rm *. On many operating systems, such as Unix/Linux, the semicolon<br />is the character that separates two commands so that two commands<br />can be entered on one line. Oops! The commands are executed as follows:<br />mkdir Smith<br />rm *<br />Now you have a problem. The directory Smith is created, and all the files in<br />the current directory are removed.<br />If you use a variable in a system command, you must use it carefully. You<br />must know where it came from. If it comes from outside the script, you need<br />to check the value in the variable before using it. In the preceding example,<br />you could add code so the script checks the variable to be sure it contains<br />only letters and numbers before using it in the mkdir command.<br />291 Chapter 13: PHP and Your Operating System<br />Using FTP<br />Transferring files from one computer to another happens a gazillion times a<br />day on the Internet. When colleagues on opposite sides of the country need<br />to share files, it’s not a problem. A quick transfer takes only seconds, and all<br />parties have the files they need.<br />Files can be transferred by using your Web server or FTP. Transferring files<br />via your Web server is described in Chapter 11. In this section, I discuss how<br />to transfer files using FTP.<br />FTP is independent of the Web. You can use FTP to transfer files in a script<br />running in PHP for the Web or in an independent, stand-alone script. FTP<br />allows you to get a directory listing from another computer, or to download<br />or upload a single file or several files at once.<br />FTP is client/server software. To use FTP to transfer files between your computer<br />and a remote computer, you connect to an FTP server on the remote<br />computer and send it requests.<br />To use FTP in your scripts, FTP support needs to be enabled when PHP is<br />installed. If you installed PHP for Windows, you don’t need to do anything<br />extra to enable FTP support. If you’re compiling PHP on Unix/Linux/Mac, and<br />you want to enable FTP support, you can use the FTP support installation<br />option, as follows:<br />&#8211;enable-ftp<br />For more information on this and other installation options, see Appendix A.<br />Logging in to the FTP server<br />To connect to the FTP server on the computer you want to exchange files<br />with, use the ftp_connect function, as follows:<br />$connect = ftp_connect(“janet.valade.com”);<br />Or, you can connect by using an IP address, as follows:<br />$connect = ftp_connect(“172.17.204.2”);<br />After you connect, you log into the FTP server. You need a user ID and a password<br />to log in. You may have your own personal ID and password, or you may<br />be using a general ID and password that anyone can use. Some public sites<br />292 Part IV: Common PHP Applications<br />on the Internet let anyone login by using the user ID of anonymous and the<br />user’s e-mail address as the password. It’s best to put the user ID and password<br />into a separate file and include the file when needed. (See Chapter 8 for<br />more details.)<br />The ftp_login function allows you to login to an FTP server after you’ve<br />made the connection. This statement assumes you have your account ID and<br />password stored in variables, as follows:<br />$login_result = ftp_login($connect,$userid,$passwd);<br />If you try to login without establishing a connection to the FTP server first,<br />you see the following warning:<br />Warning: ftp_login() expects parameter 1 to be resource,<br />boolean given in d:\test1\test13.php on line 9<br />The warning does not stop the program. The login fails, but the script continues,<br />which is probably not what you want. Because the rest of your script<br />probably depends on your successful FTP connection, you may want to stop<br />the script if the functions fail. The following statements stop the script if the<br />function fails:<br />$connect = ftp_connect(“janet.valade.com”)<br />or die(“Can’t connect to server”);<br />$login_result = ftp_login($connect,$userid,$passwd)<br />or die(“Can’t login to server”);<br />After you login to the FTP server, you can send it requests to accomplish<br />tasks, such as getting a directory listing or uploading and downloading files,<br />as described in the following sections.<br />Getting a directory listing<br />One common task is to get a directory listing. The ftp_nlist statement gets<br />a directory listing from the remote computer and stores it in an array, as<br />follows:<br />$filesArr = ftp_nlist($connect,”data”);<br />The second parameter in the parentheses is the name of the directory. If you<br />don’t know the name of the directory, you can request the FTP server to send<br />you the name of the current directory, as follows:<br />$directory_name = ftp_pwd($connect);<br />$filesArr = ftp_nlist($connect,$directory_name);<br />293 Chapter 13: PHP and Your Operating System<br />The directory listing that FTP sends after the ftp_nlist statement runs is<br />stored in an array, one filename in each element of the array. You can then<br />display the directory listing from the array, as follows:<br />foreach($filesArr as $value)<br />{<br />echo $value\n;<br />}<br />Downloading and uploading files with FTP<br />You can download a file from the remote computer with the ftp_get function.<br />The following statement downloads a file from the remote computer after<br />you’re logged into the FTP server:<br />ftp_get($connect,”newfile.txt”,”data.txt”,FTP_ASCII);<br />The first filename, newfile.txt, is the name the file will have on your computer<br />after it’s downloaded. The second filename, data.txt, is the existing<br />name of the file that you want to download.<br />The FTP_ASCII term in the statement tells FTP what kind of file is being downloaded.<br />The choices for file mode are FTP_ASCII or FTP_BINARY. Binary files<br />are machine language files. You can determine which file mode you need by<br />examining the contents of the file. If the contents are characters that you can<br />read and understand, the file is ASCII. If the contents appear to be garbage,<br />the file is binary. Graphic files, for example, are binary.<br />You can upload a file with a similar function called ftp_put. The following<br />statement uploads a file.:<br />ftp_put($connect,”newfile.txt”,”data.txt”,FTP_ASCII);<br />The first filename, newfile.txt, is the name the file will have on the remote<br />computer after it’s uploaded. The second filename, data.txt, is the existing<br />name of the file that you want to upload.<br />When you’re finished transferring files over your FTP connection, you can<br />close the connection with the following statement:<br />ftp_close($connect);<br />The script in Listing 13-2 downloads all the files in a directory that have a<br />.txt extension. The files are downloaded from the remote computer over an<br />FTP connection.<br />294 Part IV: Common PHP Applications<br />Listing 13-2: A Script to Download Files via FTP<br />&lt;?php<br />/* Script name: downloadFiles<br />* Description: Downloads all the files with a txt<br />* extension in a directory via FTP.<br />*/<br />$dir_name = “data/”;<br />$connect = ftp_connect(“janet.valade.com”)<br />or die(“Can’t connect to FTP server”);<br />$login_result = ftp_login($connect,$userID,$passwd)<br />or die(“Can’t log in”);<br />$filesArr = ftp_nlist($connect,$dir_name);<br />foreach($filesArr as $value)<br />{<br />if(ereg(“\.txt$”,$value))<br />{<br />if(!file_exists($value))<br />{<br />ftp_get($connect,$value,$dir_name.$value,FTP_ASCII);<br />}<br />else<br />{<br />echo “File $value already exists!\n”;<br />}<br />}<br />}<br />ftp_close($connect);<br />?&gt;<br />The script gets a directory listing from the remote computer and stores it in<br />$filesArr. The foreach statement loops through the filenames in $filesArr<br />and checks to see whether files have a .txt extension. If so, the scripts tests<br />to see whether a file with the same name already exists. If such a file doesn’t<br />already exist, the file is downloaded; if such a file does exist, a message is<br />printed, and the file is not downloaded.<br />Other FTP functions<br />Additional FTP functions perform other actions, such as change to another<br />directory on the remote computer or create a new directory on the remote<br />computer. Table 13-2 contains most of the FTP functions that are available.<br />295 Chapter 13: PHP and Your Operating System<br />Table 13-2 FTP Functions<br />Function What It Does<br />ftp_cdup($connect) Changes to the directory directly above the<br />current directory.<br />ftp_chdir($connect, Changes directories on the remote computer.<br />”directoryname”)<br />ftp_close($connect) Closes an FTP connection.<br />ftp_connect(“servername”) Opens a connection to the computer.<br />servername can be a domain name or an<br />IP address.<br />ftp_delete($connect, Deletes a file on the remote computer.<br />”path/filename”)<br />ftp_exec($connect, Executes a system command on the remote<br />”command”) computer.<br />ftp_fget($connect,$fh, Downloads the file contents from the remote<br />”data.txt”,FTP_ASCII) computer into an open file. $fh is the file<br />handle of the open file. (See Chapter 12 for<br />more on file handles.)<br />ftp_fput($connect, Uploads an open file to the remote computer.<br />”new.txt”,$fh,FTP_ASCII) $fh is the file handle of the open file.<br />ftp_get($connect,”d.txt”, Downloads a file from the remote computer.<br />”sr.txt”,FTP_ASCII) sr.txt is the name of the file to be downloaded,<br />and d.txt is the name of the downloaded<br />file.<br />ftp_login($connect, Logs into the FTP server.<br />$userID,$password)<br />ftp_mdtm($connect, Gets the time when the file was last modified.<br />”filename.txt”)<br />ftp_mkdir($connect, Creates a new directory on the remote<br />”directoryname”) computer.<br />ftp_nlist($connect, Gets a list of the files in a remote directory.<br />”directoryname”) Files are returned in an array.<br />ftp_put($connect,”d.txt”, Uploads a file to the remote computer.<br />”sr.txt”,FTP_ASCII) sr.txt is the name of the file to be<br />uploaded, and d.txt is the filename on the<br />remote computer.<br />ftp_pwd($connect) Gets the name of the current directory on the<br />remote computer.<br />296 Part IV: Common PHP Applications<br />Function What It Does<br />ftp_rename($connect, Renames a file on the remote computer.<br />”oldname”,”newname”)<br />ftp_rmdir($connect, Deletes a directory on the remote computer.<br />”directoryname”)<br />ftp_size($connect, Returns the size of the file on the remote<br />”filename.txt”) computer.<br />ftp_systype($connect) Returns the system type of the remote file<br />server, for example Unix.<br />Using E-Mail<br />E-mail is the most widely used application on the Internet. Many PHP applications<br />require the use of e-mail. Applications that allow customers to order<br />products send e-mail messages to customers to acknowledge their orders.<br />When users create a new account, the application sends them e-mail to verify<br />their accounts. When users click the “I forgot my password” link on a login<br />screen, the application sends the users e-mail with their passwords. Applications<br />send monthly newsletters to lists of subscribers. And e-mail has many<br />other uses as well.<br />PHP provides a function that makes sending e-mail simple. This section tells<br />you how to send e-mail from your application.<br />Setting up PHP to send e-mail<br />E-mail is sent by an outgoing e-mail server. To send e-mail, you need access to<br />an outgoing server. If you can send e-mail from your own computer right now,<br />you’re using an outgoing server. You just need to tell PHP the name of the outgoing<br />e-mail server so PHP can find it when you send mail from your script.<br />Your outgoing mail server is typically an SMTP (Simple Mail Transfer Protocol)<br />server. Whether you use a LAN at work, a cable modem at home, or an ISP via<br />a modem, you send your mail with an SMTP server, and the server has an<br />address that you need to know.<br />You can usually find out the name of your outgoing server through your<br />e-mail software. The e-mail software must know the name of your e-mail<br />server so it can store the name somewhere. Look for the settings for your<br />e-mail software and find the name of your outgoing server. In Outlook<br />Express, you can usually find it by performing the following steps:<br />297 Chapter 13: PHP and Your Operating System<br />1. Choose Tools➪Services.<br />2. In the list of services, highlight Internet Email.<br />3. Click Properties.<br />4. Click the Servers tab.<br />You see a field that shows the name of your outgoing mail server.<br />If you can’t find the name of your outgoing mail server, you can ask your e-mail<br />administrator for the name. If you use an ISP, you can ask the ISP. The name is<br />likely to be in a format similar to the following:<br />mail.ispname.net<br />If you’re using a Linux/Unix computer connected to a network, the mail server<br />is probably sendmail.<br />With the name of your outgoing mail server in front of you, open php.ini.<br />Look for the following lines:<br />[mail function]<br />; For Win32 only.<br />SMTP = localhost<br />; For Win32 only.<br />;sendmail_from = me@localhost.com<br />; For Unix only. You may supply arguments as well (default:<br />“sendmail -t -i”).<br />;sendmail_path =<br />Windows users need to change the first two settings. The first setting is<br />where you put the name of your outgoing server, as follows:<br />SMTP = mail.ispname.com<br />The second setting is the return address that is sent with all your e-mail.<br />Change the setting to the e-mail address you want to use for your return<br />address, as follows:<br />sendmail_from = Janet@Valade.com<br />The third setting is for Unix users. The default is usually correct. If it doesn’t<br />work, you need to talk to your system administrator about the correct path<br />to your outgoing mail server.<br />298 Part IV: Common PHP Applications<br />For Unix users: Some paths to sendmail that may be correct are /usr/sbin/<br />sendmail or /usr/lib/sendmail. If your system doesn’t use sendmail,<br />there is usually a wrapper for the e-mail server you are using. For example,<br />Qmail users may try /var/qmail/bin/sendmail or /var/qmail/bin/<br />qmail-inject.<br />You may have to restart your Web server before the e-mail settings in<br />php.ini go into effect.<br />Sending e-mail messages<br />PHP provides a function called mail that sends e-mail from your script. The<br />format is as follows:<br />mail(address,subject,message,headers);<br />These are the values you need to fill in:<br /> address: The e-mail address that receives the message<br /> subject: A string that goes on the subject line of the e-mail message<br /> message: The content that goes in the e-mail message<br /> headers: A string that sets values for e-mail headers<br />You may set up and send an e-mail message as follows:<br />$to = “janet@valade.com”;<br />$subj = “Test”;<br />$mess = “This is a test of the mail function”;<br />$headers = bcc:techsupport@mycompany.com\r\n<br />$mailsend = mail($to,$subj,$mess,$headers);<br />The message is sent to the address in the $to variable. You can send the message<br />to more than one person by using the following statement:<br />$to= “janet@valade.com,me@mycompany.com”;<br />The $headers string in this example also sends a blind copy of the message<br />to techsupport. You can include more than one header as follows:<br />$header = “cc:tech@mycompany.com\r\nbcc:sales@mycompany.com”;<br />Headers are optional. Only the first three parameters are required.<br />299 Chapter 13: PHP and Your Operating System<br />The $mailsend variable contains TRUE or FALSE. However, TRUE is no guarantee<br />that the mail will get to where it’s going. It just means that it started<br />out okay.<br />Sending e-mail attachments<br />Sometimes you may prefer to send information as an e-mail attachment rather<br />than as an e-mail message. For example, you may want to send the 30-page<br />service contract to all your customers as an attachment, rather than as a<br />30-page e-mail message.<br />To send a message as an attachment, you send a mail header instructing that<br />the e-mail be sent as an attachment. The header is as follows:<br />Content-disposition: attachment; filename=test.txt<br />The header tells the e-mail software to send the message as an attachment<br />with the filename of test.txt. The following example shows how to send a<br />short message as an attachment, although it’s very unlikely that you’d actually<br />want to do this:<br />$to = “janet@valade.com”;<br />$subj = “Testing an attachment”;<br />$mess = &lt;&lt;&lt; END<br />This is the test message.<br />This message should arrive as an attachment.<br />Let’s see what happens.<br />END;<br />$headers = “Content-disposition: attachment;<br />filename=test.txt\n”;<br />$headers .= “cc:sales@mycompany.com\n”;<br />$mailsend = mail($to,$subj,$mess,$headers);<br />This e-mail message has two headers: the Content-disposition header and<br />the cc header. The headers are written together into one string, stored in the<br />variable $headers. Each header ends with \n. With some e-mail software, to<br />get the same effect you may need to use \r\n at the end.<br />If you want to send e-mail as an attachment, it’s probably because you want<br />to send the contents of a file. To do this, you simply read the file into a variable<br />that you then send as the message. Reading data from a file is discussed<br />in more detail in Chapter 12.<br />For the purpose of sending e-mail, you can store the read file as one long string.<br />PHP provides the file_get_contents function for that purpose, as follows:<br />$mess = file_get_contents(“filename”);<br />Listing 13-3 shows a script that sends a text file as an attachment.<br />300 Part IV: Common PHP Applications<br />Listing 13-3: A Script to Send a Text File As an E-Mail Attachment<br />&lt;?php<br />/* Script name: mailTest<br />* Description: Sends a text file as an e-mail<br />* attachment.<br />*/<br />$filename = “mydata.txt”;<br />$mess = file_get_contents($filename);<br />$to = “janet@valade.com”;<br />$subj = “Sending mydata as an attachment “;<br />$headers = “Content-disposition: attachment;<br />filename=mydata.txt\n”;<br />if(!$mailsend = mail($to,$subj,$mess,$headers))<br />{<br />echo “Mail not sent\n”;<br />}<br />else<br />{<br />echo “Mail sent\n”;<br />}<br />?&gt;<br />This script reads the contents into a string with file_get_contents. The<br />header is stored in $headers. Then the mail is sent with the mail function.<br />An if statement tests whether the mail function succeeds, printing the<br />appropriate message.<br />You may want to send another type of file as an attachment, not just a text<br />file. To do this, you need to send headers that tell the e-mail software what<br />type of file you’re sending. One such header is the Content-type header,<br />which you can send as follows:<br />Content-type: contenttype<br />The content type for plain text is text/plain, the type of file in the previous<br />examples. In most cases, text/plain is the default. Another type of text file<br />is an HTML file, which has the content type of text/html.<br />Other types of files you may want to send are binary files. For example, image<br />files, audio files, and video files are binary files. Some of the file types for these<br />files are as follows:<br />image/gif<br />image/jpeg<br />audio/x-wav<br />audio/vnd.rn-realaudio<br />video/mpeg<br />video/avi<br />You also may want to send application files. Some are text files, and some are<br />binary files. For example, an RTF file is a text file, whereas a Word document<br />301 Chapter 13: PHP and Your Operating System<br />or an Excel spreadsheet are binary files. A general type for binary files is<br />application/octet-stream. If the file is binary and you’re unsure what<br />application generated it, try application/octet-stream.<br />Binary files should be encoded when sent over e-mail, to ensure that they arrive<br />in good shape. PHP provides functions that encode files for you, as follows:<br />$mess = chunk_split(base64_encode($string));<br />The variable $string contains the contents of the binary file stored with the<br />fread function.<br />In addition, if you send an encoded file, you need to let the mail software know<br />about that as well, with the following header:<br />Content-Transfer-Encoding: base64<br />The script in Listing 13-4 shows how to send a graphics file (binary and<br />encoded) as an e-mail attachment.<br />Listing 13-4: A Script to Send a Graphics File as an E-Mail Attachment<br />&lt;?php<br />/* Script name: mailGraphic<br />* Description: Sends a graphic file as an e-mail<br />* attachment.<br />*/<br />$filename = “logo.gif”;<br />$fh = fopen($filename,”rb”);<br />$fileContent = fread($fh,filesize($filename));<br />fclose($fh);<br />$mess = chunk_split(base64_encode($fileContent));<br />$to = “janet@valade.com”;<br />$subj = “Sending an image as an attachment”;<br />$headers = “Content-disposition: attachment;<br />filename=logo.gif\n”;<br />$headers .= “Content-type: image/gif\n”;<br />$headers .=”Content-Transfer-Encoding: base64\n”;<br />if(!$mailsend = mail($to,$subj,$mess,$headers))<br />{<br />echo “Mail not sent\n”;<br />}<br />else<br />{<br />echo “Mail sent\n”;<br />}<br />?&gt;<br />This script encodes the file contents to store in $mess. It includes the additional<br />headers needed for transferring information that’s not text.<br />302 Part IV: Common PHP Applications<br />Chapter 14<br />PHP Extensions<br />In This Chapter<br /> Understanding extensions<br /> Installing PEAR<br /> Using PEAR packages<br />The PHP architecture consists of a PHP core and PHP extensions. The PHP<br />core provides the basic functionality of the language.<br />PHP’s great flexibility and power depend greatly on its hundreds of functions,<br />which consist of built-in functions and functions available in a PHP extension.<br />Many PHP built-in functions are discussed throughout this book, and Appendix<br />B provides a reference list of many functions. However, many more functions<br />are available in PHP through the use of extensions.<br />Most PHP functions are contained in the PHP extensions. Extensions broaden<br />the capabilities of PHP. Several core extensions are compiled into PHP and are<br />always there by default. Other standard extensions are included in the PHP<br />distribution, but you must add them to PHP before you can use their functions.<br />PHP database functions are among those included in the PHP distribution<br />that must be activated before they can be used (as discussed in Chapter 12).<br />In addition, many extensions are written and made available by individuals.<br />Many of the best of these are part of PEAR, the PHP Extension and Application<br />Repository.<br />This chapter discusses available extensions and how to get and use them.<br />Investigating the Basic Extensions<br />The basic PHP distribution includes several extensions. These are compiled<br />into PHP, and their functions are available for your use. You don’t actually need<br />to know about these extensions. You don’t need to do anything to activate<br />them; you can just use their functionality. (In fact, if you don’t want them, you<br />have to do something to deactivate them, as discussed in Appendix A.) Many<br />of the functions that are made available by extensions are discussed throughout<br />this book.<br />To determine which extensions are activated in your PHP installation, look at<br />the information that is output by phpinfo(). It shows a list of settings for the<br />PHP core, and then it shows the settings for the PHP extensions that are activated.<br />The following list of extensions is activated by default:<br /> BCMath: A math library that has more precision than PHP floating point<br />numbers provide.<br /> calendar: A library that provides functions for converting between various<br />calendar formats, such as Julian, Gregorian, French Republican, and<br />so on.<br /> COM: Provides access to COM objects.<br /> ctype: Functions that check characters, such as checking whether characters<br />are alphabetic characters or punctuation.<br /> ftp: Functions that connect and send requests to an FTP server. Can be<br />used to transfer files between computers.<br /> odbc: Functions for using ODBC databases.<br /> pcre: Functions for Perl-compatible regular expressions.<br /> session: Functions for creating and using PHP built-in sessions.<br /> SQLite: Functions for storing data in flat files using SQL.<br /> tokenizer: Functions that parse PHP code.<br /> wddx: Functions for use with WDDX, an XML-based standard for<br />exchanging data between applications.<br /> xml: A library to parse XML documents.<br /> zlib: A library to read and write gzip-compressed files.<br />This list shows the extensions that are currently compiled into PHP. However,<br />this list of extensions can change. By the time you read this, the list may be<br />longer or shorter.<br />If you downloaded and installed Windows binaries for PHP, the preceding<br />extensions were compiled into the binaries. If you compile your own PHP on<br />Unix or Linux, these extensions are included by default. If you want to exclude<br />one of them, you must exclude it when you compile. For example, if you are<br />not using sessions and don’t want sessions support compiled into your version<br />of PHP, you need to use an installation option, as described in Appendix<br />A, as follows:<br />304 Part IV: Common PHP Applications<br />&#8211;disable-session<br />In general, the built-in extensions are the ones that users are most likely to<br />use. It’s rarely wise to exclude any of them.<br />PHP is included on most Linux computers when purchased and in most Linux<br />distributions when you install the operating system. However, if you are using<br />PHP provided by your Web hosting company and thus didn’t install PHP yourself,<br />you can’t be sure which extensions were installed. Usually the extensions<br />listed in this section are included, but there are no guarantees. You can find<br />documentation for these extensions in the on-line PHP manual at the PHP<br />Web site.<br />Taking a Look at Standard Extensions<br />Many extensions are included in the PHP distribution but not compiled into<br />PHP. That is, you have the necessary files, but support for the extensions is<br />not built-in. You need to activate them before you can use them. Generally,<br />these extensions are needed less frequently than the basic extensions. The<br />PHP developers provide the extensions for your use but don’t compile them<br />into PHP to conserve resources.<br />If you need to use any of the extensions in the PHP distribution, adding an<br />extension to your PHP installation is not difficult. If you compile PHP when<br />installing it, use the installation option for the extension you need. (The installation<br />instructions in Appendix A discuss installation options.) Most Unix and<br />many Linux and Mac users compile PHP at installation. Very few Windows<br />users compile PHP.<br />If you download and install a binary copy of PHP, rather than compile your<br />own, you can install any of the standards extensions as follows:<br />1. Copy the appropriate dll file from the ext subdirectory into your main<br />directory.<br />The ext subdirectory is in a location such as c:\php\ext.<br />2. Open your php.ini file and look for a line similar to the following:<br />;extension=php_gd2.dll<br />3. Remove the semicolon at the beginning of the line.<br />305 Chapter 14: PHP Extensions<br />The following are some of the most popular extensions:<br /> Database extensions: Many people use database extensions. They provide<br />functions for interacting with a specific type of database. As mentioned<br />previously, the ODBC database extension is included in PHP by<br />default. (Database extensions are discussed in Chapter 12.)<br /> GD library: One of the most popular extensions is the GD library. It provides<br />functions so you can output graphics, as well as HTML. You can<br />create and manipulate images in several formats, such as JPEG, GIF, PNG,<br />and others.<br />PHP versions since (and including) PHP 4.3.0 include a bundled version<br />of GD, which is preferable to other versions of GD. You can use this bundled<br />version rather than installing an external version of GD. To do this,<br />compile with the installation option with-gd2, as described in Appendix<br />A, and do not specify a path to a directory (do not use =DIR).<br /> PDF extension: This is a library of functions that allow you to create a<br />PDF document. You can set fonts, write text to the document, and add<br />graphics.<br /> cURL: This library allows you to communicate with many kinds of<br />servers, such as HTTPS, Telnet, FTP, LDAP, and others.<br />Most extensions provide functions that interact with software libraries. For<br />example, the database extensions provide functions that interact with specific<br />database software. For extensions to work, the software they interact with<br />must be installed. (For example, for the Oracle database extensions to work,<br />the Oracle software must be installed.) On occasion, the software libraries<br />are already installed on your computer. If not, you must download and install<br />the required library. Be sure to look at the documentation in the PHP manual<br />on the PHP Web site for any extension you are considering using. Look for<br />information about the required libraries and where to get them and to see any<br />other specific requirements for the extension. Some libraries are provided in<br />the PHP distribution, so that you don’t need to find them and download them<br />yourself. Such libraries are available in the main directory where PHP is<br />installed. For example, MySQL support requires that the library<br />libmysql.dll (MySQL 4.0 or earlier) or libmysqli.dll (MySQL 4.1 or later)<br />be available. This library is included in the main PHP directory, allowing the<br />mysql and mysqli functions to work correctly.<br />Table 14-1 provides a list of most of the extensions provided with the PHP distribution,<br />with the exception of the database extensions, which are described<br />in Chapter 12.<br />In the table, all dll names start with php_ and are found in the php/ext directory.<br />DIR is the directory where the software library is installed. If DIR is not<br />included, a default is used.<br />306 Part IV: Common PHP Applications<br />Table 14-1 PHP Extensions<br />Extension Description dll name Install option<br />bzip2 Read/write bzip2- _bz2.dll &#8211;with-bz2=DIR<br />Compression compressed files.<br />ClibPDF Create PDF _cpdf.dll &#8211;with-cpdflib=DIR<br />documents.<br />Crack Test the strength _crack.dll &#8211;with-crack=DIR<br />of a password.<br />cURL Communicate _curl.dll &#8211;with-curl=DIR<br />with various types<br />of servers.<br />Domxml Read/create XML _domxml.dll &#8211;with-dom=DIR<br />documents.<br />FDF Handle forms with _fdf.dll &#8211;with-fdftk=DIR<br />PDF document.<br />GD Output images. _gd2.dll &#8211;with-gd2<br />gettext Native language _gettext.dll &#8211;with-gettext=DIR<br />support.<br />iconv Convert strings _iconv.dll &#8211;with-iconv=DIR<br />between character<br />set encoding.<br />IMAP Manage e-mail. _imap.dll &#8211;with-imap=DIR<br />JAVA Integrate Java _java.dll &#8211;with-java=DIR<br />support.<br />LDAP Access directory _ldap.dll &#8211;with-ldap=DIR<br />servers.<br />Multi-byte Handle Japanese _mbstring.dll &#8211;with-mbstring=<br />String and (default is LANG<br />Japanese) other<br />characters.<br />Mcrypt Encrypt strings. _mcrypt.dll &#8211;with-mcrypt=DIR<br />Encryption<br />Mhash Create check- _mhash.dll &#8211;with-mhash=DIR<br />sums and more.<br />(continued)<br />307 Chapter 14: PHP Extensions<br />Table 14-1 (continued)<br />Extension Description dll name Install option<br />Mime type Guess the content _mime_magic.dll &#8211;with-mime-magic<br />type.<br />Ming for Create Flash _ming.dll &#8211;with-ming<br />Flash format movies.<br />OpenSSL Provide secure _openssl.dll &#8211;with-openssl=<br />data transfer. DIR<br />PDF Create PDF files. _pdf.dll &#8211;with-pdflib=DIR<br />Printer Write data to _printer.dll N/A<br />printer. Windows<br />only.<br />Shared Read/write _shmop.dll &#8211;enable-shmop<br />Memory shared memory<br />segments.<br />SNMP Manage SNMP _snmp.dll &#8211;with-snmp=DIR<br />objects.<br />Sockets Low-level inter- _sockets.dll &#8211;enable-sockets<br />face to socket<br />communication.<br />XML-RPC Write XML-RPC _xmlrpc.dll &#8211;with-xmlrpc=DIR<br />servers and<br />clients.<br />XSLT Extensible Style- _xslt.dll &#8211;enable-xslt<br />sheet Language<br />Transformations.<br />Zip Files Read zip files. _zip.dll &#8211;with-zip=DIR<br />At any time, some of these extensions can be removed from the PHP distribution<br />or new extensions can be added.<br />308 Part IV: Common PHP Applications<br />Using PEAR<br />PEAR is the PHP Extension and Application Repository, and it maintains a<br />structured library of open source code. The code itself is provided by developers<br />outside PEAR, but PEAR handles the management and distribution of<br />code from the various projects.<br />PEAR has developed a consistent method of distribution. Code for a project<br />is distributed in packages. Developers who want to contribute an extension<br />or application must conform to standards. They must include specified<br />elements in their packages, such as documentation, and use PEAR coding<br />standards and methods for handling errors. The standard structure makes<br />maintaining code more feasible over the long run. If the developer who is<br />maintaining a PEAR application wins the lottery and goes on a permanent<br />vacation to Tahiti, someone else can assume the maintenance of the abandoned<br />code more easily because its structure and standards are consistent.<br />Before a project is added to PEAR, it must be accepted. PEAR only accepts<br />high-quality code that conforms to the coding standards. Code contributors<br />must be willing to maintain the code and provide documentation. Code contributors<br />submit their code to the PEAR developers, who must accept it<br />before it is added to PEAR. After it’s accepted, the code contributors add it to<br />PEAR and maintain it.<br />Finding a PEAR Package<br />According to the PEAR Web site (http://pear.php.net), PEAR currently<br />holds 263 packages. Six packages are included with the PHP software when<br />you download it:<br /> DB: Database abstraction layer. Allows you to interact with different<br />databases by using the same set of functions.<br /> Net_Socket: Net Socket Interface. A class interface to TCP sockets.<br /> Net_SMTP: Provides an implementation of the SMTP (Simple Mail<br />Transfer Protocol) protocol using Net_Socket.<br /> Mail: Provides various methods for checking and sending e-mail.<br /> XML_Parser: An XML parser based on PHP’s built-in XML extension.<br /> PHPUnit: Used to automate testing of PHP functions and classes.<br />309 Chapter 14: PHP Extensions<br />You can find these PEAR packages in the directory where PHP is installed in<br />PEAR/packages or PEAR/go-pear-bundle. The packages are in zipped files.<br />You can use the PEAR installer, described in the following section, to install<br />the PEAR package.<br />Descriptions of all the PEAR packages are available on the PEAR Web site<br />(pear.php.net). You can browse through categories to look for packages,<br />or you can search the package database.<br />Notice two links in the left column of the Web page: List Packages and Search<br />Packages. To browse, click List Packages; you see the following categories:<br />310 Part IV: Common PHP Applications<br />Authentication<br />Benchmarking<br />Caching<br />Configuration<br />Console<br />Database<br />Date and Time<br />Encryption<br />File Formats<br />File System<br />Gtk Components<br />HTML<br />HTTP<br />Images<br />Internationalization<br />Logging<br />Mail<br />Math<br />Networking<br />Numbers<br />Payment<br />PEAR<br />PHP<br />Processing<br />Science<br />Streams<br />Structures<br />Text<br />Tools and Utilities<br />Web Services<br />XML<br />If you click a category, you see a page showing all the packages in that category.<br />If you click a package, you see a page showing package information. The<br />dependencies section lists packages that must be installed before this package<br />will run. You also see links to where you can download the package.<br />However, you don’t need to download it manually. The PEAR installer will<br />download it for you.<br />If you click Search Packages, you see a search form that allows you to search<br />for a package by name, category, maintainer, or date. The search results give<br />you a list of links to packages that match your search. If you click one of<br />these links, it takes you to the information page for the package.<br />The information page provides a short description about the package, which<br />may or may not be enough information to determine whether it’s the package<br />you need. You can find more information about the package in the manual.<br />One of the links in the left panel on the PEAR home page is Manual, under<br />Documentation. Clicking this link takes you to the PEAR manual table of contents<br />(after you select a language). Section IV, Packages, has a link for each<br />package category. The category manual page contains documentation for the<br />packages in the category. More package information is available in the manuals,<br />including instructions for using the classes/functions in the package.<br />You can return to the PEAR Web site home page at any point by clicking the<br />pear in the upper-left corner of any page.<br />After you have identified the package you want, write down its exact name.<br />You find out how to install it in the following sections.<br />Setting up PEAR<br />PEAR includes a package manager that administers PEAR packages. The package<br />manager is included in your PHP distribution. The installer can install,<br />uninstall, and update packages. It maintains a registry of installed packages. It<br />can display a list of available packages, check information about packages,<br />check dependencies, and perform other management tasks.<br />Setting up PEAR when compiling PHP<br />If you compiled PHP yourself, the PEAR installer was included, and the six bundled<br />PEAR applications were installed. You can check the PEAR installer by<br />running pear.php from your PHP directory. To do this, type pear, and a list<br />of options for PEAR is displayed. Alternatively, you can type pear list-all,<br />in which case a list of all packages available is displayed. (This process sometimes<br />takes a minute or two because the list is downloaded over the Internet.)<br />For versions of PHP prior to 4.3.0, the PEAR installer is not installed when PHP<br />is compiled and installed. You can find a script that downloads and installs<br />the PEAR components at go-pear.org.<br />Setting up PEAR on Windows<br />If you installed PHP using the installer or the zip file, PEAR was not installed.<br />To set up PEAR on Windows, you need to perform the following steps:<br />311 Chapter 14: PHP Extensions<br />1. Download the PEAR components.<br />You need to download the Windows zip file for manual installation, as<br />described in Appendix A. Then unzip the PEAR directory into the directory<br />where PHP is installed, which is generally a directory such as c:\<br />php\pear. If you installed PHP by using the manual installation instructions<br />from Appendix A, all the pieces of PEAR should be there already;<br />you don’t need to download them again.<br />2. Add the PEAR directory to your include file path.<br />Open php.ini and look for the following line:<br />include_path = “.;c:\php\includes;c:\php\PEAR”<br />If the path shown does not include the PEAR directory, add it as shown<br />in this example php.ini line.<br />3. Download and install the PEAR Installer.<br />Double-click go-pear.php (or go-pear.bat) in the directory where<br />PHP is installed. The go-pear script opens a command prompt window<br />and displays the following:<br />Welcome to go-pear!<br />Go-pear will install the ‘pear’ command and all the files<br />needed by it. This command is your tool for PEAR<br />installation and maintenance.<br />Go-pear also lets you download and install the PEAR<br />packages bundled with PHP: DB, Net_Socket, Net_SMTP,<br />Mail,<br />XML_Parser, phpUnit.<br />If you wish to abort, press Control-C now, or press<br />Enter:<br />The program asks you a few questions and installs the PEAR installer. It<br />also gives you the option of installing the six bundled packages if you<br />want. When the program is finished, it displays a final message.<br />The code in the go-pear.bat script includes the following line that sets the<br />path to PHP CLI. In previous versions of PHP, PHP CLI was located in a subdirectory<br />called /cli. If the script line shows the old path, as follows:<br />Set PHP_BIN=cli/php.exe<br />the go-pear script will fail. If so, you can edit the file so the path is correct.<br />After you finish installing the PEAR installer (and the 6 programs if you chose<br />to install them), you should have a program called pear.bat in the directory<br />where PHP is installed. You can test pear.bat by running it from the Command<br />312 Part IV: Common PHP Applications<br />Prompt window. To do this, type pear, and a list of options for PEAR is displayed.<br />Alternatively, you can type pear list-all, in which case a list of all<br />packages available is displayed. (This process sometimes takes a minute or<br />two because the list is downloaded over the Internet.)<br />When you use list-all with the PEAR installer, it displays a list of all available<br />programs. Remember the name of any program that looked useful for<br />you. You need to know the exact name in order to install the program.<br />Installing a PEAR package<br />You install a PEAR package using the PEAR installer (the pear.bat program<br />installed in the previous section). You test the installer in the previous section<br />by getting a list of all the packages available. In this section, you find out how<br />to install a package using the PEAR installer.<br />To install a package, type the following in your PHP directory (c:\php):<br />pear install packagename<br />The PEAR installer downloads the package file from the PEAR Web site and<br />installs it. For example, you can install Mail by typing the following:<br />pear install Mail<br />pear then displays the following:<br />downloading Mail-1.0.2.tgz &#8230;<br />&#8230;done: 12,287 bytes<br />requires package ‘Net_SMTP’<br />Mail: dependencies failed<br />This output says that Mail was downloaded. It also tells you that Mail requires<br />Net_SMTP in order to run and that Net_SMTP is not installed. Therefore, it did<br />not install Mail. You need to install Net_SMTP and then install Mail.<br />After you have installed Net_SMTP and then installed Mail, if you try to install<br />Mail again, the PEAR installer displays:<br />Mail already installed<br />You can get a list of all the PEAR packages currently installed by typing the<br />following:<br />pear list<br />313 Chapter 14: PHP Extensions<br />You can update a package with the following command:<br />pear upgrade Mail<br />In this case, the following output is displayed:<br />downloading Mail-1.0.2.tgz &#8230;<br />&#8230;done: 12,287 bytes<br />upgrade to a newer version (1.0.2 is not newer than 1.0.2)<br />If you try to install without being connected to the Internet, the PEAR<br />installer displays the following message:<br />Connection to pear.php.net:80 failed<br />You can uninstall any package, as follows:<br />pear uninstall Mail<br />The following is displayed:<br />uninstall ok: Mail<br />Using a PEAR package<br />After a package has been installed, you can use its functions or methods.<br />Accessing a PEAR package<br />After a package has been installed, a file with the package name (with a .php<br />extension) resides in the PEAR directory. For example, after you install Mail,<br />the PEAR directory contains a file named Mail.php. To use a PEAR package,<br />you include that file in your script. For example, you can use the Mail package<br />in your script after you use the following statement:<br />require_once(“Mail.php”);<br />Use require_once to be sure the entire Mail.php file is not included more<br />than once. Using require causes the script to stop if the Mail.php file can’t<br />be found.<br />For the details on using the methods or functions of a package, see the PEAR<br />manual on the PEAR Web site.<br />DB is one of the most popular PEAR packages. Therefore, I use DB in the<br />next section to demonstrate the use of a PEAR package. I don’t provide a<br />314 Part IV: Common PHP Applications<br />comprehensive explanation of the DB package — just a short program to<br />show you the principles of using a PEAR package.<br />Introducing DB — an example of a PEAR package<br />DB is a library that allows you to interact with different databases by using<br />the same functions. In Chapter 12, you discover that PHP has several sets of<br />database functions, a different set for each database. Consequently, you use<br />functions such as mysql_connect and pg_connect. Database access is very<br />simple with database functions.<br />The problem with using database functions arises if you change your database.<br />Suppose you have your database application humming along using MySQL,<br />and one morning your boss walks in and says, “I just bought Oracle. We need<br />to move all our data into Oracle.” Not only must you move all the data, but<br />you must also find all the places in your PHP scripts where you use MySQL<br />database functions and change them all to Oracle functions. Some of the<br />functions may have a different format, and some may have parameters in a<br />different order. This is certain to cause problems for a while.<br />If you’re positive you will never change to another database, you don’t need to<br />concern yourself with this specter. However, if there’s any possibility of changing<br />your database in the future, you may want to use a database-independent<br />database interface instead. DB is popular for database interaction.<br />Interacting with a database<br />Using PEAR DB, you use steps similar to those that are described in Chapter 12<br />to interact with a database:<br />1. Connect to the database<br />2. Send the database a query that tells it to perform an action.<br />3. If information is returned from the query, process the information.<br />To connect to a database using PEAR DB, you just provide the parameters,<br />such as the account and password, and the SQL to be executed and tell PEAR<br />DB which type of database it’s communicating with. The required information,<br />formatted correctly, is the Data Source Name (DSN). Using the information in<br />the DSN, DB handles the exact syntax. To give DB the necessary information,<br />you can use the following statements:<br />$host = “localhost”;<br />$user = “admin”;<br />$passwd = “secret”;<br />$dbname = “Sales”;<br />$dbtype = “mysql”;<br />$dsn = “$dbtype://$dbuser:$dbpasswd@$host/$dbname”;<br />315 Chapter 14: PHP Extensions<br />The $dsn variable contains the information PEAR DB needs to connect to a<br />database. You can connect to the database as follows:<br />$db = DB::connect($dsn);<br />After you are connected to the database you can send an SQL query as follows:<br />$sql = “SELECT * from Customer”;<br />$result = $db-&gt;query($sql);<br />If the query returns data, as the SELECT query does, you can access the information<br />using the following DB statement:<br />$row = $result-&gt;fetchRow(DB_FETCHMODE_ASSOC);<br />In this statement, the method fetchRow returns one row of the results in an<br />associative array with the field names as the keys to the array. You can then<br />use the data in the array in the same way as you use any other array.<br />As you can see, if you change your database, the only thing you need to change<br />is the value for $dbtype. Nothing else in your script needs to be changed. So<br />by doing a little extra work up front, you eliminate the problems created by<br />changing from one RDBMS to another. As of this writing, PEAR DB supports<br />the following types of databases:<br /> mysql (MySQL)<br /> pgsql (PostgreSQL)<br /> ibase (InterBase)<br /> msql (Mini SQL)<br /> mssql (Microsoft SQL Server)<br /> oci8 (Oracle 7/8/8I)<br /> odbc (ODBC — Open Database Connectivity)<br /> sybase (Sybase)<br /> ifx (Informix)<br /> fbsql (FrontBase)<br />To change to another database (say from MySql to Sybase), you can just<br />change $dbtype = “mysql”; to $dbtype = “sybase”; and you’re done.<br />Handling errors<br />As described in Chapter 12, statements that interact with a database can fail.<br />For example, the database software may be down when your script attempts<br />to connect. You want your script to stop when the database interaction fails,<br />and you want to receive an informative message.<br />316 Part IV: Common PHP Applications<br />DB provides the method isError that you can use to check for errors. The<br />method checks the variable to see whether it is TRUE or an error object. If<br />the variable contains an error object, you can use a method called getMessage<br />to see what the error message is. The following statements show how to use<br />isError:<br />$db = DB::connect($dsn);<br />if(DB::isError($db))<br />{<br />die($db-&gt;getMessage());<br />}<br />The method isError checks the contents of $db. If $db contains TRUE, the<br />connect function succeeded, and the statements in the if block are not executed.<br />However, if $db contains an error object, the if block executes. In this<br />case, the if block contains a die statement, which displays a message and<br />stops the script. $db-&gt;getMessage gets the error message stored in $db.<br />Suppose the information you used in building the DSN included a typo in the<br />database name. The connect statement fails, and the die statement displays<br />the following message:<br />DB Error: no such database<br />Putting it all together<br />The script shown in Listing 14-1 displays a customer list taken from a database.<br />A script to produce the same output was shown in Chapter 12, using<br />PostgreSQL database functions. The script from Chapter 12 is shown here, in<br />altered form, by using the PEAR DB library.<br />Listing 14-1: A Script That Displays a Customer List<br />&lt;?php<br />/* Script name: DisplayCustomer-DB<br />* Description: Gets all customer records from a<br />* database and displays the<br />* Customer list in a Web page.<br />*/<br />require_once(“DB.php”); # includes PEAR DB classes<br />$host = “localhost”;<br />$dbuser = “admin”;<br />$dbpasswd = “secret”;<br />$dbname = “Sales”;<br />$dbtype = “pgsql”;<br />$dsn = “$dbtype://$dbuser:$dbpasswd@$host/$dbname”;<br />$db = DB::connect($dsn);<br />if(DB::isError($db))<br />{<br />die($db-&gt;getMessage());<br />}<br />(continued)<br />317 Chapter 14: PHP Extensions<br />Listing 14-1 (continued)<br />$sql = “SELECT * from Customer”;<br />$result = $db-&gt;query($sql);<br />if(DB::isError($result))<br />{<br />die($result-&gt;getMessage());<br />}<br />echo “&lt;html&gt;<br />&lt;head&gt;&lt;title&gt;Customer List&lt;/title&gt;&lt;/head&gt;<br />&lt;body&gt;<br />&lt;table width=\”100%\” border=\”0\”&gt;\n”;<br />while($row = $result-&gt;fetchRow(DB_FETCHMODE_ASSOC))<br />{<br />if(DB::isError($row))<br />{<br />die($row-&gt;getMessage());<br />}<br />echo “&lt;tr&gt;”;<br />echo “&lt;td&gt;{$row[‘lastname’]}, {$row[‘firstname’]}&lt;/td&gt;<br />&lt;td&gt;{$row[‘phone’]}&lt;/td&gt;”;<br />echo “&lt;/tr&gt;\n”;<br />}<br />echo “&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;”;<br />?&gt;<br />The output is a list of customer names in the following format:<br />Lastname, Firstname phonenumber<br />Using PEAR libraries is easy in terms of getting access to them. The PEAR<br />installer installs the package, and you just include it with a require_once<br />statement. However, each package has its own functions and classes and<br />methods for accomplishing tasks. In a way, each new package is like learning<br />a new language. The things you know about PHP may not help you at all. Some<br />PEAR packages are documented well in the PEAR manual, online documentation,<br />and books. Other PEAR packages are not documented as thoroughly.<br />318 Part IV: Common PHP Applications<br />Part V<br />The Part of Tens<br />In this part . . .<br />The chapters in this part extend your knowledge of<br />PHP. This part provides hints and warnings to keep<br />in mind while programming and pointers to the megainformation<br />on PHP that is available on the Web. PHP itself<br />is a growing, expanding language. As a PHP programmer,<br />you will grow and expand along with it.<br />Chapter 15<br />Ten Things to Look For When<br />Troubleshooting a Script<br />In This Chapter<br /> Recognizing common PHP errors<br /> Interpreting error messages<br />Iguarantee that you will do all the things that I mention in this chapter. You<br />just can’t write scripts without making these mistakes. The trick is to train<br />yourself to recognize them, roll your eyes, say, “Not again,” and just fix them.<br />One error message that you’ll see many times is<br />Parse error: parse error in c:\test.php on line 7<br />This is PHP’s way of saying “Huh?” It means that it doesn’t understand something.<br />This message helpfully points to the file and the line number where PHP<br />got confused. Sometimes it’s directly pointing at the error, but sometimes<br />PHP’s confusion results from an error earlier in the script.<br />Here are ten of the most common errors and how to avoid them.<br />Missing Semicolons<br />Every PHP statement ends with a semicolon (;). PHP doesn’t stop reading a<br />statement until it reaches a semicolon. If you leave out the semicolon at the<br />end of a line, PHP continues reading the statement on the following line. For<br />example, consider the following statement:<br />$test = 1<br />echo $test;<br />These statements don’t make sense to PHP; it reads the two lines as one<br />statement, so it complains with an error message, such as the following:<br />Parse error: parse error in c:\test.php on line 2<br />This is a very common error. Before you know it, you’ll be writing your home<br />address with semicolons at the end of each line.<br />Not Enough Equal Signs<br />In a comparison statement, in which you ask whether two values are equal,<br />you need two equal signs in a row. Using one equal sign is a common mistake.<br />It’s a perfectly reasonable error because you have been using one equal sign<br />to mean equal since the first grade when you learned that 2 + 2 = 4. This is a<br />difficult mistake to recognize because it doesn’t cause an error message. It<br />just makes your script do odd things, like infinite loops or if blocks that<br />never execute. I am continually amazed at how long I can stare at<br />$test = 0;<br />while ( $test = 0 )<br />{<br />$test++;<br />}<br />and not see why it’s looping endlessly.<br />Misspelled Variable Names<br />This is another PHP gotcha that doesn’t result in an error message, just odd<br />script behavior. If you misspell a variable name, PHP considers it a new variable<br />and does what you ask it to do. Here’s another clever way to write an<br />infinite loop:<br />$test = 0;<br />while ( $test == 0 )<br />{<br />$Test++;<br />}<br />Remember, to PHP, test is not the same as Test.<br />322 Part V: The Part of Tens<br />Missing Dollar Signs<br />A missing dollar sign in a variable name is really hard to see, but at least it<br />usually results in an error message so that you know where to look for the<br />problem. It usually results in the old familiar parse error:<br />Parse error: parse error in test.php on line 7<br />Troubling Quotes<br />You can have too many, too few, or the wrong kind of quotes. You have too<br />many when you put quotes inside of quotes, such as this example:<br />$test = “&lt;table width=”100%”&gt;”;<br />PHP sees the second double quote (“) — before 100 — as the ending double<br />quote (“) and reads the 1 as an instruction, which makes no sense. Voilà!<br />Another parse error. The line must be either<br />$test = “&lt;table width=’100%’&gt;”;<br />or<br />$test = “&lt;table width=\”100%\”&gt;”;<br />You have too few quotes when you forget to end a quoted string, such as<br />$test = “&lt;table width=’100%’&gt;;<br />PHP continues reading the lines as part of the quoted string until it encounters<br />another double quote (“), which may not occur for several lines. This is<br />one occasion when the parse error that points to where PHP got confused is<br />not pointing to the actual error. The actual error occurred some lines previously,<br />when you forgot to end the string.<br />You have the wrong kind of quotes when you use a single quote (‘) when you<br />meant a double quote (“) or vice versa. The difference between single and<br />double quotes is sometimes important and is explained in Chapter 5.<br />323 Chapter 15: Ten Things to Look For When Troubleshooting a Script<br />Invisible Output<br />Some statements, such as the header statement, must execute before the<br />script produces any output. If you try to use such statements after sending<br />output, they fail. The following statements fail because the header message is<br />not the first output:<br />&lt;html&gt;<br />&lt;?php<br />header(“Location: http://company.com”);<br />?&gt;<br />&lt;html&gt; is not in a PHP section and is therefore sent as HTML output. The following<br />statements work:<br />&lt;?php<br />header(“Location: http://company.com”);<br />?&gt;<br />&lt;html&gt;<br />The following statements fail:<br />&lt;?php<br />header(“Location: http://company.com”);<br />?&gt;<br />&lt;html&gt;<br />It’s not easy to see, but there’s one, single blank space before the opening PHP<br />tag. The blank space is output to the browser, although the resulting Web page<br />looks empty. Therefore, the header statement fails because there is output<br />before it. This is a common mistake and is difficult to spot.<br />Numbered Arrays<br />PHP believes that the first value in an array is numbered zero (0). Of course,<br />humans tend to believe that lists start with the number one (1). This fundamentally<br />different way of viewing lists results in us humans believing an array<br />isn’t working correctly when it is indeed working just fine. For example, consider<br />the following statements:<br />$test = 1;<br />while ( $test &lt;= 3 )<br />{<br />$array[] = $test;<br />$test++;<br />}<br />echo $array[3];<br />324 Part V: The Part of Tens<br />No output (or an error notice) results. I leap to the conclusion that there is<br />something wrong with my loop. Actually, it’s fine. It just results in the following<br />array:<br />$array[0]=1<br />$array[1]=2<br />$array[2]=3<br />and doesn’t set anything into $array[3].<br />Including PHP Statements<br />When a file is read in by using an include statement in a PHP section, it seems<br />reasonable to me that the statements in the file will be treated as PHP statements.<br />After all, PHP adds the statements to the script at the point where I<br />include them. However, PHP doesn’t see it my way. If a file named file1.inc<br />contains the following statements:<br />if ( $test == 1 )<br />echo “Hi”;<br />and I read it in with the following statements in my main script:<br />&lt;?php<br />$test = 1;<br />include (“file1.inc”);<br />?&gt;<br />I expect the word Hi to display on the Web page. However, the Web page actually<br />displays this:<br />if ( $test == 1 ) echo “Hi”;<br />Clearly, the file that is included is seen as HTML. To send Hi to the Web page,<br />file1.inc needs to contain the PHP tags.<br />&lt;?php<br />if ( $test == 1 )<br />echo “Hi”;<br />?&gt;<br />Missing Mates<br />Parentheses and curly brackets must come in pairs. Opening with a ( that<br />has no closing ) or a { without a } results in an error message. One of my<br />325 Chapter 15: Ten Things to Look For When Troubleshooting a Script<br />favorite examples of this is when I use one closing parenthesis where two are<br />needed, as in the following statement:<br />if ( isset($test)<br />This statement needs a closing parenthesis at the end. It’s much more difficult<br />to spot that one of your blocks didn’t get closed when you have blocks<br />inside of blocks inside of blocks. For example, consider the following:<br />while ( $test &lt; 3 )<br />{<br />if ( $test2 != “yes” )<br />{<br />if ( $test3 &gt; 4 )<br />{<br />echo “go”;<br />}}<br />You can see there are three opening curly brackets but only two closing ones.<br />Imagine that 100 lines of code are inside these blocks. It can be difficult to spot<br />the problem — especially if you think the last closing bracket is closing the<br />while loop, but PHP sees it as closing the if loop for $test2. Somewhere<br />later in your script, PHP may be using a closing bracket to close the while<br />loop that you aren’t even looking at. It can be difficult to trace the problem in<br />a large script.<br />Indenting blocks makes it easier to see where closing brackets belong. Also, I<br />often use comments to keep track of where I am, such as<br />while ( $test &lt; 3 )<br />{<br />if ( $test2 != “yes” )<br />{<br />if ( $test3 &gt; 4 )<br />{<br />echo “go”;<br />} # closing if block for $test3<br />} # closing if block for $test2<br />} # closing while block<br />Confusing Parentheses and Brackets<br />I’m not sure whether this is a problem for everyone or just a problem for me<br />because I refuse to admit that I can’t see as well as I used to. Although PHP<br />has no trouble distinguishing between parentheses and curly brackets, my<br />eyes are not so reliable. Especially while staring at a computer screen at the<br />end of a 10-hour programming marathon, I can easily confuse ( and {. Using<br />the wrong one gets you a parse error message.<br />326 Part V: The Part of Tens<br />Chapter 16<br />Ten PHP Resources You<br />Can’t Live Without<br />In This Chapter<br /> Where to find articles and tutorials<br /> Where to find code libraries<br />One advantage of PHP is its growing developer community. Many people<br />use it, and the PHP community is helpful. Many resources are available<br />online. This chapter describes the most useful resources. Remember that you<br />are not alone.<br />The PHP Web Site<br />This is the official PHP Web site. Here, new versions of PHP are released for<br />download, and the PHP manual is online. You can find anything that you need<br />to know about PHP here.<br />www.php.net<br />PHP Lists<br />When you’ve struggled for days with some recalcitrant code that stubbornly<br />refuses to run, take it to the lists. Hundreds of PHP developers frequent the<br />lists, and these folks know everything. Post a question to a PHP list, and you<br />often have the answer before your finger is off your mouse key. You’ll find<br />different lists for different subjects: php-general, php-db, php-install,<br />php-windows, and others. You can sign up for the lists on the PHP Web site.<br />The PHP lists have a lot of traffic. You can easily get more than 100 e-mail messages<br />per day. However, when you are starting with PHP, reading the messages<br />that other coders ask and the solutions that they receive can greatly help you<br />learn PHP. At the very least, subscribe to the announce list to be informed of<br />new versions and important releases. The announce list won’t deluge you with<br />e-mail; it only sends a message every now and then.<br />www.php.net/mailing-lists.php<br />Zend<br />The Zend engine is the core scripting engine of PHP. This Web site is full of<br />information about PHP. You can find tutorials, articles, news, online seminars,<br />and even a PHP job board.<br />http://zend.com<br />PHP Builder<br />PHP Builder is a Web site containing a variety of resources for PHP coders.<br />You can find news there and a list of useful articles. In addition, PHP Builder<br />has a code library where you can obtain snippets of code or functions for a<br />broad range of uses. You can search for code in such categories as databases,<br />calendars, shopping carts, games, graphics, and many others.<br />www.phpbuilder.com<br />Black Beans<br />If you could only have one resource, the Black Beans Web site would be a<br />good candidate. Black Beans is a Web site that provides lists of resources. It<br />has links to articles, forums, user groups, tools, and many other resources.<br />www.black-beans.com.br/php_home_eng.htm<br />PHP Beginners<br />PHP Beginners is a collection of articles on PHP and related subjects. Articles<br />there are oriented specifically toward beginners.<br />www.phpbeginner.com<br />328 Part V: The Part of Tens<br />PHP Dev Center<br />PHP Dev Center is a repository of very good PHP articles and tutorials on<br />subjects from beginners to quite advanced levels. The authors are always<br />knowledgeable.<br />www.onlamp.com/php<br />PHPMac.com<br />This Web site has articles and instructions for installing and using PHP for<br />the Mac. This information is invaluable and much harder to find than information<br />on PHP for Windows and Unix/Linux.<br />www.phpmac.com<br />PHP Editors<br />This Web site provides a list of all the editors and IDEs (Integrated Development<br />Environments) that you can use to write PHP scripts. As of this moment, 105<br />are listed, both free and commercial. The list includes comments from users.<br />http://phpeditors.linuxbackup.co.uk<br />SourceForge.net<br />SourceForge.net is the largest repository of Open Source code and applications<br />available on the Internet. You can find software for all purposes at this<br />site. You can find software written specifically in PHP by using the following<br />method:<br />1. Click the Software Map tab.<br />2. Click Programming Language in the column on the right.<br />3. Click PHP in the column of alphabetically listed programming languages<br />on the left.<br />As of today, SourceForge.net shows almost 7,000 projects in PHP.<br />www.sourceforge.net<br />329 Chapter 16: Ten PHP Resources You Can’t Live Without<br />Free PHP Hosting Directory<br />This site is a list of free Web hosting companies that offer PHP. Hosts are<br />rated up to five stars.<br />www.oinko.net/freephp<br />My Web Site<br />I provide a Web site where I support my books. There I post the scripts from<br />the book and additional code for download by readers, as well as a list of any<br />necessary error corrections. I also provide PHP news and links to important<br />PHP-related Web sites.<br />http://janet.valade.com<br />330 Part V: The Part of Tens<br />Part VI<br />Appendixes<br />In this part . . .<br />This part provides the instructions for installing PHP, as<br />well as a complete reference of essential PHP functions.<br />In Appendix B, you can quickly find any function that you<br />need, including functions that I didn’t have room to discuss<br />in the book.<br />Appendix A<br />Installing PHP<br />In this Appendix, I describe how to install PHP on the Unix/Linux, Windows,<br />and Mac platforms, both for use with Web sites and with PHP command<br />line interface (CLI). For Web sites, although PHP runs with several Web servers,<br />I discuss Apache and IIS (Microsoft Internet Information Server), which<br />together power almost 90 percent of the Web sites on the Internet. If you need<br />instructions for other operating systems or Web servers, see the PHP Web<br />site (www.php.net).<br />This appendix provides installation instructions for PHP 5. If you are installing<br />an earlier version, the installation may be slightly different; in this case, please<br />read the file install.txt that is provided with the PHP distribution.<br />Installing PHP on Computers<br />Running Unix/Linux<br />You can install PHP as a partner with Apache for use in Web pages or as a<br />stand-alone interpreter. If you want to use PHP for both Web sites and as<br />a stand-alone language, you need to install PHP with Apache and PHP CLI,<br />which are two separate types of PHP. The instructions below include information<br />for both types of PHP installations — PHP for the Web and PHP CLI.<br />You install PHP by downloading the source files, compiling them, and then<br />installing the compiled programs. This process isn’t as technical and daunting<br />as it may appear. I provide step-by-step instructions in the next few sections.<br />Read all the way through the steps before you begin the installation procedure<br />to be sure that you understand it all clearly. Try to have everything prepared<br />so you don’t have to stop in the middle of the installation.<br />For Linux users only: Many Linux distributions automatically install both<br />Apache and PHP, thus saving you the trouble of installing them yourself. In<br />addition, PHP for Linux is available in an RPM as well as in source files. It may<br />be in RPM format on your distribution CD. However, when PHP is preinstalled<br />or when you install it from an RPM, you can’t control the options that PHP<br />is installed with. For example, in these instances, PHP CLI may not have been<br />installed. Or perhaps an RPM doesn’t install PHP with support for the database<br />that you plan to use. In addition, an RPM usually enables all the most popular<br />options, so an RPM may enable options that you don’t need. And Linux distributions<br />and RPMs are likely to be slightly older versions; they probably don’t<br />install the most recent version of PHP that is available. Consequently, the simplest<br />and most efficient way to install PHP may be from the source. If you’re<br />familiar with RPMs, by all means feel free to find an RPM and install it. RPMs<br />are available. However, I provide steps for source code installation, not RPMs.<br />Before installing on Unix/Linux<br />If you want to use PHP with Apache for your Web site, Apache must be<br />installed. Most Unix/Linux operating systems install Apache by default when<br />the operating system is installed. Before beginning to install PHP, check the<br />following:<br /> The Apache version is 1.3.0 or newer. To check the version, type the<br />following at the command line:<br />httpd &#8211;v<br />You may have to be in the directory where httpd is located before the<br />command will work.<br />Because of security issues with Apache, it is much better to use Apache<br />1.3.27 or newer.<br />PHP with Apache 2 is still considered experimental. For use on production<br />Web sites, it’s better to use Apache 1.3 than Apache 2.<br /> The Apache module mod_so is installed. It usually is. To display a list of<br />all the modules, type the following:<br />httpd –l.<br />You may have to be in the directory where httpd is located before the<br />command will work. The output usually shows a long list of modules. All<br />you need to be concerned with for PHP is mod_so. If mod_so is not loaded,<br />Apache must be reinstalled using the option enable-module=so.<br /> The apxs utility is installed. (Or apxs2 for use with Apache 2.) apxs<br />is often installed when Apache is installed. To determine whether it’s<br />installed on your computer, you should look for a file called apxs, possibly<br />at /usr/sbin/apxs. If you can find the file apxs, it’s installed; if not,<br />it’s not. If Apache was installed on Linux from an RPM, apxs may not have<br />been installed. Some RPMs for Apache consist of two RPMs: one for the<br />basic Apache server and one for Apache development tools. Possibly<br />the RPM with the development tools, which installs apxs, needs to be<br />installed.<br />334 Part VI: Appendixes<br />Installing on Unix/Linux<br />To install PHP 5 on Unix/Linux, follow these steps:<br />1. Point your Web browser to www.php.net, which is the PHP home page.<br />2. Click Downloads.<br />3. Click the latest version of the PHP source code, which is version 5.0.0<br />as of this writing.<br />A dialog box opens.<br />4. Select the option to save the file.<br />A dialog box opens that lets you select where the file is to be saved.<br />5. Navigate to where you want to save the source code (for example,<br />/usr/src). Then click Save.<br />6. After the download, change to the download directory (for example,<br />cd-/usr/src).<br />You see a file named php-, followed by the version name and tar.gz.<br />This file is called a tarball because it contains many files compressed<br />into one file using the tar command.<br />7. Unpack the tarball.<br />The command to unpack the tarball for PHP version 5.0.0 is the following:<br />gunzip -c php-5.0.0.tar.gz | tar -xf –<br />A new directory called php-5.0.0 is created with several subdirectories.<br />8. Change to the new directory that was created when you unpacked the<br />tarball.<br />For example, you can use a command like the following:<br />cd php-5.0.0<br />9. Type the configure command:<br />The configure command consists of ./configure followed by all the<br />necessary options. If you are installing PHP for use with Apache, use the<br />following configure command:<br />./configure &#8211;with-apxs<br />You will see many lines of output. Wait until the configure command<br />has completed. This may take a few minutes.<br />If the apxs utility is not installed in the expected location, you see an error<br />message, indicating that apxs could not be found. If you get this message,<br />check the location where apxs is installed (find / -name apxs)<br />and then include this path in the with-apxs option of the configure<br />command: —with-apxs=/usr/sbin/apxs.<br />335 Appendix A: Installing PHP<br />If you decide to use Apache 2, you need to use apxs2.<br />You may need to use many other options, such as options for the database<br />that you’re using or options that change the directories where<br />PHP is installed. These configure options are discussed in the section,<br />“Installation Options for Unix/Linux/Mac,” later in this Appendix.<br />10. Type make.<br />You will see many lines of output. Wait until it is finished. This may take<br />a few minutes.<br />By default, both the CLI and CGI versions of PHP are built. The file<br />libphp5.so is built for use with Apache. PHP CLI is named php and is<br />located in the directory where php is intalled (e.g. user/local/php).<br />If you don’t want both versions, you can disable one or the other with a<br />configure option, as described in the section, “Installation Options for<br />Unix/Linux/Mac,” later in this chapter.<br />11. Type make install.<br />The files are moved to the correct locations. For instance, the Web<br />version of PHP is installed in the directory where Apache is installed<br />(e.g. /usr/local/apache/libexec/libphp5.so).<br />Alternative method for installing<br />with Apache<br />Occasionally, you can’t install PHP using apxs. This section provides an alternative<br />method of installation for situations in which apxs isn’t available or<br />refuses to work. The preceding installation method is easier and usually works<br />fine. This section is just here to provide an alternative in case the first section<br />fails you. Follow these steps:<br />1. Point your Web browser to www.php.net, which is the PHP home page.<br />2. Click Downloads.<br />3. Click the latest version of the PHP source code — version 5.0.0 as of<br />this writing.<br />A dialog box opens.<br />4. Select the option to save the file.<br />A dialog box opens that lets you select where the file is to be saved.<br />5. Navigate to where you want to save the source code (for example,<br />/usr/src/php), and then click Save.<br />6. After the download is complete, change to the download directory<br />(for example, cd-/usr/src/php).<br />336 Part VI: Appendixes<br />You see a file named php-, followed by the version number and tar.gz.<br />This type of file is called a tarball.<br />7. Unpack the tarball.<br />The command to unpack the tarball for the current PHP version 5.0.0 is<br />as follows:<br />gunzip -c php-5.0.0.tar.gz | tar -xf –<br />A new directory called php-5.0.0 is created with several subdirectories.<br />8. Repeat Steps 1 through 5, but this time, download the Apache source<br />code into the directory where the PHP source code was unpacked.<br />You can find the Apache source code at httpd.apache.org.<br />For the rest of this example, I use the current version, 1.3.27. By the time<br />you read this, a later version may be available.<br />As of this writing, using PHP with Apache 2 is not recommended for a<br />production Web site. Check the PHP Web site before downloading to<br />see whether the recommendation has changed about using PHP with<br />Apache 2.<br />9. Unpack the Apache tarball. For the current version, the command is<br />as follows:<br />gunzip -c apache_1.3.27.tar.gz | tar -xf –<br />Now there are two directories: php-5.0.0 and apache_1.3.27. Each<br />has several subdirectories.<br />10. Type cd apache_1.3.27.<br />11. Type ./configure.<br />The options do not matter for this command. This is a preliminary configuration<br />of Apache that should be done before you configure PHP. The<br />Apache configure will be run again in a later step with the appropriate<br />options. Wait until the configure has completed. This may take a while.<br />12. Type cd ../php-5.0.0.<br />13. Type the following:<br />./configure &#8211;with-apache=../apache_1.3.27<br />If you need to type the configure command on two lines, type a \ at<br />the end of the first line.<br />You may need to use many other options, such as options for the database<br />that you are using or options that change the directories where<br />PHP is installed. The configure options are discussed in the section,<br />“Installation Options,” later in this Appendix.<br />14. Type make.<br />You see many lines of output. You will be informed when it is finished<br />running. It may take some time.<br />337 Appendix A: Installing PHP<br />15. Type make install.<br />This finishes quickly.<br />16. Type cd ../apache_1.3.27 to return to the Apache directory tree.<br />17. Type the following command to configure Apache again:<br />./configure &#8211;prefix=/www<br />&#8211;activate-module=src/modules/php5/libphp5.a<br />You can type this command on one line. If you type it on two lines, type<br />a \ at the end of the first line. Be sure there is at least one space between<br />the end of one option and the beginning of the next.<br />18. Type make.<br />You see many lines of output. You will be informed when it is finished<br />running. It may take some time.<br />The final step depends on whether Apache is already installed on your<br />system or whether this is the first installation of Apache.<br />19. For a first installation of Apache, type make install.<br />If Apache is currently installed and running, do the following:<br />a. Shut down Apache.<br />You can stop the Apache Web server by running a script that was<br />installed on your system during installation. This script is usually<br />called apachectl. It may be located in the bin directory in the<br />directory where Apache was installed — for example, /usr/local/<br />apache/bin or in /sbin or in /usr/sbin. You also may be able to<br />find it in the directory on your system where startup scripts are<br />located — for example, /etc/rc.d/init.d. If you find the script,<br />you can stop the server by typing the name of the script, followed<br />by stop, for example: apachectl stop. You may need to be in the<br />directory with the script in order to run it.<br />b. Find the new file named httpd that you just created in Step 18.<br />This file will be somewhere under the apache directory tree that<br />you just created — for example, /usr/src/php/apache_1.3.27/<br />bin/httpd.<br />c. Find the existing file named httpd.<br />This file will be somewhere on your disk, possibly in<br />/usr/local/apache/bin or /sbin or /usr/sbin.<br />d. Copy the new file named httpd over the old one — that is,<br />replace the old one with the new one.<br />You may want to make a backup copy of the old one before you copy<br />over it.<br />338 Part VI: Appendixes<br />If you decide to upgrade PHP to a newer version, you must use this<br />installation method. You can’t use this method to install now; you’ll need<br />it next time.<br />Installing PHP on Computers<br />Running Mac OS X<br />With the release of PHP 4.3, you can install PHP on Mac OS X as easily as on<br />Unix/Linux. You can install PHP as a partner with Apache (for use in Web<br />pages) or as a stand-alone interpreter. If you want to use PHP for both Web<br />sites and as a stand-alone language, you need to install PHP with Apache and<br />PHP CLI, which are two separate types of PHP. The instructions below include<br />information for both types of PHP installations: PHP for the Web and PHP CLI.<br />You install PHP by downloading source files, compiling the source files, and<br />installing the compiled programs. This process isn’t as technical and daunting<br />as it may appear. I provide step-by-step instructions in the next few sections.<br />Read all the way through the steps before you begin the installation procedure<br />to be sure that you understand it all clearly and have everything prepared so<br />you don’t have to stop in the middle of the installation.<br />Before installing on Mac<br />If you want to use PHP with Apache for your Web site, Apache must be<br />installed. Most Mac OS X systems come with Apache already installed. Before<br />beginning to install PHP, check the following:<br /> The Apache version is 1.3.0 or newer: To check the version, type the<br />following on the command line:<br />httpd &#8211;v<br />You may have to be in the directory where httpd is located before the<br />command will work.<br />Because of security issues with Apache, it is much better to use Apache<br />1.3.27 or newer.<br />PHP with Apache 2 is still considered experimental. For use on production<br />Web sites, it’s better to use Apache 1.3 than Apache 2.<br /> The Apache module mod_so is installed. It usually is. To display a list of<br />all the modules, type the following:<br />httpd –l.<br />You may have to be in the directory where httpd is located before the<br />command will work. The output usually shows a long list of modules. All<br />339 Appendix A: Installing PHP<br />you need to be concerned with for PHP is mod_so. If mod_so is not loaded,<br />Apache must be reinstalled with the &#8211;enable-module=so option.<br /> The apxs utility is installed. apxs often is installed when Apache is<br />installed. To determine whether it’s installed on your computer, you<br />should look for a file called apxs, usually in the /usr/sbin/apxs directory.<br />If you can find the file apxs, it’s installed; if not, it’s not.<br />.  The files from the Developer’s Tools CD are installed. This CD is supplemental<br />to the main Mac OS X distribution. If you can’t find the CD,<br />you can download the tools from the Apple Developer Web Site at<br />developer.apple.com/tools/macosxtools.html.<br />Installing on Mac<br />To install PHP on Mac, follow these steps:<br />1. Point your Web browser to www.php.net, which is the PHP home page.<br />2. Click Downloads.<br />3. Click the latest version of the PHP source code, which is version 5.0.0<br />as of this writing.<br />A dialog box opens.<br />4. Select the option to save the file.<br />A dialog box opens that lets you select where the file is to be saved.<br />5. Navigate to where you want to save the source code (for example,<br />/usr/src), and then click Save.<br />6. After the download, change to the download directory (for example,<br />cd-/usr/src).<br />You see a file named php-, followed by the version name and tar.gz.<br />This file is called a tarball. The file may have been unpacked by the Stuffit<br />Expander automatically so that you see the directory php-5.0.0. If so,<br />skip to Step 8.<br />7. Unpack the tarball.<br />The command to unpack the tarball for PHP version 5.0.0 is the following:<br />tar xvfz php-5.0.0.tar.gz<br />A new directory called php-5.0.0 is created with several subdirectories.<br />8. Change to the new directory that was created when you unpacked the<br />tarball.<br />For example, you can use a command like the following:<br />cd php-5.0.0<br />340 Part VI: Appendixes<br />9. Type the configure command:<br />The configure command consists of ./configure followed by all the<br />necessary options. The minimum set of options are as follows:<br />• Location options: Because the Mac stores files in different locations<br />than the PHP default locations, you need to tell PHP where files are<br />located. Use the following options:<br />&#8211;prefix=/usr<br />&#8211;sysconfdir=/etc<br />&#8211;localstatedir=/var<br />&#8211;mandir=/usr/share/man<br />• zlib option: —with-zlib<br />• Apache option: If you are installing PHP for use with Apache, use<br />the following option: —with-apxs.<br />Therefore, the most likely configuration command that you should use is<br />./configure &#8211;prefix=/usr &#8211;sysconfdir=/etc<br />&#8211;localstatedir=/var &#8211;mandir=/usr/share/man<br />&#8211;with-apxs –with-zlib<br />You can type the configure command on one line. If you use more than<br />one line, type a \ at the end of each line.<br />You will see many lines of output. Wait until the configure command<br />has completed. This may take a few minutes.<br />If the apxs utility is not installed in the expected location, you will see<br />an error message, indicating that apxs could not be found. If you get this<br />message, check the location where apxs is installed (find / -name<br />apxs) and include the path in the with-apxs option of the configure<br />command: —with-apxs=/usr/sbin/apxs.<br />If you decide to use Apache 2, you need to use apxs2.<br />You may need to use many other options, such as options for the database<br />that you’re using or options that change the directories where<br />PHP is installed. These configure options are discussed in the section,<br />“Installation Options for Unix/Linux/Mac,” later in this Appendix.<br />10. Type make.<br />You will see many lines of output. Wait until it is finished. This may take<br />a few minutes.<br />By default, both the CLI and CGI versions of PHP are built. The file<br />libphp5.so is built for use with Apache. PHP CLI is named php and is<br />located in the directory where php is intalled (such as user/local/php).<br />If you don’t want both versions, you can disable one or the other with a<br />configure option, as described in the section, “Installation Options for<br />Unix/Linux/Mac,” later in this chapter.<br />11. Type sudo make install.<br />341 Appendix A: Installing PHP<br />Installation Options for Unix/Linux/Mac<br />The previous sections give you steps to quickly install PHP. However, PHP<br />can be installed with many options, and you may want to use some of these<br />options during installation. For example, you may want to install PHP with<br />support for the database that you plan to use, such as MySQL or Oracle. Or,<br />all the PHP programs and files are installed in their default locations, but you<br />need to install PHP in different locations. Or you may be planning applications<br />using additional software.<br />You can use additional command line options if you need to configure PHP for<br />your specific needs. Just add the options to the configure command shown in<br />Step 13 of the Linux/Unix installation instructions or Step 9 of the Mac installation<br />instructions. In general, the order of the options in the command line<br />doesn’t matter. Table A-1 shows the most commonly used options for PHP.<br />To see a list of all possible options, type configure –help in the directory<br />where PHP is installed.<br />Table A-1 PHP Configure Options<br />Option Tells PHP To . . .<br />prefix=PREFIX Set main PHP directory to PREFIX. Default PREFIX<br />is /usr/local.<br />infodir=DIR Install info documentation in DIR. Default is<br />PREFIX/info.<br />mandir=DIR Install man files in DIR. Default is PREFIX/man.<br />with-config-file- Look for the configuration file (php.ini) in DIR.<br />path=DIR Without this option, PHP looks for the configuration<br />file in a default location, usually /usr/local/lib.<br />disable-cgi Don’t build the PHP CGI binary program.<br />disable-cli Don’t build the PHP CLI binary program.<br />disable-libxml Disables XML support.<br />enable-debugger Enable support for internal debugger.<br />enable-ftp Enable FTP support.<br />enable-magic-quotes Enable automatic escaping of quotes with a backslash.<br />enable-url-includes Allow the include() function to get files from HTTP<br />and FTP locations, as well as from the include<br />directory.<br />342 Part VI: Appendixes<br />Option Tells PHP To . . .<br />with-msql=DIR Enable support for mSQL databases. Default DIR<br />where mSQL is located is /usr/local/Hughes.<br />with-mysql=DIR Enable support for MySQL 4.0 or earlier databases.<br />Default DIR where MySQL is located is /usr/local.<br />with-mysqli=DIR Enable support for MySQL 4.1 or later databases. No<br />default. DIR must be the path to the file mysql_<br />config that is installed with MySQL 4.1 or greater.<br />Do not enable both mysql and mysqli.<br />with-openssl=DIR Enable OpenSSL support for a secure server.<br />Requires OpenSSL version 0.9.5 or later.<br />with-oracle=DIR Enable support for Oracle. Default DIR is contained<br />in the environmental variable, ORACLE_HOME.<br />with-pgsql=DIR Enable support for PostgreSQL databases. Default<br />DIR where PostgreSQL is located is /usr/local/<br />pgsql.<br />with-servlet=DIR Include servlet support. DIR is the base install directory<br />for the JSDK. The Java extension must be built as<br />a shared dll.<br />with-xml Enable XML support.<br />Configuring on Unix/Linux/Mac<br />PHP has configuration settings that allow you to change some of its behavior.<br />The configuration settings are read by PHP at startup from a file called<br />php.ini. The default location where php.ini should be located is /usr/<br />local/lib/php.ini. However, you can change this default location by using<br />an installation option, as I describe in the previous section. If PHP doesn’t<br />find the php.ini file in the expected directory, default settings are used.<br />You may have to copy the php.ini file to the correct location. The default<br />file is in the php directory called php.ini-dist. Copy it by using the following<br />command:<br />cp php.ini-dist /usr/local/lib/php.ini<br />On the Mac, use the following:<br />sudo cp php.ini-dist /usr/local/lib/php.ini<br />343 Appendix A: Installing PHP<br />You can edit php.ini to change the settings for PHP. In general, the defaults<br />are okay. PHP settings are discussed throughout the book when the settings<br />are relevant to PHP features. For example, you can change the settings in<br />php.ini to control how PHP handles and displays error messages. The error<br />handling settings are discussed in Chapter 4 when PHP error handling is<br />discussed.<br />If you’re using PHP with Apache, you must configure Apache to recognize<br />PHP files. To configure Apache, follow the steps below:<br />1. Locate the Apache configuration file, called httpd.conf.<br />It is on your system, possibly in /etc or in /usr/local/apache/conf.<br />On Mac, it is probably located in /etc/httpd. You must edit this file<br />before PHP can run properly.<br />2. Add a line to the file that tells Apache to load the PHP module.<br />Find the list of LoadModule statements. You load the PHP module with<br />the line:<br />LoadModule php5_module libexec/libphp5.so<br />Check to be sure that this line is there. If it is not there, add it. If it is<br />there with a pound sign (#) at the beginning of the line, remove the<br />pound sign.<br />3. Add a line to the file that tells Apache which files may contain<br />PHP code.<br />Look for a section describing AddType. You may see one or more AddType<br />lines for other software. The AddType line for PHP is<br />AddType application/x-httpd-php .php<br />Look for this line. If you find it with a pound sign (#) at the beginning of<br />the line, remove the pound sign (#). If you don’t find this line, add it to<br />the list of AddType statements. This line tells Apache to look for PHP<br />code in all files with a .php extension. You can specify any extension or<br />series of extensions. On Mac, add this line to the bottom of the file.<br />4. Mac only: If you have been previously running the PHP that came<br />with the Mac, you need to comment out the following lines.<br />LoadModule hfs_apple_module<br />libexec/httpd/mod_hfs_apple.so<br />AddModule mod_hfs_apple.c<br />Just add a # at the beginning of each line to make the lines inactive.<br />5. Start (if it’s not running) or restart (if it is running) the Apache httpd<br />server.<br />You can start or restart the server by using a script that was installed<br />on your system during installation. This script may be apachectl or<br />httpd.apache, and it may be located in /bin or in /usr/local/<br />apache/bin. For example, if the script is called apachectl, you can start<br />344 Part VI: Appendixes<br />the server by typing apachectl start, restart it by using apachectl<br />restart, or stop it by using apachectl stop. On Mac, type sudo<br />apachectl restart. Sometimes restarting Apache doesn’t change your<br />PHP settings; if your settings didn’t change, you must stop the server<br />first and then start it again. In addition, your computer is undoubtedly<br />set up so that Apache starts whenever the computer starts. Therefore, if<br />you’re having trouble, you can always shut down and then start your<br />computer to restart Apache.<br />Whenever you change any of the settings in php.ini, you may have to<br />restart Apache before the changes go into effect.<br />Installing PHP on Computers<br />Running Windows<br />PHP runs on Windows 98/Me (although it’s not recommended) and Windows<br />NT/2000/XP. You can use PHP with your Web server for your Web site (PHP<br />CGI) or you can use PHP as an independent stand-alone scripting language<br />(PHP CLI). The two types of PHP require different executable files. You can<br />install either or both types of PHP software.<br />There are two ways to install PHP — using the Windows Installer or manually<br />from a Windows .zip file. Which one you use depends on what you are<br />planning to use PHP for. Use the following guidelines to choose a method of<br />installation:<br /> Windows Installer: Installs PHP CGI only. Includes built-in support for a<br />selected set of popular functions. This installation includes support for<br />ODBC, which is a method of interacting with some databases, such as<br />MS Access, and for SQLite, a quick easy way to store data in flat files.<br />(See Chapter 12 for a discussion of database use with PHP.) Support is<br />also included for XML, FTP, and COM. PHP CLI is not installed using this<br />method.<br />You can use this simpler, faster installation method as long as the following<br />criteria are met:<br />• You are using PHP with your Web site and don’t need to use PHP<br />CLI independently.<br />• You are using PHP for simple HTML or to process forms.<br />• You are not using a database or, if you are using a database, you<br />are using ODBC for your database interaction.<br />• You are using only the built-in functionality.<br /> Manual installation: All the required files are bundled into a Windows<br />.zip file. You download the .zip file, unzip it, and place the needed files<br />into the correct locations manually.<br />345 Appendix A: Installing PHP<br />PHP includes a lot more functionality than is automatically installed by<br />the installer. If you need to use any of that functionality, then you need to<br />use the manual installation method. For example, if you need to use PHP<br />CLI or if you need to interact with a database other than by using ODBC,<br />you need to install manually. In addition to the built-in functionality of<br />PHP, extensions are available with a great deal of added functionality. If<br />you want to use any of this additional functionality, the necessary files<br />are included in the Windows .zip file. For more discussion of extensions<br />and how to install them, see Chapter 14.<br />Installing PHP CGI with the PHP installer<br />The following steps install PHP on a Windows computer for use on your Web<br />site but do not install PHP CLI:<br />1. Point your Web browser at www.php.net.<br />2. Click Download.<br />3. Go to the Windows Binaries section. Click the download link for the<br />installer for the most recent version of PHP (as of this writing, 5.0.0).<br />4. Click the link for a mirror Web site from which to download the file,<br />and then choose the site closest to your location.<br />A dialog box opens.<br />5. Select the option to save the file.<br />A dialog box opens that lets you select where the file is to be saved.<br />6. Navigate to where you want the file to be downloaded. Then click Save.<br />After the download is complete, you see a file in the download location<br />containing all the files needed. The file is named php, followed by the<br />version number and -installer.exe. For the current version, the file is<br />named php500-installer.exe.<br />7. If you’re not using IIS or PWS for your Web server and you currently<br />have your Web server running, shut it down.<br />8. Navigate to the directory where you downloaded PHP and doubleclick<br />php500-installer.exe.<br />The installer software starts with the screen shown in Figure A-1.<br />9. Click Next.<br />The license is displayed.<br />10. Click I Agree to continue.<br />You see a screen in which you can choose the type of installation.<br />346 Part VI: Appendixes<br />11. Select Standard and then click Next.<br />You see a screen showing the directory where PHP is to be installed.<br />12. If you want to install PHP in the default directory, c:\php, click<br />Next. If you want to install PHP in a different directory, click Browse,<br />select a directory, and click OK; then click Next.<br />You see a mail configuration screen.<br />13. The mail screen has two fields to collect information for use when you<br />send e-mail from a PHP script. If you plan to send email and know the<br />address of your SMTP server or the From address you want to use in<br />your e-mail, enter them now. If you don’t know this information, just<br />leave the defaults selected.<br />If you need to, you can change this later by editing the PHP configuration<br />file.<br />14. Click Next<br />You see the screen shown in Figure A-2. It shows a list of Web servers<br />that PHP can be installed with.<br />15. Select the server that you’re using. If the server that you’re using is<br />not listed, select None.<br />16. Click Next.<br />You see the Ready screen. The installer is now ready to install.<br />17. Click Next to start the installation.<br />You see a confirmation message after PHP 5.0.0 has been installed. Any<br />information that you need is be displayed, such as whether you need to<br />reboot or restart your server. For example, when I selected Apache, I<br />saw the screen in Figure A-3.<br />Figure A-1:<br />The opening<br />screen of<br />the PHP<br />installer.<br />347 Appendix A: Installing PHP<br />This message doesn’t mean that Apache was not installed. It just means<br />that it wasn’t automatically configured, so I have to configure it myself,<br />as described in the configuration section later in this Appendix. Perhaps<br />by the time that you install PHP, the configuration for Apache will also<br />be an automated process, saving you the trouble.<br />Installing PHP manually<br />To install PHP5 manually on Windows, you must first download a zip file that<br />contains all the necessary files for PHP. The following steps show how to<br />install PHP on Windows.<br />1. Point your Web browser at www.php.net.<br />2. Click Download.<br />3. Go to the Windows Binaries section. Click the download link for the zip<br />package for the most recent version of PHP (as of this writing, 5.0.0).<br />If you are familiar with .bz format files and know how to uncompress<br />them, download the .bz file. It’s smaller and faster to download, but not<br />all software can uncompress it.<br />Figure A-3:<br />An installer<br />message<br />about<br />Apache.<br />Figure A-2:<br />The Server<br />Type screen<br />in the PHP<br />installer<br />program.<br />348 Part VI: Appendixes<br />4. Click the link for a mirror Web site from which to download the file,<br />and choose the site closest to your location.<br />A dialog box opens.<br />5. Select the option to save the file.<br />A dialog box opens that lets you select where the file is to be saved.<br />6. Navigate to where you want the file to be downloaded. Then click Save.<br />After the download is complete, you see a file in the download location<br />containing all the files needed. The file is named php, followed by the version<br />number and -win32.zip. For the current version, the file is named<br />php5.0.0-win32.zip.<br />7. Extract the files from the .zip file into the directory where you want<br />PHP to be installed, such as c:\php.<br />If you double click the .zip file, it should open in the software on your<br />computer that extracts files from .zip files, such as WinZip or PKzip.<br />Select the menu item for extract and select the directory into which the<br />files are to be extracted.<br />When you extract all files from the .zip file, it may put the contents into<br />a file called php-5.0.0-win32. If so, you can just rename it to something<br />more reasonable. For example, you can extract the directory into c:\<br />and then rename it to php, so your installation is in c:\php. c:\php is a<br />good choice for installation because many configuration files assume<br />that’s where PHP is installed, so the default settings are more likely to be<br />correct.<br />It’s best not to install PHP in a directory with a space in the path, such<br />as in Program Files/PHP. It sometimes causes problems.<br />You now have a directory with several subdirectories that contain the<br />files that you need.<br />8. Copy PHP CLI into the directory where you intend to run it. It is currently<br />located in the directory where PHP is installed and is named<br />php.exe. You can run it from this directory if you want to.<br />Configuring PHP and your Web<br />server on Windows computers<br />PHP uses a configuration file that you can edit to change some of the behavior<br />of PHP. In addition, if you are using PHP for your Web site, you need to<br />configure your Web server as well.<br />Configuring PHP on Windows<br />PHP uses settings in a file named php.ini to control some of its behavior.<br />PHP looks for php.ini when it begins and uses the settings that it finds.<br />349 Appendix A: Installing PHP<br />If you used the Windows Installer, a default php.ini file was installed. If you<br />installed manually, you need to install the php.ini file yourself. A default<br />configuration file php.ini-dist is located in the directory where PHP was<br />installed. Copy this file into one of the following directories, giving it the<br />name php.ini:<br /> Windows 98/Me/XP: windows<br /> Windows NT/2000: winnt<br />If you have a previous version of PHP installed (such as PHP 4.3), make a<br />backup copy of the php.ini file before you overwrite it with the new one<br />for PHP5. You can then see the settings you are currently using and change<br />the settings in the new php.ini file where needed.<br />If you’re using PHP with the IIS Web server, you need to change one of the<br />default settings. Open the php.ini file in the windows or winnt directory.<br />Find the line:<br />; cgi.force_redirect = 1<br />This setting needs to be changed to 0. Also, the above setting has a semicolon<br />at the beginning of the line, which comments the line so that it isn’t active.<br />For IIS, you need to use the following line.<br />cgi.force_redirect = 0<br />In general, the default settings allow PHP to run okay (with the exception<br />described in the previous paragraph), but you may need to edit some of the<br />settings for specific reasons. I discuss settings in the php.ini file throughout<br />the book when I am discussing a topic that may require you to change settings.<br />For example, PHP error handling actions can be changed by settings in the<br />php.ini file. The possible settings and their effects are discussed in Chapter 4.<br />Configuring your Web server for PHP<br />Your Web server needs to be configured to recognize PHP files. If you<br />installed with the Windows Installer and your Web server is IIS or PWS, it was<br />automatically configured during the installation procedure (except for IIS 6).<br />If your Web server is Apache or if you used the manual installation procedure,<br />you need to do the configuration yourself.<br />Configuring Apache<br />To configure Apache to use PHP, follow these steps:<br />1. You configure Apache by editing a file called httpd.conf.<br />You may be able to edit it by choosing Start➪Programs➪Apache HTTP<br />Server➪Configure Apache Server➪Edit Configuration.<br />350 Part VI: Appendixes<br />If you can’t find a menu item at the above location, find the httpd.conf<br />file on your hard disk, usually in the directory where Apache is installed,<br />in a subdirectory called conf (for example, c:\program files\Apache<br />group\Apache\conf). Open this file in an editor, such as Notepad or<br />WordPad.<br />2. Your httpd.conf file must instruct Apache to send PHP code to the<br />PHP program. Two statements work together to do this:<br />• ScriptAlias: A ScriptAlias statement is used to set up a name<br />for the directory where PHP is installed. Look for ScriptAlias<br />statements in the httpd.conf file. You may see some for other<br />software. If you do not see one for PHP, add the following:<br />ScriptAlias /php/ “c:/php/”<br />The first argument is the name, and the second argument is what<br />it represents. In this statement, the name /php/ is used to mean<br />c:/php/.<br />• Action: An Action statement is used to tell Apache where to<br />find PHP. If you don’t find an Action statement for PHP, add the<br />following:<br />Action application/x-httpd-php /php/php-cgi.exe<br />Notice that the Action statement uses the name defined in the<br />ScriptAlias statement. It locates php-cgi.exe in /php/, which<br />means c:/php/. If you change the ScriptAlias statement to say<br />c:/php27/, the Action statement would then look for php-cgi.<br />exe in c:/php27.<br />It’s better to use forward slashes. Apache can find the location on<br />Windows okay.<br />3. You need to tell Apache which files may contain PHP code.<br />In the httpd.conf file, look for a section describing AddType. This section<br />may contain one or more AddType lines for other software. The<br />AddType line for PHP is<br />AddType application/x-httpd-php .php<br />Look for this line. If you find it with a pound sign (#) at the beginning of<br />the line, remove the pound sign. If you don’t find the line, add it to the<br />list of AddType statements. This line tells Apache to look for PHP code in<br />all files with a .php extension. You can specify any extension or series of<br />extensions.<br />4. Start (if it’s not running) or restart (if it is running) Apache.<br />You can start it as a service on Windows NT/2000/XP by choosing Start➪<br />Programs➪Apache HTTP Server➪Control Apache Server.<br />Or you can start it on Windows 98/Me by choosing Start➪Programs➪<br />Apache Web Server➪Management.<br />351 Appendix A: Installing PHP<br />Sometimes restarting Apache doesn’t change the settings; if your settings<br />didn’t change, you must stop it first and then start it. In addition,<br />your computer is undoubtedly set up so that Apache starts whenever<br />the computer starts. Therefore, if you’re having trouble, you can always<br />shut down and then start your computer to restart Apache.<br />Configuring IIS manually<br />If you installed PHP with the Windows Installer and are using IIS 5 or before,<br />IIS was automatically installed. However, if you installed PHP manually, you<br />need to configure IIS. In addition, if you installed PHP with Windows Installer<br />and are using IIS 6/Windows Server 2003, IIS was not totally configured, so<br />you need to perform the steps in this section.<br />To configure IIS to work with PHP, follow these steps:<br />1. Enter the IIS Management Console.<br />You should be able to enter by choosing Start➪Programs➪<br />Administrative Tools➪Internet Services Manager or Start➪Settings➪<br />Control Panel➪Administrative Tools➪Internet Services Manager.<br />2. Right-click your Web site (such as Default Web Site).<br />3. Select Properties.<br />4. Select the Home Directory tab.<br />5. Click the Configuration button.<br />6. Choose the App Mappings tab.<br />7. Click Add.<br />8. In the Executable box, type the path to the PHP interpreter: for example,<br />c:\php\php-cgi.exe.<br />9. In the extension box, type .php.<br />This will be the extension that is associated with PHP scripts.<br />10. Select the Script Engine check box.<br />11. Click OK.<br />Repeat Steps 6–10 if you want any additional extensions in addition to .php<br />to be processed by PHP, such as .phtml.<br />352 Part VI: Appendixes<br />Appendix B<br />Useful PHP Built-in Functions<br />PHP is as powerful as it is because of its many functions. This Appendix<br />is a reference to the most useful functions.<br />Some of the functions are discussed at various places in the book; some are<br />not. If the function is discussed in the book, its definition includes a chapter<br />reference where a more complete description can be found.<br />Array Functions<br />This section describes built-in functions that work with arrays.<br />array<br />Creates a new array. (See Chapter 6.)<br />Format: $array = array(key=&gt;value,key=&gt;value,key=&gt;value,&#8230;);<br />array_count_values<br />Creates an array that contains a count of the values in the original array.<br />Format: $array_out = array_count_values($orig_array);<br />For example, suppose that $orig_array contained the following:<br />$orig_array[a] = John<br />$orig_array[b] = Mary<br />$orig_array[c] = John<br />$orig-Array[d] = Jose<br />Then $array_out would contain the following:<br />$array[John] = 2<br />$array[Mary} = 1<br />$array[Jose] = 1<br />array_diff<br />Returns $array_out with elements from $array1 that are not present in any<br />other of the specified arrays ($array2, $array3, and so on). (See Chapter 6.)<br />Format: $array_out = array_diff($array1,$array2,$array3 . . .);<br />array_intersect<br />Creates an array that contains the elements that are the same (rather than<br />different) in two or more arrays. (See Chapter 6.)<br />Format: $simArray = array_intersect($array1,$array2, . . .);<br />array_keys<br />Creates an array containing all the keys in the $orig_array. If search_key is<br />included, only keys that match search_key are in the new array.<br />Format: $array_out = array_keys($orig_array,”search_key”);<br />For example, suppose that $orig_array contained the following:<br />$orig_array[a] = CA<br />$orig_array[b] = OR<br />$orig_array[c] = TX<br />Then $array_out would contain the following:<br />$array_out[0] = a<br />$array_out[1] = b<br />$array_out[2] = c<br />Suppose that search_key= OR, as in the following:<br />$array_out = array_keys($orig_array,”OR”);<br />Then $array_out would contain the following:<br />$array_out[0] = b<br />array_merge<br />Merges two or more arrays together. If more than one element has the same<br />non-numeric key, only the last value for the key is added to the output array.<br />(See Chapter 6.)<br />Format: $bigArray = array_merge($array1,$array2, . . .);<br />354 Part VI: Appendixes<br />array_merge_recursive<br />Merges two or more arrays. If more than one element has the same nonnumeric<br />key, an array with all the values for the key is added to the output<br />array. (See Chapter 6.)<br />Format: $bigArray = array_merge($array1,$array2, . . .);<br />array_pop<br />Removes and returns the last element in an array.<br />Format: $element = array_pop($orig_array);<br />array_push<br />Adds the specified element(s) to the end of the array. Returns the new size of<br />the array.<br />Format: $new_size = array_push($orig_array,”el1”,”el2”,”el3”);<br />array_reverse<br />Reverses the order of the items in $orig_array.<br />Format: $array_out = array_reverse($orig_array);<br />array_search<br />Searches an array for a value. If value is found, key is returned.<br />Format: $key = $array_search(“value”,$orig_array);<br />array_slice<br />Creates a new array that contains a subset of an existing array. Puts number<br />of elements, beginning with start, into $subArray. (See Chapter 6.)<br />Format: $subArray = array_slice($orig_array,start,number);<br />array_sum<br />Adds all the values in an array. (See Chapter 6.)<br />Format: $sum = array_sum($orig_array);<br />array_unique<br />Removes duplicate elements from an array. (See Chapter 6.)<br />Format: $array_out = array_unique($orig_array);<br />355 Appendix B: Useful PHP Built-in Functions<br />arsort<br />Sorts an array by value in reverse order. (See Chapter 6.)<br />Format: arsort($orig_array);<br />asort<br />Sorts an array by value, keeping the original keys. (See Chapter 6.)<br />Format: asort($orig_array);<br />compact<br />Creates an array from the specified variables ($var1, $var2, and so on). The<br />variables can be strings or arrays.<br />Format: $array_out = compact($var1, $var2, . . .);<br />count<br />Returns the number of elements in the array. (See Chapter 6.)<br />Format: $size = count($orig_array);<br />current<br />Returns the value of the array element where the pointer is currently located.<br />(See Chapter 6.)<br />Format: $value = current($array);<br />end<br />Moves the pointer to the last element in an array and returns the value. (See<br />Chapter 6.)<br />Format: $value = end($array);<br />explode<br />Creates an array containing substrings of a string. The specified separator,<br />sep, which is generally something like a comma or a tab, divides the string<br />into substrings. (See Chapter 6.)<br />Format: $array_out = explode(“sep”,$string);<br />extract<br />Creates a set of variables, one for each element of an array. The key for the<br />element is used as the variable name. (See Chapter 6.)<br />Format: extract($array);<br />356 Part VI: Appendixes<br />implode<br />Builds a string containing the values of all the elements in an array, separated<br />by the specified separator. (See Chapter 6.)<br />Format: $string = implode($array,”sep”);<br />in_array<br />Searches through the values in an array for a specified value. Returns TRUE<br />or FALSE.<br />Format: $bool = in_array(“value”,$array);<br />key<br />Returns the key of the array element where the pointer is currently located.<br />Format: $key = key($array);<br />key_exists<br />Checks an array to see whether it contains an element with the specified key.<br />Returns TRUE or FALSE.<br />Format: $bool = key_exists(“key”,$array);<br />ksort, krsort<br />Sorts the array by key. ksort sorts in ascending order, and krsort sorts in<br />reverse (descending) order. (See Chapter 6.)<br />Format: ksort($array); krsort($array);<br />natsort, natcasesort<br />Sorts an array by value in natural order. The order of the results is n1, n2,<br />n12, n25, rather than n1, n12, n2, n25 in the usual sort. The function natcasesort<br />works the same way but is case-insensitive.<br />Format: natsort($array); natcasesort($array);<br />next<br />Moves pointer in array to next element. (See Chapter 6.)<br />Format: next($array);<br />prev<br />Moves pointer in array to previous element. (See Chapter 6.)<br />Format: prev($array);<br />357 Appendix B: Useful PHP Built-in Functions<br />range<br />Sets up an array with elements spanning a range of values. Possible ranges can<br />be numerical (such as 1–10 or 10@nd1) or alphabetical (such as a–m or m–a).<br />Format: $array_out = range(start,end);<br />reset<br />Moves pointer to the first element in an array. (See Chapter 6.)<br />Format: reset($array);<br />sizeof<br />Returns the number of elements in an array. (See Chapter 6.)<br />Format: $size = sizeof($array);<br />sort, rsort<br />Sorts array by value. sort sorts in ascending order, and rsort sorts in<br />reverse (descending) order. (See Chapter 6.)<br />Format: sort($array); rsort($array);<br />Date and Time Functions<br />This sections contains functions that work with date and time values.<br />checkdate<br />Checks whether date is valid. Returns TRUE or FALSE.<br />Format: checkdate(month,day,year);<br />date, gmdate<br />Converts a Unix timestamp into a formatted date. The function gmdate<br />returns Greenwich Mean Time. (See Chapter 5.)<br />Format: $formatted_date = date(“format”,$timestamp);<br />getdate<br />Creates an array from a Unix timestamp, each element containing part of the<br />array, such as seconds, minutes, month, day of the year, and so on.<br />Format: $array_date = getdate($timestamp);<br />358 Part VI: Appendixes<br />localtime<br />Creates an array of values related to your local time, such as seconds, minutes,<br />day of month, and so on.<br />Format: $array_date = localtime($timestamp);<br />microtime<br />Returns time in seconds and microseconds since January 1, 1970.<br />Format: $time_out = microtime();<br />mktime, gmmktime<br />Returns a Unix timestamp. gmmktime uses Greenwich Mean Time. (See<br />Chapter 5.)<br />Format: $timestamp=mktime(“hrs”,”min”,”sec”,”mo”,”da”,”yr”);<br />time<br />Returns the Unix timestamp for the current time. (See Chapter 5.)<br />Format: $timestamp = time();<br />File System Functions<br />This section contains functions for use with your file system.<br />basename<br />Returns the filename from a full path. (See Chapter 13.)<br />Format: $filename = basename(“path”);<br />chdir<br />Change to a different directory. (See Chapter 13.)<br />Format: chdir(“pathtodirectory”);<br />chgrp<br />Changes the group for a file.<br />Format: chgrp(“pathtofile”,”group”);<br />359 Appendix B: Useful PHP Built-in Functions<br />chmod<br />Changes the permissions of the file.<br />Format: chmod(“pathtofile”,”octalnumber”);<br />chown<br />Changes the owner of a file.<br />Format: chown(“pathtofile”,”newowner”);<br />closedir<br />Closes the directory pointed to by the directory handle $dh. (See Chapter 13.)<br />Format: closedir($dh);<br />copy<br />Copies a file, resulting in two copies of the file. (See Chapter 13.)<br />Format: copy(“oldfilename”,”newfilename”);<br />dirname<br />Returns the directory from a path. (See Chapter 13.)<br />Format: $directory_name = dirname(“path”);<br />dis_total_space<br />Returns the number of bytes of total space on the disk.<br />Format: $space = disk_total_space(“path”);<br />disk_free_space<br />Returns the number of bytes of free (unused) space.<br />Format: $free = disk_free_space(“pathtodir”);<br />fclose<br />Closes an open file pointed to by the file handle $fh. (See Chapter 12.)<br />Format: fclose($fh);<br />feof<br />Returns TRUE when the pointer reaches the end of the file. (See Chapter 12.)<br />Format: feof($fh);<br />360 Part VI: Appendixes<br />fgetc<br />Returns one character (the current character) and moves the pointer to the<br />next character in the file.<br />Format: $char = fgetc($fh);<br />fgetcsv<br />Reads a line of no longer than length from a file and returns it as an array,<br />breaking it into elements at the specified separator, sep. (See Chapter 12.)<br />Format: $array_out = fgetcsv($fh,length,”sep”);<br />fgets, fgetss<br />Reads a line from file of no longer than length. Does not return the end-ofline<br />character. fgetss also strips tags from line. (See Chapter 12.)<br />Format: $line = fgets($fh,length); $line=fgetss($fh,length);<br />file<br />Reads a file and returns an array with one line per element. (See Chapter 12.)<br />Format: $array_lines = file($fh);<br />file_exists<br />Checks whether a specific file exists. Returns TRUE or FALSE. (See Chapter 13.)<br />Format: $bool = file_exists(“pathtofile”);<br />fileatime<br />Returns the time that the specified file was last accessed. (See Chapter 13.)<br />Format: $timestamp = fileatime(“pathtofilename”);<br />filectime<br />Returns the time that the specified file was created. (See Chapter 13.)<br />Format: $timestamp = filectime(“pathtofilename”);<br />filemtime<br />Returns the time that the specified file was last modified. (See Chapter 13.)<br />Format: $timestamp = filemtime(“pathtofile”);<br />361 Appendix B: Useful PHP Built-in Functions<br />fileowner<br />Returns the user ID of the owner of the file. (See Chapter 13.)<br />Format: $userID = fileowner(“pathtofile”);<br />fileperms<br />Returns the file permissions for the file.<br />Format: $perms = fileperms(“pathtofile”);<br />filesize<br />Returns the file size in bytes. (See Chapter 13.)<br />Format: $size = filesize(“pathtofile”);<br />filetype<br />Returns the file type, such a file or directory. (See Chapter 13.)<br />Format: $type = filetype(“pathtofile”);<br />flock<br />Locks a file so that no one else can access it until it’s unlocked. (See<br />Chapter 12.)<br />Format: flock($fh,mode);<br />fopen<br />Opens a file and returns a pointer to the specified file. (See Chapter 12.)<br />Format: $fh = fopen(“pathtofile”,”mode”);<br />fputs<br />Writes text to a file. Alias for fwrite. Returns the number of bytes written to<br />the file or FALSE if the function fails. (See Chapter 12.)<br />Format: $result = fputs($fh,”text”,length);<br />fread<br />Reads number of bytes, unless it reaches the end of the file first, from a file.<br />(See Chapter 13.)<br />Format: $file_content = fread($fh,number);<br />362 Part VI: Appendixes<br />fscanf<br />Reads text from a file and returns a formatted string. (See the format and<br />syntax for sprintf in Chapter 13.)<br />Format: $string = fscanf($fh,”format”,$v1,$v2, . . .);<br />fseek<br />Moves the file pointer, depending on the next two parameters. The value<br />specified in num is a number of characters. You can set mode to SEEK_SET<br />(moves to char in position num), SEEK_CUR (moves num characters forward<br />from current position), or SEEK_END (moves num characters back from<br />the last character).<br />Format: fseek($fh,num,mode);<br />fwrite<br />Writes text to the file indicated by $fh, stopping at length. Specifying<br />length is optional. (See Chapter 12.)<br />Format: $bytes_written = fputs($fh,”text”,length);<br />getcwd<br />Returns the path to the current directory.<br />Format: $current_directory = getcwd();<br />getlastmod<br />Returns the last modification date of the current script.<br />Format: $timestamp = getlastmod();<br />is_dir<br />Checks whether the specified path is a directory. (See Chapter 13.)<br />Format: $bool = is_dir(“pathtodir”);<br />is_file<br />Checks whether a specified file is a regular file, rather than a directory or<br />special system file. (See Chapter 13.)<br />Format: $bool = is_file(“pathtofile”);<br />363 Appendix B: Useful PHP Built-in Functions<br />is_readable<br />Checks whether a specified file is readable. (See Chapter 13.)<br />Format: $bool = is_readable(“pathtofile”);<br />is_uploaded_file<br />Checks whether a specified file was uploaded via Web server form.<br />Format: $bool = is_uploaded_file(“pathtofile”);<br />is_writable<br />Checks whether a specified file is writable. (See Chapter 13.)<br />Format: $bool = is_writable(“pathtofile”);<br />link<br />Creates a hard link to path at newpath.<br />Format: link(“path”,”newpath”);<br />mkdir<br />Creates a new directory. The value specified in mode is permissions in octal<br />form.<br />Format: mkdir(“pathtonewdir”,mode);<br />move_uploaded_file<br />Moves a file from its temporary upload directory to a permanent file. (See<br />Chapter 11.)<br />Format: move_uploaded_file(“filename”,”pathtodestination”);<br />opendir<br />Opens a directory. Returns a pointer to the open directory. (See Chapter 13.)<br />Format: $dh = opendir(“pathtodir”);<br />passthru<br />Executes a system command and outputs the result. (See Chapter 13.)<br />Format: passthru(“systemcommand”);<br />364 Part VI: Appendixes<br />pathinfo<br />Creates an array with information about a path. The array contains three elements:<br />dirname, basename, and extension.<br />Format: $array_dir = pathinfo(“pathtodir”);<br />readdir<br />Reads one filename from the open directory. (See Chapter 13.)<br />Format: $filename = readdir($dh);<br />readfile<br />Reads a file and outputs the contents. Can handle a URL.<br />Format: $numberOfBytesRead = readfile(“pathtofile”);<br />rename<br />Renames a file. (See Chapter 13.)<br />Format: rename(“oldfilename”,”newfilename”);<br />rewind<br />Sets a file pointer to beginning of the file referred to by $fh.<br />Format: rewind($fh);<br />rmdir<br />Removes a directory. (See Chapter 13.)<br />Format: rmdir(“pathtodir”);<br />tempnam<br />Generates a unique filename with a specified prefix in the directory.<br />Format: $filename = tempnam(“pathtodir”,”prefix”);<br />tmpfile<br />Creates a temporary file with a unique name, opens it with write privileges,<br />and returns a pointer to the open file.<br />Format: $fh = tmpfile();<br />365 Appendix B: Useful PHP Built-in Functions<br />touch<br />Sets the modification date of a file. If time isn’t specified, it sets the date to<br />the current time. If the file does not exist, it’s created.<br />Format: $bool = touch(“pathtofile”,time);<br />umask<br />Sets the default permissions to mask and returns the previous mask. The previous<br />defaults are restored at the end of the script.<br />Format: $old_mask = umask(mask);<br />unlink<br />Deletes a file. (See Chapter 13.)<br />Format: unlink(“pathtofile”);<br />HTTP and Mail Functions<br />This section contains functions related to HTTP headers and mail functions.<br />get_browser<br />Returns an object containing information about the user’s current browser or<br />about the browser name if specified.<br />Format: $string = get_browser(“name”);<br />get_meta_tags<br />Creates an array, each element of which is a name attribute for any meta tags<br />found in a file.<br />Format: $array_tags = get_meta_tags(“pathtofile”);<br />header<br />Sends an HTTP header to the Web server. (See Chapter 10.)<br />Format: header(“HTTPformattedheader”);<br />mail<br />Sends e-mail from a PHP script. (See Chapter 13.)<br />Format: $success = mail(“to”,”subj”,”message”,”headers”);<br />366 Part VI: Appendixes<br />parse_url<br />Returns an array, each element of which is a part of the URL, such as host,<br />path, port, user, and so on.<br />Format: $array_url = parse_url(“url”);<br />setcookie<br />Creates a cookie. (See Chapter 10.)<br />Format:<br />setcookie(“name”,”value”,exp,”path”,”domain”,is_secure);<br />Mathematical Functions<br />This section contains functions that perform mathematical operations. There<br />are many more functions for advanced math that are not listed in this section,<br />such as cos for cosine, tan for tangent, and pi.<br />abs<br />Returns the absolute value of number.<br />Format: $absolute = abs(number);<br />bindec<br />Converts binary to a decimal value.<br />Format: $number_decimal = bindec(binary);<br />exp<br />Returns the constant e raised to the power specified in exponent.<br />Format: $number = exp(exponent);<br />floor<br />Rounds float to the next lower integer.<br />Format: $int = floor(float);<br />hexdec<br />Converts hex (a number in hexadecimal form) to decimal.<br />Format: $number_decimal = hexdec(hex);<br />367 Appendix B: Useful PHP Built-in Functions<br />log<br />Returns the natural log of number.<br />Format: $log = log(number);<br />log10<br />Returns the base-10 logarithm of number.<br />Format: $log10 = log10(number);<br />max<br />Returns the largest number found in an array or a list of numbers.<br />Format: $num_large = max($array); or $num_large = max(num1,num2,<br />. . .);<br />min<br />Returns the smallest number found in an array or a list of numbers.<br />Format: $num_min = min($array); or $num_min = min<br />(num1,num2, . . .);<br />number_format<br />Formats a number with specified decimal (dec) and thousands separators<br />(thous). The default is a standard decimal point (.) and a comma (,) for the<br />thousands separators. (See Chapter 5.)<br />Format: $formatted = number_format(number,”dec”’,”thous”);<br />octdec<br />Converts a number in octal form to decimal form.<br />Format: $number_decimal = octdec(octal);<br />pow<br />Returns number raised to power.<br />Format: $result = pow(number,power);<br />rand<br />Returns a random number between min and max.<br />Format: $number_rand = rand(min,max);<br />368 Part VI: Appendixes<br />round<br />Rounds number to the nearest number with the specified number of decimal<br />places.<br />Format: $result = round(number,dec);<br />sqrt<br />Returns the square root of number.<br />Format: $square_root = sqrt(number);<br />srand<br />Seeds the random number generator with seed.<br />Format: srand(seed);<br />PHP Options and Information Functions<br />This section contains functions that work with PHP options and information.<br />getenv<br />Returns the value of an environmental variable.<br />Format: $environment_value = getenv(“envvarname”);<br />getlastmod<br />Gets the time that the current script was last modified.<br />Format: $timestamp = getlastmod();<br />ini_get<br />Gets the value for a configuration option.<br />Format: $string = ini_get(“option”);<br />ini_set<br />Sets the value of a configuration option. (See Chapter 4.)<br />Format: ini_set(“option”,”setting”);<br />369 Appendix B: Useful PHP Built-in Functions<br />phpinfo<br />Outputs information about your PHP version and settings. (See Chapter 2.)<br />Format: phpinfo();<br />phpversion<br />Returns the current PHP version.<br />Format: $version = phpversion();<br />putenv<br />Sets an environments variable. The value indicated in setting is usually in<br />the form name=value.<br />Format: putenv(“setting”);<br />String Functions<br />This section contains functions that work with strings.<br />addslashes<br />Escapes single quotes, double quotes, backslashes, and  in strings.<br />Format: $string_escaped = addslashes(“string”);<br />base64_encode, base64_decode<br />Encodes/decodes a string of base-64–coded characters, usually binary data.<br />(See Chapter 13.)<br />Format: $string_encoded = base64_encode(“string”);<br />chop<br />Truncates blank spaces at the end of a string.<br />Format: $chopped = chop(“string”);<br />chr<br />Returns a single ASCII character for the number code.<br />Format: $char = chr(code)<br />370 Part VI: Appendixes<br />count_chars<br />Creates an associative array out of a string. Each element has a character as<br />a key, and the value is the number of that character in the string. This function<br />has some options for only returning characters with count 0 or with<br />nonzero and others. Default, when no options is specified, is all characters.<br />Format: $array = count_chars($string,option);<br />echo<br />Outputs a list of one or more items. (See Chapter 3.)<br />Format: echo item1,item2,item3, . . .<br />ereg, eregi<br />Searches a string for pattern. The function eregi works the same but is<br />case-insensitive. (See Chapter 7.)<br />Format: $bool = ereg(“pattern”,$string);<br />ereg_replace, eregi_replace<br />Searches a string for pattern and replaces pattern with newchar.<br />Ereg_replace is case-sensitive; eregi_replace is not. (See Chapter 7.)<br />Format: $newstring = ereg_replace(“pattern”,”newchars”,<br />$string);<br />explode<br />Creates an array. Each element is part of the string, split at sep.<br />Format: $array_out = explode(“sep”,$string);<br />htmlentities<br />Converts HTML entities to special characters in a string.<br />Format: $string_out = htmlentities($orig_string);<br />htmlspecialchars<br />Converts special characters to HTML entities, such as &amp; to &amp;amp;.<br />Format: $string_out($string);<br />implode<br />Joins every element in an array into a string, separated by sep.<br />Format: $string_out = ($array,”sep”);<br />371 Appendix B: Useful PHP Built-in Functions<br />nl2br<br />Inserts a &lt;br /&gt; before all new line characters (\n) in $string.<br />Format: $string_out = ($string);<br />ord<br />Returns the ASCII value of the first character in the string.<br />Format: $integer = ord(“string”);<br />parse_url<br />Creates an associative array. Each element is part of the URL.<br />Format: $array = parse_url($url);<br />print<br />Outputs item, where item can be a string, a number, or a variable.<br />Format: print item;<br />printf<br />Outputs a string formatted according to format. (See Chapter 5.)<br />Format: printf(“format”,arg1,arg2,arg3, . . .);<br />split, spliti<br />Creates array. Each element is part of a specified string, split based on the<br />regular expression pattern. Split is case-sensitive; spliti is not.<br />Format: $array = split(“pattern”,$string); $array =<br />spliti(“pattern”,$string);<br />sprintf<br />Returns a string formatted according to format. (See Chapter 5.)<br />Format: $string = sprintf(“format”,arg1,arg2,arg3 . . .);<br />str_pad<br />Returns a string that is padded to make it number long. The character specified<br />by pad is used to pad the string.<br />Format: $string_out = str_pad($string,numberh,”pad”);<br />372 Part VI: Appendixes<br />str_repeat<br />Returns a string that contains $string repeated number times.<br />Format: $string_out = str_repeat($string,number);<br />str_replace<br />Finds all instances of oldtext in $string and replaces them with newtext.<br />Format: $string_out = str_replace(“oldtext”,”newtext”,$string)<br />strchr, strrchar<br />The function strchr returns part of string from char to end of $string, and<br />strrchar returns $string from char to start of string.<br />Format: $string_part = strchr($string,”char”);<br />strcmp, strcasecmp<br />Compares two strings on alphabetical and numerical order . Returns @@n1 if<br />str1 is less, 0 if two strings are equal, or +1 if str1 is greater. strcmp is casesensitive;<br />strcasecmp is not.<br />Format: strcasecmp($str1,$str2);<br />strcspn<br />Returns the position of the first occurrence of char in $string.<br />Format: $int = strcspn($string,”char”);<br />strip_tags<br />Removes HTML and PHP tags from string. The value allowed is optional and<br />specifies tags that should not be stripped. (See Chapter 10.)<br />Format: $string_stripped = strinp_tags($string,”allowed”);<br />strlen<br />Returns the number of characters in $string. (See Chapter 7.)<br />Format: $length = strlen($string);<br />strpos, strrpos<br />strpos returns the position of the first occurrence of char in $string.<br />strrpos returns position of last occurrence of char in string.<br />Format: $integer = strpos($string,”char”); $integer =<br />strrpos($string,”char”);<br />373 Appendix B: Useful PHP Built-in Functions<br />strspn<br />Returns the length of the substring in $string that matches text.<br />Format: $length = strspn($string,”text”);<br />strstr, stristr<br />Returns part of $string from the first occurrence of char to end of $string.<br />Strstr is case-sensitive; trichar is case-insensitive.<br />Format: $str_part = strstr($string,”char”); $str_part =<br />strstr($string,”char”);<br />strtolower, strtoupper<br />Converts $string to lowercase or uppercase.<br />Format: $string_lower = strtolower($string);<br />strtr<br />Converts from characters in $string to characters in to.<br />Format: $string_out = strtr($string,”from”,”to”);<br />substr<br />Returns a substring of $string. Starts at start and reads number characters.<br />Format: $substring = substr($string,start,number);<br />substr_replace<br />Replaces a substring with newtext. Starts at start and reads number characters.<br />Format: $string_new =<br />substr_replace($string,”newtext”,start,number);<br />trim, ltrim, rtrim<br />Removes whitespace characters from $string. The trim function removes<br />from beginning and end; ltrim removes from beginning; rtrim removes from<br />end.<br />Format: $string_new = trim($string);<br />374 Part VI: Appendixes<br />ucfirst<br />Converts first character in $string to uppercase.<br />Format: $string_new = ucfirst($string);<br />ucwords<br />Converts first character of each word in $string to uppercase.<br />Format: $string_new = ucwords($string);<br />wordwrap<br />Inserts end-of-line character (\r\n) into $string every length characters.<br />Format: $string_out = wordwrap($string,length);<br />Variable Functions<br />This section contains functions that work with variables.<br />empty<br />Tests whether the variable specified is empty. (See Chapter 7.)<br />Format: $bool = empty($varname);<br />get_defined_classes<br />Creates an array containing the names of all the classes in the script, including<br />those in included files.<br />Format: $array_classes = get_defined_classes();<br />get_defined_constants<br />Creates an associative array of all the constants.<br />Format: $array_constants = get_defined_constants();<br />get_defined_functions<br />Creates an array with names of all functions.<br />Format: $array_functions = get_defined_functions();<br />375 Appendix B: Useful PHP Built-in Functions<br />get_defined_vars<br />Creates an array of all variables.<br />Format: $array_vars = get_defined_vars();<br />isset<br />Checks whether variable is set. (See Chapter 7.)<br />Format: $bool = isset($varname);<br />print_r<br />Outputs contents of a variable. (See Chapter 4.)<br />Format: print_r($varname);<br />putenv<br />Sets an environmental variable as specified by setting. setting is usually<br />name=value.<br />Format: putenv(“setting”);<br />serialize<br />Converts data into a string containing binary data. Used to store data in a file<br />or database. The specified variable can be any type, including an object or a<br />function.<br />Format: $string_ser = serialize($variable);<br />unserialize<br />Converts serialized data back to its original form.<br />Format: $variable = unserialize($string_ser);<br />unset<br />Removes a variable. (See Chapter 4.)<br />Format: unset($varname);<br />var_dump<br />Outputs contents of a variable. (See Chapter 4.)<br />Format: var_dump($varname);<br />376 Part VI: Appendixes<br />• Symbols •<br />+ (addition operator), 77<br />+= (addition shortcut operator), 78<br />&amp; (ampersand), 68, 69, 228<br />&amp;&amp; (ampersand, double), 139<br />‘ (apostrophe), 84<br />* (asterisk), 77, 135, 266<br />*= (asterisk, equal sign), 78<br />@ (at sign), 57, 105–106<br />\ (backslash), 84, 135, 342<br />&#8220; (backticks), 287, 288<br />^ (caret), 134, 135<br />, (comma), 76–77. See also CSV file<br />/*&#8230;*/ (comments), 48–50<br />// (comments), 49<br /># (comments), 49<br />; (comments), 68<br />{} (curly braces)<br />confusing with parentheses, 326<br />enclosing block of statements, 36–37, 142<br />enclosing variable names, 60, 121<br />mismatched, 325–326<br />in pattern matching, 135<br />&#8211; (decrement operator), 78<br />/ (division operator), 77<br />/= (division shortcut operator), 78<br />$ (dollar sign), 54, 134, 323<br />$$ (dollar sign, double), 60<br />. (dot), 85, 134<br />.= (dot, equal sign), 85<br />&#8230; (ellipses), 2<br />= (equal sign), 55, 132, 154, 322<br />=&gt; (equal sign, right angle bracket),<br />99, 119–120<br />=== (equality operator), 131<br />== (equality operator), 131<br />! (exclamation point), 142–143<br />&gt; (greater than operator), 131<br />&gt;= (greater than or equal operator), 131<br />&lt;&lt;&lt;heredoc statement, 81<br />- (hyphen), 77, 89, 135, 214<br />-= (hyphen, equal sign), 78<br />-&gt; (hyphen, right angle bracket), 190–191<br />++ (increment operator), 78<br />!= (inequality operator), 131<br />!== (inequality operator), 131<br />&lt;&gt; (inequality operator), 131<br />&lt; (less than operator), 131<br />&lt;= (less than or equal operator), 131<br />* (multiplication operator), 77<br />*= (multiplication shortcut operator), 78<br />\n (new line), 46–47, 82<br />( ) (parentheses)<br />affecting order of comparisons, 139<br />affecting order of operation, 77–78<br />confusing with curly braces, 326<br />indicating function call, 162, 167<br />mismatched, 325–326<br />in pattern matching, 134<br />% (percent sign), 77, 90<br />&lt;?php&#8230;?&gt; tags, 38–39<br />+= (plus, equal sign), 78<br />+ (plus sign), 77, 135<br />++ (plus sign, double), 78<br />? (question mark), 134, 227<br />quotes, (“ double) and (‘ single)<br />enclosing numbers in mathematical<br />operations, 76<br />enclosing strings, 55, 59–60, 82–84<br />escaped characters in, 84<br />escaping with backslash (\), 342<br />magic quotes, enabling, 342<br />in mathematical operations, 76<br />special characters in, 82<br />using incorrectly, 323<br />variables in, 59–60, 82–84<br />; (semicolon), 36, 68, 321–322<br />/ (slash), 77<br />/= (slash, equal sign), 78<br />[] (square brackets), 98, 134, 135<br />- (subtraction operator), 77<br />-= (subtraction shortcut operator), 78<br />\t (tab), 82, 257<br />~ (tilde), 68<br />_ (underscore), 54, 61<br />Index<br />| (vertical bar), 135<br />|| (vertical bar, double), 139<br />• A •<br />abs function, 367<br />Access databases, 12, 260<br />Action statement, 351<br />addition operator (+), 77<br />addition shortcut operator (+=), 78<br />addslashes function, 370<br />ampersand (&amp;), 68, 69, 228<br />ampersand, double (&amp;&amp;), 139<br />and, joining comparisons with, 138<br />angle brackets, three (&lt;&lt;&lt;), starting<br />heredoc statement, 81<br />Apache Web server<br />benefits of, 25–26<br />checking if installed, 334, 339–340<br />configuring, 344–345, 351–352<br />definition of, 15, 16<br />installed with Linux, 333–334<br />installing, 26<br />installing PHP with, 335–338<br />SSL and, 202–203<br />version requirements, 334, 339<br />versions of, 26<br />Web site for, 16, 26<br />Web space, default for, 28, 29<br />apostrophe (‘), in single-quoted strings, 82.<br />See also quotes<br />apxs utility, Apache, 334, 340<br />apxs2 utility, Apache, 336<br />Arachnophilia program editor, 33<br />$argc built-in array, 41, 125–126<br />$argv built-in array, 41, 125–126<br />array function, 99, 119–120, 353<br />array_count_values function, 353<br />array_diff function, 115, 353<br />array_diff_assoc function, 115<br />array_flip function, 117<br />array_intersect function, 116, 354<br />array_keys function, 354<br />array_merge function, 114, 354<br />array_merge_recursive function,<br />114, 355<br />array_pop function, 355<br />array_push function, 355<br />array_reverse function, 355<br />array_search function, 355<br />array_slice function, 113–114, 355<br />array_sum function, 116–117, 355<br />array_unique function, 117, 355<br />arrays<br />built-in PHP arrays, 123–126<br />changing values in, 101–102<br />comparing, 115–116<br />conversions to and from, 110–113, 121<br />copying to another array, 102<br />creating, 97–100, 119–120<br />definition of, 97<br />deleting, 103<br />displaying values in, 100–101, 120<br />exchanging keys and values of, 117<br />functions for, 353–358<br />intersecting, 116<br />keys of, 98–99<br />merging, 114<br />multidimensional, 114, 118–122<br />numbering of, starting with zero instead<br />of one, 324–325<br />passing to functions, 167–168<br />reading flat files into, 254–255<br />referencing values in statements,<br />105–107, 120–121<br />removing duplicate values from, 117<br />removing values from, 102–103<br />size of, determining, 110<br />sorting, 103–105<br />splitting, 113–114<br />summing values in, 116–117<br />traversing (iterating), 107–110, 121–122<br />of words in string, 86<br />arsort function, 105, 356<br />asort function, 103–104, 356<br />asterisk (*), 77, 135, 266<br />asterisk, equal sign (*=), 78<br />at sign (@), 57, 105–106<br />attachments, e-mail, 300–302<br />attributes. See properties<br />autoglobal arrays. See superglobal arrays<br />• B •<br />background, executing commands in, 287<br />backslash (\), 84, 135, 342<br />backticks (&#8220;), 287, 288<br />backups, 23, 34<br />378 PHP 5 For Dummies<br />base64_decode function, 370<br />base64_encode function, 370<br />basename function, 281, 359<br />BBEdit program editor, 33<br />BCMath extension, 304<br />bindec function, 367<br />Black Beans Web site, 328<br />books. See publications<br />Boolean data types, 73, 74, 132<br />&lt;br&gt; tag, 46–47<br />braces ({}). See curly braces<br />brackets ([]). See square brackets<br />break statement, 145, 154–156<br />built-in PHP arrays, 123–126<br />built-in PHP constants, 66, 68–69, 71<br />built-in PHP functions<br />for arrays, 353–358<br />for date and time, 358–359<br />for file system, 359–366<br />for HTTP headers, 366–367<br />for mathematical operations, 367–369<br />for PHP options, 369–370<br />for strings, 370–375<br />using, 174<br />for variables, 375–376<br />Buying a Computer For Dummies<br />(Gookin), 25<br />bzip2 Compression extension, 307<br />• C •<br />calendar extension, 304<br />camel caps, in variable names, 54<br />caret (^), 134, 135<br />case of constant and variable names, 54, 62<br />case statement. See switch statement<br />catch statement, 194<br />ceil function, 79<br />character strings. See strings<br />characters, 81, 304<br />chdir function, 284, 359<br />check boxes, 208<br />checkdate function, 358<br />checksums, Mhash extension for, 307<br />chgrp function, 359<br />chmod function, 360<br />chop function, 370<br />chown function, 360<br />chr function, 370<br />class statement, 183–184<br />classes. See also objects<br />constructor for, 186<br />creating, 183–189<br />creating objects from, 190<br />definition of, 178–179<br />example of, 186–189<br />Exception class, 194<br />inheritance and, 180<br />methods for, 185–186<br />properties for, 184–185<br />using, 190–191<br />CLI (Command Line Interface), 14, 17,<br />30–31, 31, 40–42<br />ClibPDF extension, 307<br />__clone method, 195<br />closedir function, 360<br />COM extension, 304<br />comma (,), 76–77. See also CSV file<br />Command Line Interface. See CLI<br />commands. See system commands<br />comma-separated values file. See CSV file<br />comments (//), 49<br />comments (;), 68<br />comments (#), 49<br />comments (/*&#8230;*/), 48–50<br />commercial software, 261<br />compact function, 112–113, 356<br />comparison operators, 131–132, 322<br />complex statements, 37<br />compressed files, extensions for, 307–308<br />computer, setting up for PHP, 25<br />concatenation, 85<br />conditional statements, 130, 140–145<br />conditions, 131–139, 142–143, 322<br />configuration file. See php.ini file<br />configure command<br />for Apache installation, 337, 338<br />for Linux and Unix installation, 335<br />for Mac OS X installation, 341<br />options for, list of, 263, 342–343<br />constants, 62–65, 66, 68–69, 71. See also<br />variables<br />__construct method, 186<br />constructor, 186<br />continue statement, 154–156<br />conventions used in this book, 2<br />$_COOKIE built-in array, 124, 230<br />cookie variables, built-in array for, 124<br />379 Index<br />cookies, 227, 229–231, 233, 235–237<br />copy function, 282, 360<br />count function, 110, 356<br />count_chars function, 371<br />Crack extension, 307<br />CSV (comma-separated values) file, 256–259<br />Ctrl+C, stopping infinite loops with, 154<br />ctype extension, 304<br />cURL extension, 306–307<br />curly braces ({})<br />confusing with parentheses, 326<br />enclosing block of statements, 36–37, 142<br />enclosing variable names, 60, 121<br />mismatched, 325–326<br />in pattern matching, 135<br />current function, 108, 356<br />• D •<br />data<br />accessing from flat files, 249–255<br />exchanging with other programs, 255–259<br />passing between Web pages, 226–238<br />storing in databases, 247–249<br />storing in flat files, 247–249<br />storing in SQLite flat files, 249<br />writing to flat files, 252<br />data types. See also strings<br />assigned to variables automatically, 74<br />Boolean, 73, 74, 132<br />comparison functions for, 133<br />comparison operators for, 131<br />converted automatically, 74<br />determining for variable, 75<br />floating point numbers, 73, 75–80, 89–92<br />integers, 73, 75–80, 89–92<br />type casting, 74–75<br />of values passed to functions, 167–168<br />Database Management System. See DBMS<br />databases. See also SQLite<br />accessing, 266–271<br />advantages of, 248–249<br />choosing, 260–261<br />closing connection to, 271<br />connecting to, 267–268<br />DB package for, 309, 315–318<br />definition of, 247, 259<br />error handling for, 272–273<br />example script for, 273–276<br />extensions for, 306<br />features for, 11–12<br />functions for, 262<br />location of, 202<br />processing queried data, 269–271<br />provided by Web hosting company, 23<br />querying, 266, 268–269<br />security for, 262<br />setting up, 263–265<br />structure of, 261–262<br />supported by PHP, list of, 12, 260<br />date function, 92–93, 358<br />dates and times<br />calendar extension, 304<br />current date and time, 92<br />formatting, 92–93<br />functions for, 358–359<br />storing a timestamp in a variable, 94–95<br />DB package, 309, 315–318<br />DB2 databases (IBM), 12, 260, 263<br />dBASE databases, 12<br />DBMS (Database Management System),<br />259. See also databases<br />debugger, enabling, 342<br />decrement operator (&#8211;), 78–79<br />default.htm file, 21<br />define function, 62<br />__destruct method, 196<br />Developer’s Tools CD, Mac OS X, 340<br />die statement, 72, 174–175<br />directories<br />changing current directory, 284<br />for configuration file, 42, 342–343, 350<br />creating, 283–284<br />definition of, 279<br />determining for file, 281<br />for documentation, 342<br />listing with FTP, 293–294<br />for man files, 342<br />opening, 284<br />for PHP programs, 342<br />reading file names from, 284–285<br />Web space location, 21, 28<br />directory handle, 284<br />directory servers, LDAP extension for, 307<br />dirname function, 281, 360<br />discussion lists. See mailing lists<br />disk space requirements, Web hosting, 23<br />disk_free_space function, 360<br />380 PHP 5 For Dummies<br />disk_total_space function, 360<br />display_errors setting in php.ini file, 69<br />division operator (/), 77<br />division shortcut operator (/=), 78<br />dll (Dynamic Link Library), 264<br />do..while statement, 145, 151–152<br />documentation for PHP, 342<br />dollar sign ($), 54, 134, 323<br />dollar sign, double ($$), 60<br />domain name registration, 23<br />Domxml extension, 307<br />dot (.), 85, 134<br />dot, equal sign (.=), 85<br />double quotes. See quotes<br />Dreamweaver MX software, 34<br />Dynamic Link Library. See dll<br />dynamic variable names, 60–61<br />dynamic Web pages, 199<br />• E •<br />E_ALL built-in constant, 68–69<br />echo statement<br />definition of, 36, 44–45, 371<br />displaying array values with, 106<br />displaying constants with, 66<br />displaying HTML forms with, 204–205<br />displaying multidimensional array values<br />with, 120–121<br />displaying strings with, 89<br />displaying text fields with, 206<br />displaying variables with, 56–57, 59–60<br />example scripts using, 57–58<br />editors. See program editors<br />EditPlus program editor, 33<br />ellipses (&#8230;), 2<br />else statement. See if statement<br />elseif statement. See if statement<br />Emacs program editor, 33<br />e-mail, 23, 297–302, 307, 367<br />embedded scripting language, 15<br />empty function, 133, 213, 375<br />encryption, 307<br />enctype attribute, form tag, 239<br />end function, 108, 356<br />E_NOTICE built-in constant, 68–69<br />$_ENV built-in array, 124–125<br />equal sign (=), 55, 132, 154, 322<br />equal sign, right angle bracket (=&gt;), 99,<br />119–120<br />equality operator (==), 131<br />equality operator (===), 131<br />ereg function, 371<br />eregi function, 371<br />eregi_replace function, 371<br />ereg_replace function, 371<br />error level, setting, 68–70<br />error messages. See also troubleshooting<br />about long arrays, 123<br />cannot modify header information, 225<br />customizing, 71–72<br />database access denied, 272<br />database results invalid, 272–273<br />definition of, 67<br />exception handling, 194<br />formatting of, 41<br />in functions, 174–175<br />functions handling, 72<br />logging, 70–72<br />missing argument, 169<br />no such file or directory, 250<br />parsing errors, 36, 321<br />preventing display of, 57, 105–106<br />SQLite and, 278<br />from system commands, 286<br />types of, 67<br />undefined index, 105<br />undefined variables, 57<br />error_log setting, in php.ini file, 70<br />error_log statement, 71–72<br />error_reporting setting, in php.ini file,<br />68–69<br />error_reporting statement, 69–70<br />escaped characters, in double-quoted<br />strings, 84<br />E_USER_ERROR built-in constant, 71<br />E_USER_NOTICE built-in constant, 71<br />E_USER_WARNING built-in constant, 71<br />Exception class, 194<br />exclamation point (!), 142–143<br />exec function, 287, 289–290<br />executable files, checking for, 280<br />exit statement, 175<br />exp function, 367<br />explode function, 110–111, 356, 371<br />extension setting in php.ini file, 264–265<br />381 Index<br />extensions to PHP<br />activating and deactivating, 304–305<br />list of, 304, 306–308<br />PEAR repository for, 309–318<br />extract function, 112, 356<br />• F •<br />f formatting instruction, 90<br />FALSE values, 74. See also Boolean<br />data types<br />fclose function, 251, 360<br />FDF extension, 307<br />feof function, 253, 360<br />fgetc function, 361<br />fgetcsv function, 256–257, 361<br />fgets function, 252–254, 361<br />fgetss function, 361<br />__FILE__ built-in constant, 66<br />file extensions<br />for included files, 158, 160<br />for PHP scripts, 15, 21<br />file function, 254–255, 361<br />file handle, 249<br />file system, 279. See also files<br />File Transfer Protocol. See FTP<br />fileatime function, 281, 361<br />filectime function, 281, 361<br />file_exists function, 280, 361<br />file_get_contents function, 255, 300–301<br />filegroup function, 281<br />filemtime function, 281, 361<br />fileowner function, 281, 362<br />fileperms function, 362<br />filePro databases, 12<br />files. See also databases; flat files; FTP<br />checking for existence of, 280<br />checking whether executable, 280<br />checking whether readable, 281<br />checking whether writable, 281<br />compressed files, 307<br />copying, 282<br />creation time of, determining, 281<br />current file, built-in constant for, 66<br />deleting, 283<br />directory name of, from path, 281<br />filename of, from path, 281<br />functions for, 359–366<br />group ID for, determining, 281<br />including in scripts, 158–162<br />last access time of, determining, 281<br />last modified time of, determining, 281<br />list of, displayed on Web site, 201<br />names of, retrieving, 284–285<br />renaming, 282<br />security for, 201–202<br />sending as e-mail attachments, 300–302<br />size of, determining, 281<br />transferring with FTP, 292–297<br />type of, determining, 280, 281<br />uploaded, built-in array for, 124<br />uploading to Web site, 238–244<br />user ID for, determining, 281<br />$_FILES built-in array, 124, 240–241<br />filesize function, 281, 362<br />filetype function, 362<br />final var statement, 185<br />Flash movies, 308<br />flat files, 247–259, 276–278. See also SQLite<br />(float), type casting to floating point, 75<br />floating point data types, 73, 75–80, 89–92<br />flock function, 362<br />floor function, 79, 367<br />folders. See directories<br />font conventions used in this book, 2<br />fopen function, 249–251, 362<br />for statement, 145–149<br />foreach statement, 109–110, 121–122<br />formatting instructions, 90–92<br />forms. See HTML forms<br />fputs function, 362<br />fread function, 362<br />Free PHP Hosting Directory Web site, 330<br />FrontBase databases, 12<br />fscanf function, 363<br />fseek function, 363<br />FTP (File Transfer Protocol), 21, 34,<br />292–297, 304, 306, 342<br />ftp_cdup function, 296<br />ftp_chdir function, 296<br />ftp_close function, 294, 296<br />ftp_connect function, 292–293, 296<br />ftp_delete function, 296<br />ftp_exec function, 296<br />ftp_fget function, 296<br />ftp_fput function, 296<br />ftp_get function, 294–296<br />ftp_login function, 293, 296<br />382 PHP 5 For Dummies<br />ftp_mdtm function, 296<br />ftp_mkdir function, 296<br />ftp_nlist function, 293–294, 296<br />ftp_put function, 294, 296<br />ftp_pwd function, 296<br />ftp_rename function, 297<br />ftp_rmdir function, 297<br />ftp_size function, 297<br />ftp_systype function, 297<br />functions. See also built-in PHP functions;<br />methods; specific functions<br />calling, 162, 175<br />creating, 163–165<br />definition of, 162<br />for error handling, 72<br />error handling in, 174–175<br />global variables in, 166<br />local variables in, 165–166<br />for mail, 367<br />passing values to, 164, 167–171<br />returning values from, 164–165, 171–173<br />sorting arrays by, 105<br />fwrite function, 252, 363<br />• G •<br />GD library extension, 306, 307<br />general-purpose scripting. See scripting<br />language, PHP used as<br />$_GET built-in array, 124, 211, 228<br />GET method, 211–212<br />get variables, built-in array for, 124<br />get_browser function, 366<br />getcwd function, 363<br />getdate function, 358<br />get_defined_classes function, 375<br />get_defined_constants function, 375<br />get_defined_functions function, 375<br />get_defined_vars function, 376<br />getenv function, 369<br />getlastmod function, 363, 369<br />get_meta_tags function, 366<br />gettext extension, 307<br />global statement, 166<br />global variables, 124, 166<br />$GLOBALS built-in array, 124<br />gmdate function, 358<br />gmmktime function, 359<br />Gookin, Dan<br />Buying a Computer For Dummies, 25<br />PCs For Dummies, 25<br />graphics, extension for, 306–307<br />greater than operator (&gt;), 131<br />greater than or equal operator (&gt;=), 131<br />group ID for file, 281<br />gvim program editor, 33<br />gzip-compressed files, extension for, 304<br />• H •<br />header function, 225–226, 324, 366<br />Hello World example, 42–44, 57–58<br />help file, displaying, 42<br />&lt;&lt;&lt;heredoc statement, 81<br />hexdec function, 367<br />hidden fields in HTML forms, 231<br />HomeSite program editor, 33<br />host computer, security for, 200–201<br />HTML 4 For Dummies, Quick Reference<br />(Ray; Ray), 3<br />HTML 4 For Dummies (Tittel; Pitts), 3, 204<br />HTML forms<br />books about, 204<br />check boxes in, 208<br />collecting data with, 204–212<br />data entered by users, security for,<br />202, 213–222<br />definition of, 203<br />displaying, 204–205<br />example script for, 215–220<br />features for, 11<br />hidden fields in, 231<br />passing information to next page,<br />227, 231–232<br />post variables in, built-in array for, 124<br />submit button, displaying new page, 224<br />uploading files using, 239–244<br />HTML links. See links, HTML<br />HTML pages. See Web pages<br />HTML tags, 202, 203<br />htmlentities function, 371<br />HTML-Kit program editor, 33<br />htmlspecialchars function, 220–222, 371<br />HTTP headers, 41, 225–226, 324, 366–367<br />$HTTP_COOKIE_VARS built-in array, 124<br />$HTTP_ENV_VARS built-in array, 124<br />383 Index<br />$HTTP_FILES_VARS built-in array, 124<br />$HTTP_GET_VARS built-in array, 124<br />$HTTP_POST_VARS built-in array, 124<br />HTTPS server, cURL extension for, 306<br />https, URL prefixed with, 202<br />$HTTP_SERVER_VARS built-in array, 124<br />$HTTP_SESSION_VARS built-in array, 124<br />hyperlinks. See links, HTML<br />hyphen (-), 90, 135, 214<br />hyphen, right angle bracket (-&gt;), 190–191<br />• I •<br />IBM DB2. See DB2 databases<br />icons used in this book, 5<br />iconv extension, 307<br />IDE (Integrated Development<br />Environment), 33–34, 329<br />identifiers. See variables, naming<br />if statement, 37, 140–143<br />IIS/PWS Web server<br />configuring on Windows, 350, 352<br />definition of, 16<br />PHP used with, 15<br />SSL and, 203<br />Web space, default for, 28<br />IMAP extension, 307<br />implode function, 111–112, 121, 357, 371<br />in_array function, 357<br />.inc file extension, 158<br />include directory, 161–162<br />include statement, 158–160, 203, 325, 342<br />include_once statement, 159<br />include_path setting, in php.ini file, 161<br />including files, 158–162<br />increment operator (++), 78–79<br />indenting statements, 37<br />index of an array. See keys of an array<br />index.htm file, 21<br />index.html file, 21, 201<br />inequality operator (&lt;&gt;), 131<br />inequality operator (!=), 131<br />inequality operator (!==), 131<br />infinite loops, avoiding, 151, 153–154, 156<br />Informix databases, 12, 260, 263<br />Ingres databases, 12, 260, 263<br />inheritance, 180–181<br />ini_get function, 369<br />ini_set function, 161, 369<br />INSERT INTO query, 266<br />installation<br />of extensions, 305<br />of PEAR packages, 313–314<br />of PHP, 26–27, 333–343, 345–349<br />of server, 25–26<br />(int), type casting to integer, 75<br />integer data types, 73, 75–80, 89–92<br />Integrated Development Environment.<br />See IDE<br />InterBase databases, 12<br />iPlanet Web server, 15<br />is_array function, 133<br />is_dir function, 280, 283, 363<br />is_executable function, 280<br />is_file function, 280, 363<br />is_float function, 133<br />is_int function, 133<br />is_null function, 133<br />is_numeric function, 133<br />is_readable function, 281, 364<br />isset function, 133, 376<br />is_string function, 133<br />is_uploaded_file function, 364<br />is_writable function, 281, 364<br />italic font used in this book, 2<br />• J •<br />Japanese characters, extension for, 307<br />JAVA extension, 307<br />JavaScript, 11, 12, 244–246<br />JavaScript For Dummies (Vander Veer), 244<br />• K •<br />key function, 107, 357<br />key_exists function, 357<br />keys of an array, 98–99. See also arrays<br />keywords, 63<br />Komodo software, 34<br />krsort function, 105, 357<br />ksort function, 105, 357<br />384 PHP 5 For Dummies<br />• L •<br />language support, gettext extension for, 307<br />LDAP extension, 307<br />LDAP server, cURL extension for, 306<br />Lerdorf, Rasmus (PHP developer), 9<br />less than operator (&lt;), 131<br />less than or equal operator (&lt;=), 131<br />line numbers for scripts, 36, 66<br />__LINE__ built-in constant, 66<br />link function, 364<br />links, HTML, 224<br />Linux<br />installing PHP, 333–338<br />running scripts using, 40<br />setting up database support, 263–264<br />Web space, default for, 28<br />list statement, 106–107<br />local variables, 165–166<br />localtime function, 359<br />log file, sending error messages to, 70<br />log function, 368<br />log_errors setting, in php.ini file, 70<br />log10 function, 368<br />loop statements. See also conditions<br />break statement, 154–156<br />continue statement, 154–156<br />definition of, 130, 145<br />do..while statement, 151–152<br />for statement, 146–149<br />foreach statement, 109–110, 121–122<br />infinite loops, avoiding, 151, 153–154, 156<br />while statement, 149–151<br />lowercase letters. See case of constant<br />and variable names<br />ltrim function, 86, 374<br />• M •<br />Mac OS X<br />installing PHP, 339–341<br />PHPMac Web site, 329<br />setting up database support, 263–264<br />magic quotes, enabling, 342<br />Maguma software, 34<br />mail. See e-mail<br />mail function, 299, 367<br />Mail package, 309<br />mail server for outgoing mail, 297–299<br />mailing lists, 17, 25, 30, 327–328<br />man files, 342<br />math library, BCMath extension, 304<br />mathematical operations<br />built-in functions for, 79, 367–369<br />on dates, 95<br />on numbers, 75–79<br />max function, 368<br />Mcrypt Encryption extension, 307<br />messages, e-mail, 299–300<br />methods<br />adding to a class, 185–186<br />choosing, 182<br />__clone method, 195<br />__construct method, 186<br />definition of, 179–180<br />__destruct method, 196<br />GET and POST methods, 211–212<br />private or protected, 191–193<br />Mhash extension, 307<br />Microsoft IIS/PWS. See IIS/PWS<br />Microsoft SQL Server. See SQL Server<br />databases<br />microtime function, 359<br />Mime type extension, 308<br />min function, 368<br />Ming for Flash extension, 308<br />minus, equal sign (-=), 78<br />minus sign (-), 77<br />minus sign, double (—), 78<br />mkdir function, 283–284, 364<br />mktime function, 94, 359<br />mod_so module, Apache, 334, 339<br />modules, on command line, 42<br />modulus operator (%), 77<br />move_uploaded_file function, 241, 364<br />mSQL databases, 12, 260, 263, 265, 342<br />Multi-byte String extension, 307<br />multidimensional arrays, 114, 118–122<br />multiple inheritance, not supported, 181<br />multiplication operator (*), 77<br />multiplication shortcut operator (*=), 78<br />MySQL databases, 12, 17, 203, 260, 263,<br />265, 343<br />385 Index<br />• N •<br />\n (new line), 46–47, 82<br />natcasesort function, 357<br />native language support, 307<br />natsort function, 105, 357<br />nesting, 121–122, 143, 147<br />Netscape Enterprise Server. See iPlanet<br />Web server<br />Net_SMTP package, 309<br />Net_Socket package, 309<br />new line character (\n), 46–47, 82<br />new statement, 190<br />next function, 108, 357<br />nl2br function, 372<br />notices, 67. See also error messages<br />number_format function, 79–80, 368<br />numbers<br />numeric data types, 73, 75–80, 89–92<br />in variable names, 54<br />• O •<br />object-oriented programming<br />classes, 178–179, 182–191<br />definition of, 17, 177–178<br />developing a program using, 181–189<br />exception handling, 194<br />inheritance, 180–181<br />methods, 179–180, 182, 185–186, 191–193<br />multiple inheritance, not supported, 181<br />objects, 178–179, 181, 195, 196<br />polymorphism, not supported, 181<br />properties, 179, 182, 184–185, 191–193<br />objects<br />choosing, 181<br />copying, 195<br />creating (instantiating), 190<br />definition of, 178–179<br />destroying, 196<br />octdec function, 368<br />odbc extension, 304<br />ODBC (Open Database Connectivity)<br />standard, 12, 260<br />open source license for PHP, 10<br />open source software, 261<br />opendir function, 284, 364<br />OpenSSL, 308, 343<br />operating system commands. See system<br />commands<br />operating systems, 10, 26, 124<br />or, joining comparisons with, 138<br />Oracle databases, 12, 260, 263, 343<br />ord function, 372<br />order of execution, 129–130<br />order of operations, 77–78<br />outgoing mail server, 297–299<br />output statements, 44–48, 79–80, 89–92,<br />225, 324<br />• P •<br />packages. See PEAR<br />parentheses (( ))<br />affecting order of comparisons, 139<br />affecting order of operation, 77–78<br />confusing with curly braces, 326<br />indicating function call, 162, 167<br />mismatched, 325–326<br />in pattern matching, 134<br />parse_url function, 366, 372<br />parsing errors, 36<br />parsing, tokenizer extension for, 304<br />passthru function, 287, 290–291, 364<br />passwords, 238, 307<br />pathinfo function, 281, 365<br />pattern matching (regular expressions)<br />definition of, 133–134<br />example patterns, 135–137<br />Perl-compatible, extension for, 304<br />special characters for, 134–135<br />validating HTML form information<br />with, 214<br />pcre extension, 304<br />PCs For Dummies (Gookin), 25<br />PDF documents, extensions for, 306–308<br />PEAR (PHP Extension and Application<br />Repository)<br />definition of, 309<br />finding packages in, 309–311<br />installing packages, 313–314<br />listing installed packages, 314<br />packages included with PHP, 309<br />setting up, 311–313<br />uninstalling packages, 314<br />386 PHP 5 For Dummies<br />updating packages, 314<br />using packages, 314–318<br />percent sign (%), 77, 90<br />performance, Zend engine and, 17<br />period (.), 85, 134<br />period, equal sign (.=), 85<br />Perl-compatible regular expressions,<br />extension for, 304<br />PHP (Personal Home Page)<br />applications of, 10–13, 14–15<br />configuring, 29–30, 32, 343–345, 349–352<br />definition of, 9, 10, 14–15<br />extensions to, 304–318<br />features of, 10, 17, 303<br />information about, displaying, 42<br />installing, 26–27, 333–338, 339–341,<br />345–349<br />JavaScript and, 11, 12, 244–246<br />mailing lists, 17, 25, 30, 327–328<br />program names for, 17<br />system requirements for, 3, 19<br />technical support, 10, 16–17, 30<br />testing, 27–30<br />updating, 16–17<br />version 4.x, 18, 22<br />version 5, 17<br />version requirements, 22, 27<br />Web site for, 10, 327<br />PHP &amp; MySQL For Dummies (Valade),<br />203, 265<br />PHP Beginners Web site, 328<br />PHP Builder Web site, 328<br />PHP CLI. See CLI<br />PHP Dev Center Web site, 329<br />PHP Editors Web site, 329<br />php- file, 335<br />.php file extension, 15, 21, 160<br />PHP files. See scripts<br />PHP Hypertext Preprocessor. See PHP<br />php program, 17, 41, 42, 342<br />PHP scripts. See scripts<br />&lt;?php&#8230;?&gt; tags, 38–39<br />php5.0.0-win32.zip file, 349<br />php5ts.dll file, 31, 349<br />php500-installer.exe file, 346<br />php-cgi program, 17, 27, 29, 31, 342<br />PHPEdit software, 34<br />php.exe file, 17, 31<br />phpinfo function, 28, 42, 125, 304, 370<br />php.ini file<br />activating extensions in, 305<br />definition of, 32<br />editing, 32<br />location of, 42, 342, 343, 350<br />restarting server after changing, 69<br />setting error level in, 68–69<br />setting for long arrays in, 123<br />setting include directory in, 161<br />setting outgoing mail server in, 298<br />setting session save path in, 232<br />setting sessions automatically<br />starting, 233<br />setting temporary upload directory in,<br />239–240<br />setting up database support, 264–265<br />setting whether session ID is passed, 233,<br />236–237<br />php.ini-dist directory, 343<br />php.ini-dist file, 350<br />PHPMac Web site, 329<br />$PHPSESSID variable, 232, 235, 236–237<br />PHPUnit package, 309<br />phpversion function, 370<br />.phtml file extension, 15, 21<br />piping output from system command, 287<br />Pitts, Natanya (HTML 4 For Dummies), 3, 204<br />platforms. See operating systems<br />plus, equal sign (+=), 78<br />plus sign (+), 77, 135<br />plus sign, double (++), 78<br />pointers, traversing an array using, 108–109<br />polymorphism, not supported, 181<br />$_POST built-in array, 124, 211<br />POST method, 211–212<br />post variables in, built-in array for, 124<br />PostgreSQL databases, 12, 260, 263, 343<br />pow function, 368<br />&lt;pre&gt; tag, 101<br />prev function, 108, 357<br />print function, 372<br />Printer extension, 308<br />printf function, 80, 89–92, 372<br />print_r function, 56, 66, 100, 376<br />privacy. See security<br />private methods or properties, 191–193<br />program editors, 32–33, 329<br />programs, running from PHP, 13<br />properties, 179, 182, 184–185, 191–193<br />387 Index<br />protected methods or properties, 192–193<br />publications. See also Web sites<br />about computers, 25<br />about HTML, 3<br />about JavaScript, 244<br />about PHP with MySQL, 203<br />about SQL, 265<br />putenv function, 370, 376<br />• Q •<br />queries. See SQL<br />question mark (?), 134, 227<br />quotes, (“ double) and (‘ single)<br />enclosing numbers in mathematical<br />operations, 76<br />enclosing strings, 55, 59–60, 82–84<br />escaped characters in, 84<br />escaping with backslash (\), 342<br />magic quotes, enabling, 342<br />in mathematical operations, 76<br />special characters in, 82<br />using incorrectly, 323<br />variables in, 59–60, 82, 83–84<br />• R •<br />radio buttons, 208<br />rand function, 368<br />range function, 99–100, 358<br />Ray, Deborah S. and Ray, Eric J. (HTML 4<br />For Dummies, Quick Reference), 3<br />RDBMS (Relational Database Management<br />System), 259. See also databases<br />readdir function, 284–285, 365<br />readfile function, 365<br />register_globals setting in php.ini<br />file, 18<br />register_long_arrays setting in<br />php.ini file, 123<br />regular expressions. See pattern matching<br />Relational Database Management System.<br />See RDBMS<br />remainder. See modulus operator<br />rename function, 282, 365<br />$_REQUEST built-in array, 124, 211, 228<br />require statement, 159<br />require_once statement, 159, 314<br />reset function, 108, 358<br />return statement, 163–165, 171–173<br />reusing code<br />including files, 158–162<br />reasons for, 157<br />using built-in functions, 174<br />writing functions, 162–173<br />rewind function, 365<br />rmdir function, 365<br />root directory, 279<br />round function, 369<br />RPM format for PHP installation, 333–334<br />rsort function, 104, 358<br />rtrim function, 86, 253, 374<br />• S •<br />s formatting instruction, 90<br />safe_mode setting, disabling backtick<br />operator, 288<br />ScriptAlias statement, 351<br />scripting language, PHP used as, 14, 15,<br />30–31. See also php program; scripts<br />scripts<br />adding to Web pages, 38–40<br />building, 37–42<br />definition of, 35<br />documenting (comments in), 48–50<br />error checking for, 42<br />error level for, 69–70<br />file extensions for, 15, 21<br />IDEs for, 33–34, 329<br />including files into, 158–162<br />line numbers for, 36<br />processing of, 45–46<br />program editors for, 32–33, 329<br />running with CLI, 40–42<br />specifying on command line, 42<br />variables passed into, 125–126<br />viewing source in browser, 44<br />Secure Sockets Layer. See SSL<br />security<br />of Apache Web server, 26<br />bugs in PHP versions prior to 4.3.1, 22<br />of data entered by users, 202, 213–222, 291<br />of databases, 248, 262<br />features for, 11<br />of files, 201–202<br />of host computer, 200–201<br />of included files, 160–161<br />388 PHP 5 For Dummies<br />of passing variables through URL, 228<br />privacy of information, 201–202<br />of server, 202–203<br />sessions requiring user login, 238<br />of system command execution, 291<br />of uploading files, 241<br />of Web site, 200–203<br />SELECT query, 266<br />selection lists, 208–210<br />semicolon (;), 36, 68, 321–322<br />sendmail_from setting in php.ini file, 298<br />sendmail_path setting in php.ini file,<br />298–299<br />serialize function, 376<br />server<br />configuring on Windows, 350<br />cURL extension for, 306–307<br />definition of, 11, 15, 16<br />information about, 123, 124<br />installing, 25–26<br />processing of output statements by, 45–46<br />processing of PHP files by, 38, 39<br />requirements for, 19<br />security of, 201–203<br />supported by PHP, list of, 15, 16<br />$_SERVER built-in array, 123–125<br />server-side scripting language, 11<br />servlets, enabling during installation, 343<br />$_SESSION built-in array, 124, 234–235<br />session extension, 304<br />session ID, 232, 236–237<br />session.auto_start setting in php.ini<br />file, 233<br />session_destroy function, 233–234<br />sessions<br />closing, 233–234<br />cookies and, 233, 235–237<br />definition of, 232–233<br />opening, 233<br />restricted, requiring user login, 238<br />storing information from, 227<br />variables for, 124, 234–235<br />session.save_path setting in php.ini<br />file, 232<br />session_start function, 233<br />setcookie function, 225, 230–231, 367<br />set_error_handler statement, 72<br />Shared Memory extension, 308<br />SID constant, 236–237<br />Simple Mail Transfer Protocol. See SMTP<br />simple statements, 36<br />single quotes. See quotes<br />sizeof function, 110, 358<br />slash (/), 77<br />slash, equal sign (/=), 78<br />SMTP setting in php.ini file, 298<br />SMTP (Simple Mail Transfer Protocol),<br />297, 309<br />SNMP extension, 308<br />Sockets extension, 308<br />sort function, 103–104, 358<br />SourceForge Web site, 329<br />special characters<br />in output statements, 46–48<br />in pattern matching, 134–135<br />in strings, 82<br />split function, 372<br />spliti function, 372<br />sprintf function, 80, 89–92, 372<br />SQL For Dummies (Taylor), 265<br />SQL Server databases (Microsoft), 12, 260<br />SQL (Structured Query Language), 265–266<br />SQLite, 17, 249, 276–278, 304<br />sqlite_close function, 277<br />sqlite_fetch_array function, 277<br />sqlite_open function, 277<br />sqlite_query function, 277<br />sqrt function, 79, 369<br />square brackets ([]), 98, 134, 135<br />srand function, 369<br />SSL (Secure Sockets Layer), 202, 308<br />statelessness, 223<br />statements. See also specific statements<br />block of, 36–37<br />complex statements, 37<br />conditional statements, 130, 140–145<br />definition of, 35<br />indenting, 37<br />line numbers for, 36<br />loop statements, 109–110, 121–122, 130,<br />145–156<br />order of execution, 129–130<br />output statements, 44–48, 79–80, 89–92,<br />225, 324<br />parsing errors in, 36<br />running from command line, 42<br />simple statements, 36<br />syntax of, 36–37<br />389 Index<br />static Web pages, 199, 203<br />strcasecmp function, 373<br />strchr function, 87, 373<br />strcmp function, 373<br />strcspn function, 373<br />(string), type casting to a string, 75<br />strings<br />adding characters to, 85<br />built-in functions for, 86–88, 370–375<br />case of, modifying, 87, 88<br />comparing, 132<br />comparing to patterns, 137<br />concatenating (joining together), 85<br />converting arrays into, 111–112<br />converting into arrays, 110–111<br />counting words in, 86<br />as data type, 73<br />escape characters in, 84<br />formatting for output, 89–92<br />length of, determining, 87<br />new line character (\n) in, 82<br />numbers converted to when formatting, 80<br />quotes enclosing, 55, 59–60, 82–84<br />reading entire flat files into, 255<br />reading parts of flat files into, 253–254<br />repeating, 87<br />replacing substrings in, 87–88<br />returning substrings from, 87–88<br />reversing, 87<br />splitting into words, 86<br />tab character (\t) in, 82<br />trimming leading and trailing spaces, 86<br />type casting to, 75<br />variables in, evaluation of, 82–84<br />very long (heredoc statement), 81<br />strip_tags function, 220–222, 373<br />stristr function, 87, 374<br />strlen function, 87, 373<br />str_pad function, 372<br />strpos function, 87, 373<br />strrchar function, 373<br />strrchr function, 87<br />str_repeat function, 87, 373<br />str_replace function, 87, 373<br />strrev function, 87<br />strrpos function, 87, 373<br />strspn function, 374<br />strstr function, 374<br />strtolower function, 87, 374<br />strtotime function, 94–95<br />strtoupper function, 88, 374<br />strtr function, 374<br />Structured Query Language. See SQL<br />str_word_count function, 86<br />style arrays, 18. See also superglobal arrays<br />substr function, 88, 374<br />substr_count function, 88<br />substr_replace function, 88, 374<br />subtraction operator (-), 77<br />subtraction shortcut operator (-=), 78<br />superglobal arrays, 18, 123<br />support, technical. See technical support<br />switch statement, 144–145<br />Sybase databases, 12, 260, 263<br />system commands, 13, 286–291, 296<br />system function, 287, 289<br />system requirements, 3, 19<br />• T •<br />tab character (\t), 82<br />tab-separated values file. See TSV file<br />tags. See HTML tags<br />tarball for PHP installation, 335<br />tar.gz file, 335<br />Taylor, Allen (SQL For Dummies), 265<br />TCP sockets, Net_Socket package for, 309<br />technical support<br />for database software, 261<br />for PHP, 10, 16–17, 30<br />for Web hosting company, 22–23<br />Telnet server, cURL extension for, 306<br />tempnam function, 365<br />text fields, 204–208<br />$this variable, 185<br />throw statement, 194<br />tilde (~), 68<br />time. See dates and times<br />time function, 359<br />timestamp, storing in variable, 94–95<br />Tittel, Ed (HTML 4 For Dummies), 3, 204<br />tmpfile function, 365<br />tokenizer extension, 304<br />touch function, 366<br />track-vars setting, 125<br />trans-sid setting in php.ini file,<br />233, 236–237<br />trigger_error statement, 71<br />390 PHP 5 For Dummies<br />trim function, 86, 214, 222, 374<br />troubleshooting. See also error messages<br />after installation, 29–30<br />array numbering, 324–325<br />error checking scripts, 42<br />infinite loops, avoiding, 151, 153–154, 156<br />missing semicolons, 321–322<br />parentheses and curly braces,<br />325–326<br />PHP statements in included file, 325<br />quotes used incorrectly, 323<br />single equal sign (=) used in<br />comparisons, 322<br />statements that must come before<br />browser output, 225, 324<br />variable names, 322–323<br />TRUE values, 74. See also Boolean<br />data types<br />try statement, 194<br />TSV (tab-separated values) file, 257–259<br />type casting, 74–75<br />• U •<br />ucfirst function, 88, 375<br />ucwords function, 88, 375<br />umask function, 366<br />underscore (_), 54, 61<br />Uniform Resource Locator. See URL<br />Unix<br />installing PHP, 333–338<br />running scripts using, 40<br />setting up database support, 263–264<br />unlink function, 283, 366<br />unserialize function, 376<br />unset function, 62, 102–103, 196, 234, 376<br />upload_tmp_dir setting in php.ini file,<br />239–240<br />uppercase letters. See case of constant and<br />variable names<br />URL (Uniform Resource Locator)<br />definition of, 14<br />passing information with, 227–228<br />prefixed with https, 202<br />user ID for file, 281<br />user sessions. See sessions<br />usort statement, 105<br />• V •<br />Valade, Janet<br />PHP &amp; MySQL For Dummies, 203, 265<br />Web site, 330<br />Vander Veer, Emily A. (JavaScript For<br />Dummies), 244<br />var statement, 184–185<br />var_dump function, 75, 100–101, 120, 376<br />variable variables. See dynamic variable<br />names<br />variables. See also constants; data types;<br />properties<br />$this variable, 185<br />changing information in, 55–56<br />checking content of, 133<br />converting arrays into, 112<br />converting into arrays, 112–113<br />creating, 55–56<br />definition of, 53, 55<br />deleting when session ends, 234<br />determining data type of, 75<br />displaying in HTML forms, 205–207, 208<br />displaying values in, 56–57, 59–60<br />dynamic variable names, 60–61<br />empty, 56–57, 61<br />evaluation of, in strings, 82–84<br />example scripts using, 57–58<br />formatted output in, 80, 89–92, 372<br />formatting for output, 89–92<br />functions for, 375–376<br />global, 166<br />local, 165–166<br />missing dollar sign ($) in, 323<br />misspelled, 322<br />naming, 53–54<br />passed into scripts, referencing, 125–126<br />passing at end of URL, 227–228<br />passing to functions, 164, 167–171<br />passing with cookies, 229–231<br />$PHPSESSID variable, 232, 235–237<br />preventing error messages when<br />displaying, 57<br />receiving system command output,<br />288–290<br />removing information from, 61<br />returning from functions, 171–173<br />391 Index<br />variables (continued)<br />session variables, 234–235<br />in system commands, 291<br />uncreating (deleting), 62<br />using with JavaScript, 245–246<br />when to use, 65<br />vertical bar (|), 135<br />vertical bar, double (||), 139<br />vi editor, 33<br />vim program editor, 33<br />• W •<br />warning messages, 67. See also error<br />messages<br />wddx extension, 304<br />WDDX standard, extension for, 304<br />Web applications. See also HTML forms<br />features for, 11–12<br />requirements for, 19–20<br />scripts for, processing, 15, 38<br />scripts for, writing, 38–40<br />Web environment<br />creating for PHP, 20, 25–27<br />existing, using for PHP, 20–21<br />requirements for, 19–20<br />testing, 27–30<br />Web hosting company, 22–25, 330<br />Web pages<br />access speed of, 22<br />adding scripts to, 38–40<br />backups of, 23<br />copying to Web site, 21<br />default file for, 21, 201<br />dynamic, 199<br />location of, 21<br />navigating, 224–226<br />passing information between, 226–238<br />relocating user to another page, 225–226<br />statelessness of, 223<br />static, 199, 203<br />Web server. See server<br />Web sites<br />Apache source code, 337<br />Apache Web server, 16, 26<br />author’s, 330<br />Black Beans, 328<br />Developer’s Tools CD, Mac OS X, 340<br />error level for, 68–69<br />Free PHP Hosting Directory, 330<br />for IDEs, 34<br />navigating, 224–226<br />open source SSL, 202–203<br />opening files on, 251<br />PEAR, 310<br />PHP, 10, 327<br />PHP Beginners, 328<br />PHP Builder, 328<br />PHP Dev Center, 329<br />PHP Editors, 329<br />PHP mailing lists, 17<br />PHP technical support, 10<br />PHPMac, 329<br />for program editors, 33–34<br />security for, 200–203<br />SourceForge, 329<br />uploading files to, 238–244<br />Zend, 328<br />Web space, location of, 28<br />while statement, 145, 149–151<br />white space, in statements, 36<br />Windows<br />running scripts using, 41<br />setting up database support, 264–265<br />setting up PEAR, 312–313<br />wordwrap function, 375<br />World Wide Web (WWW), 14<br />• X •<br />XML<br />Domxml extension, 307<br />enabling during installation, 343<br />xml extension, 304<br />XML_Parser package, 309<br />XML-RPC extension, 308<br />xor, joining comparisons with, 138<br />XSLT extension, 308<br />• Z •<br />Zend engine, 17<br />Zend Studio software, 34<br />Zend Web site, 328<br />Zip Files extension, 308<br />zlib extension, 304<br />392 PHP 5 For Dummies<br />Available wherever books are sold. Go to www.dummies.com or call 1-877-762-2974 to order direct<br />Plain-English solutions for everyday challenges<br />HOME &amp; BUSINESS COMPUTER BASICS<br />Also available:<br />Excel 2002 All-in-One Desk<br />Reference For Dummies<br />(0-7645-1794-5)<br />Office XP 9-in-1 Desk<br />Reference For Dummies<br />(0-7645-0819-9)<br />PCs All-in-One Desk<br />Reference For Dummies<br />(0-7645-0791-5)<br />Troubleshooting Your PC<br />For Dummies<br />(0-7645-1669-8)<br />Upgrading &amp; Fixing PCs For<br />Dummies<br />(0-7645-1665-5)<br />Windows XP For Dummies<br />(0-7645-0893-8)<br />Windows XP For Dummies<br />Quick Reference<br />(0-7645-0897-0)<br />Word 2002 For Dummies<br />(0-7645-0839-3)<br />Also available:<br />CD and DVD Recording<br />For Dummies<br />(0-7645-1627-2)<br />Digital Photography<br />All-in-One Desk Reference<br />For Dummies<br />(0-7645-1800-3)<br />eBay For Dummies<br />(0-7645-1642-6)<br />Genealogy Online For<br />Dummies<br />(0-7645-0807-5)<br />Internet All-in-One Desk<br />Reference For Dummies<br />(0-7645-1659-0)<br />Internet For Dummies<br />Quick Reference<br />(0-7645-1645-0)<br />Internet Privacy For Dummies<br />(0-7645-0846-6)<br />Paint Shop Pro For Dummies<br />(0-7645-2440-2)<br />Photo Retouching &amp;<br />R</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=9&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/for-dummies-for-dummies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>Wahai Idolaku Muhammad SAW</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/wahai-idolaku-muhammad-saw/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/wahai-idolaku-muhammad-saw/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 13:53:13 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/?p=7</guid>
		<description><![CDATA[Maha Suci Allah, Yang Membentangkan Kerajaan Alam Semesta dengan Cahaya Kemegahan Nya, maka tegaklah Angkasa Raya Langit dan Bumi sebagai Lambang Kesempurnaan Nya Yang Maha Tunggal dalam Pengaturan, Maha Tunggal dalam Keabadian Maha Tunggal dalam Kesempurnaan, Maka Gemuruhlah Kerajaan Alam Semesta sepanjang masa bertasbih Kehadirat Nya, Menggema Angkasa Raya Mensucikan Nama Nya Yang Maha Luhur [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=7&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Maha Suci Allah, Yang Membentangkan Kerajaan Alam Semesta dengan Cahaya Kemegahan Nya, maka tegaklah Angkasa Raya Langit dan Bumi sebagai Lambang Kesempurnaan Nya Yang Maha Tunggal dalam Pengaturan, Maha Tunggal dalam Keabadian Maha Tunggal dalam Kesempurnaan, Maka Gemuruhlah Kerajaan Alam Semesta sepanjang masa bertasbih Kehadirat Nya, Menggema Angkasa Raya Mensucikan Nama Nya Yang Maha Luhur dari zaman ke zaman, Dicipta Nya keturunan Adam untuk mencapai kehidupan yang Abadi, maka akan musnahlah kerajaan Alam semesta menemui kefanaan, lebur dibawah Kehendak Nya Yang Maha Menentukan, dan tersisalah Benua Kemewahan nan Abadi dan Benua Kehinaan.</p>
<p>Dibangkitkan Nya Pemimpin dari para Duta Nya dimuka Bumi, Sayyidina Muhammad saw, sebaik-baik makhluk dan dipenuhi Nya dengan akhlak yang sempurna, satu-satunya makhluk yang menjadi pemimpin bagi pembawa Cahaya Keridhoan Nya yang Abadi, Maha Suci Allah swt yang menjadikan kecintaan pada Sang Nabi saw merupakan kesempurnaan Iman kepada Nya, sebagaimana sabda beliau saw : ?Tiada Sempurna Iman Kalian, sebelum aku lebih dicintainya dari anak-anaknya, ayahnya dan seluruh manusia? (Shahih Muslim).</p>
<p>Betapa besar kecintaan para sahabat Radhiyallahu?anhum kepada Nabi saw, sebagaimana makna cinta, berarti selalu rindu pada yang dicintainya, selalu ingin bersama kekasihnya, selalu tak ingin berpisah dengan kekasihnya, mencintai segala miliknya, bahkan apa-apa yang disentuh oleh Rasul saw menjadi mulia dimata mereka, sebagaimana riwayat Sa?ib ra, : &#8220;aku diajak oleh bibiku kepada Rasul saw, seraya berkata : Wahai Rasulullah.., keponakanku sakit.., maka Rasul saw mengusap kepalaku dan mendoakan keberkahan padaku, lalu beliau berwudhu, lalu aku meminum air dari bekas wudhu beliau saw, lalu aku berdiri dibelakang beliau dan kulihat Tanda Kenabian beliau saw&#8221; (Shahih Muslim hadits no.2345). Riwayat lain ketika dikatakan pada Ubaidah ra bahwa kami memiliki rambut Rasul saw, maka ia berkata : ?Kalau aku memiliki sehelai rambut beliau saw, maka itu lebih berharga bagiku dari dunia dan segala isinya? (Shahih Bukhari hadits no.168), Diriwayatkan pula bahwa Abu Talhah adalah yang pertama kali mengambil rambut Rasul saw saat beliau saw bercukur (Shahih Bukhari hadits no.169)</p>
<p>Tentunya seorang yang dicintai akan selalu dipuji, tentunya seorang pecinta akan selalu memuji kekasihnya, dan pujian bagi sang nabi saw boleh dimana saja, tidak terkecuali di masjid, karena kecintaan pada Utusan Allah adalah kecintaan kepada Allah, dan beliau saw sendiri yang bersabda bahwa cintailah aku karena cinta kalian kepada Allah, dan dalam hadits beliau bersabda : ?tiada sempurna iman kalian sebelum aku lebih dicintainya dari anak-anaknya, dari ayahnya dan dari seluruh manusia? (Shahih Muslim hadits no.44). bahkan Imam Muslim mengatakan bahwa ?Secara Mutlak seseorang itu tidak disebut beriman kalau ia tak mencintai Nabi saw? (Shahih Muslim Juz 1 hal 67).</p>
<p>Hassan bin Tsabit ra selalu memuji Rasul saw didalam masjid Nabawiy, maka ketika ia sedang asyik bernasyid (nasyid, syair, qasidah, sama saja dalam bahasa arab yaitu puji-pujian pada Allah dan Rasul saw), ia sedang melantunkan syair puji-pujian pada Rasul saw, tiba-tiba Umar ra mendelikkan matanya kepada Hassan, maka berkatalah Hassan bin tsabit ra : ?Aku sudah memuji beliau (saw) ditempat ini (masjid) dan saat itu ada yang lebih mulia dari engkau (Rasul saw melihatnya dan tidak melarang)?, lalu berkata pula Hassan kepada Abu hurairah ra yang juga ada bersama mereka : ?Demi Allah bukankah Rasul saw telah berdoa untukku : WAHAI ALLAH BANTULAH IA (hassan ketika membaca syair dihadapan Rasul saw) DENGAN JIBRIL???. Maka Abu Hurairah berkata : ?Betul?, maka Umar ra pun tak lagi berani mengganggunya. (Shahih Bukhari hadits no.3040). riwayat yang sama pada Shahih Muslim hadits no.2485.</p>
<p>Maka jelaslah sudah bahwa Rasul saw tidak melarang puji-pujian atas Allah dan Rasul Nya di masjid, bahkan diriwayatkan bahwa Rasul saw menaruh sebuah Mimbar khusus untuk Hassan bin Tsabit ra di Masjid, untuk ia membaca Syair memuji Allah dan Rasul saw (Mustadrak Alaa Shahihain hadits no.6058, 6059), dan ketika ada orang yg tak menyukai Hassan, maka marahlah Ummulmukminin Aisyah ra, seraya berkata : ?Jangan kalian menghina Hassan, karena ia selalu memuji Rasulullah saw? (Mustadrak Alaa Shahihain hadits no.6063), berkata Imam Hakim bahwa ucapan ini shahih memenuhi syarat Shahih Bukhari dan Muslim.</p>
<p>Fahamlah kita bahwa Puji-Pujian pada Rasul saw, yang diantaranya Qasidah, Maulid dll merupakan hal yang dimuliakan oleh Rasul saw, bahkan Sayyidatuna Aisyah ra marah ketika ada orang yang menghina orang yang memuji Rasul saw, maka ketika di akhir zaman ini muncul kelompok yang mengharamkan puji-pujian pada Rasul saw dan nasyid/qasidah di masjid, ini menunjukkan kesempitan pemahaman mereka dalam Syariah Islamiyyah, memang betul ada hadits Rasul saw yang melarang membaca syair-syair di masjid, namun itu adalah syair-syair keduniawian yang membuat ummat lupa kepada Allah swt, bukanlah syair pujian atas Allah dan Rasul saw yang memberi semangat kepada ummat untuk semakin taat kepada Allah swt.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=7&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/wahai-idolaku-muhammad-saw/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>BID’AH</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/bid%e2%80%99ah/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/bid%e2%80%99ah/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 13:47:44 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/?p=6</guid>
		<description><![CDATA[I. Nabi saw memperbolehkan berbuat bid’ah hasanah. Nabi saw memperbolehkan kita melakukan Bid’ah hasanah selama hal itu baik dan tidak menentang syariah, sebagaimana sabda beliau saw: “Barangsiapa membuat buat hal baru yang baik dalam islam, maka baginya pahalanya dan pahala orang yang mengikutinya dan tak berkurang sedikitpun dari pahalanya, dan barangsiapa membuat-buat hal baru yg [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=6&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>I. Nabi saw memperbolehkan berbuat bid’ah hasanah.</strong><br />
Nabi saw memperbolehkan kita melakukan Bid’ah hasanah selama hal itu baik dan tidak menentang syariah, sebagaimana sabda beliau saw: “Barangsiapa membuat buat hal baru yang baik dalam islam, maka baginya pahalanya dan pahala orang yang mengikutinya dan tak berkurang sedikitpun dari pahalanya, dan barangsiapa membuat-buat hal baru yg buruk dalam islam, maka baginya dosanya dan dosa orang yg mengikutinya dan tak dikurangkan sedikitpun dari dosanya” (Shahih Muslim hadits no.1017, demikian pula diriwayatkan pada Shahih Ibn Khuzaimah, Sunan Baihaqi Alkubra, Sunan Addarimiy, Shahih Ibn Hibban dan banyak lagi). Hadits ini menjelaskan makna Bid’ah hasanah dan Bid&#8217;ah dhalalah.</p>
<p>Perhatikan hadits beliau saw, bukankah beliau saw menganjurkan?, maksudnya bila kalian mempunyai suatu pendapat atau gagasan baru yg membuat kebaikan atas islam maka perbuatlah.., alangkah indahnya bimbingan Nabi saw yg tidak mencekik ummat, beliau saw tahu bahwa ummatnya bukan hidup untuk 10 atau 100 tahun, tapi ribuan tahun akan berlanjut dan akan muncul kemajuan zaman, modernisasi, kematian ulama, merajalela kemaksiatan, maka tentunya pastilah diperlukan hal-hal yg baru demi menjaga muslimin lebih terjaga dalam kemuliaan, demikianlah bentuk kesempurnaan agama ini, yg tetap akan bisa dipakai hingga akhir zaman, inilah makna ayat : <strong>“ALYAUMA AKMALTU LAKUM DIINUKUM..dst</strong>, “hari ini Kusempurnakan untuk kalian agama kalian, kusempurnakan pula kenikmatan bagi kalian, dan kuridhoi islam sebagai agama kalian”, maksudnya semua ajaran telah sempurna, tak perlu lagi ada pendapat lain demi memperbaiki agama ini, semua hal yg baru selama itu baik sudah masuk dalam kategori syariah dan sudah direstui oleh Allah dan rasul Nya, alangkah sempurnanya islam.</p>
<p>Namun tentunya bukan membuat agama baru atau syariat baru yg bertentangan dengan syariah dan sunnah Rasul saw, atau menghalalkan apa-apa yg sudah diharamkan oleh Rasul saw atau sebaliknya, inilah makna hadits beliau saw : “Barangsiapa yg membuat buat hal baru yg berupa keburukan&#8230;dst”, inilah yg disebut Bid’ah Dhalalah. Beliau saw telah memahami itu semua, bahwa kelak zaman akan berkembang, maka beliau saw memperbolehkannya (hal yg baru berupa kebaikan), menganjurkannya dan menyemangati kita untuk memperbuatnya, agar ummat tidak tercekik dengan hal yg ada dizaman kehidupan beliau saw saja, dan beliau saw telah pula mengingatkan agar jangan membuat buat hal yg buruk (Bid’ah dhalalah).</p>
<p>Mengenai pendapat yg mengatakan bahwa hadits ini adalah khusus untuk sedekah saja, maka tentu ini adalah pendapat mereka yg dangkal dalam pemahaman syariah, karena hadits diatas jelas-jelas tak menyebutkan pembatasan hanya untuk sedekah saja, terbukti dengan perbuatan bid’ah hasanah oleh para Sahabat dan Tabi’in.</p>
<p><strong>II. Siapakah yg pertama memulai Bid’ah hasanah setelah wafatnya Rasul saw?</strong><br />
Ketika terjadi pembunuhan besar-besaran atas para sahabat (Ahlul yamaamah) yg mereka itu para Huffadh (yg hafal) Alqur’an dan Ahli Alqur’an di zaman Khalifah Abubakar Asshiddiq ra, berkata Abubakar Ashiddiq ra kepada Zeyd bin Tsabit ra : “Sungguh Umar (ra) telah datang kepadaku dan melaporkan pembunuhan atas ahlulyamaamah dan ditakutkan pembunuhan akan terus terjadi pada para Ahlulqur’an, lalu ia menyarankan agar Aku (Abubakar Asshiddiq ra) mengumpulkan dan menulis Alqur’an, aku berkata : Bagaimana aku berbuat suatu hal yg tidak diperbuat oleh Rasulullah..??, maka Umar berkata padaku bahwa Demi Allah ini adalah demi kebaikan dan merupakan kebaikan, dan ia terus meyakinkanku sampai Allah menjernihkan dadaku dan aku setuju dan kini aku sependapat dengan Umar, dan engkau (zeyd) adalah pemuda, cerdas, dan kami tak menuduhmu (kau tak pernah berbuat jahat), kau telah mencatat wahyu, dan sekarang ikutilah dan kumpulkanlah Alqur’an dan tulislah Alqur’an..!” berkata Zeyd : “Demi Allah sungguh bagiku diperintah memindahkan sebuah gunung daripada gunung-gunung tidak seberat perintahmu padaku untuk mengumpulkan Alqur’an, bagaimana kalian berdua berbuat sesuatu yg tak diperbuat oleh Rasulullah saw??”, maka Abubakar ra mengatakannya bahwa hal itu adalah kebaikan, hingga iapun meyakinkanku sampai Allah menjernihkan dadaku dan aku setuju dan kini aku sependapat dengan mereka berdua dan aku mulai mengumpulkan Alqur’an”. (Shahih Bukhari hadits no.4402 dan 6768).</p>
<p>Nah saudaraku, bila kita perhatikan konteks diatas Abubakar shiddiq ra mengakui dengan ucapannya : “sampai Allah menjernihkan dadaku dan aku setuju dan kini aku sependapat dengan Umar”, hatinya jernih menerima hal yg baru (bid’ah hasanah) yaitu mengumpulkan Alqur’an, karena sebelumnya alqur’an belum dikumpulkan menjadi satu buku, tapi terpisah-pisah di hafalan sahabat, ada yg tertulis di kulit onta, di tembok, dihafal dll, ini adalah Bid’ah hasanah, justru mereka berdualah yg memulainya.</p>
<p>Kita perhatikan hadits yg dijadikan dalil menafikan (menghilangkan) Bid’ah hasanah mengenai semua bid’ah adalah kesesatan, diriwayatkan bahwa Rasul saw selepas melakukan shalat subuh beliau saw menghadap kami dan menyampaikan ceramah yg membuat hati berguncang, dan membuat airmata mengalir.., maka kami berkata : “Wahai Rasulullah.. seakan-akan ini adalah wasiat untuk perpisahan…, maka beri wasiatlah kami..” maka rasul saw bersabda : “Kuwasiatkan kalian untuk bertakwa kepada Allah, mendengarkan dan taatlah walaupun kalian dipimpin oleh seorang Budak afrika, sungguh diantara kalian yg berumur panjang akan melihat sangat banyak ikhtilaf perbedaan pendapat, maka berpegang teguhlah pada sunnahku dan sunnah khulafa’urrasyidin yg mereka itu pembawa petunjuk, gigitlah kuat kuat dengan geraham kalian (suatu kiasan untuk kesungguhan), dan hati-hatilah dengan hal-hal yg baru, sungguh semua yg Bid&#8217;ah itu adalah kesesatan”. (Mustadrak Alasshahihain hadits no.329).</p>
<p>Jelaslah bahwa Rasul saw menjelaskan pada kita untuk mengikuti sunnah beliau dan sunnah khulafa’urrasyidin, dan sunnah beliau saw telah memperbolehkan hal yg baru selama itu baik dan tak melanggar syariah, dan sunnah khulafa’urrasyidin adalah anda lihat sendiri bagaimana Abubakar shiddiq ra dan Umar bin Khattab ra menyetujui bahkan menganjurkan, bahkan memerintahkan hal yg baru, yg tidak dilakukan oleh Rasul saw yaitu pembukuan Alqur’an, lalu pula selesai penulisannya dimasa Khalifah Utsman bin Affan ra, dengan persetujuan dan kehadiran Ali bin Abi Thalib kw.</p>
<p>Nah.. sempurnalah sudah keempat makhluk termulia di ummat ini, khulafa’urrasyidin melakukan bid’ah hasanah, Abubakar shiddiq ra dimasa kekhalifahannya memerintahkan pengumpulan Alqur’an, lalu kemudian Umar bin Khattab ra pula dimasa kekhalifahannya memerintahkan tarawih berjamaah dan seraya berkata : “Inilah sebaik-baik Bid’ah!”(Shahih Bukhari hadits no.1906) lalu pula selesai penulisan Alqur’an dimasa Khalifah Utsman bin Affan ra hingga Alqur’an kini dikenal dengan nama Mushaf Utsmaniy, dan Ali bin Abi Thalib kw menghadiri dan menyetujui hal itu. Demikian pula hal yg dibuat-buat tanpa perintah Rasul saw adalah dua kali adzan di Shalat Jumat, tidak pernah dilakukan dimasa Rasul saw, tidak dimasa Khalifah Abubakar shiddiq ra, tidak pula dimasa Umar bin khattab ra dan baru dilakukan dimasa Utsman bn Affan ra, dan diteruskan hingga kini (Shahih Bulkhari hadits no.873).</p>
<p>Siapakah yg salah dan tertuduh?, siapakah yg lebih mengerti larangan Bid’ah?, adakah pendapat mengatakan bahwa keempat Khulafa’urrasyidin ini tak faham makna Bid’ah?</p>
<p><strong>III. Bid’ah Dhalalah</strong><br />
Jelaslah sudah bahwa mereka yg menolak bid’ah hasanah inilah yg termasuk pada golongan Bid’ah dhalalah, dan Bid’ah dhalalah ini banyak jenisnya, seperti penafikan sunnah, penolakan ucapan sahabat, penolakan pendapat Khulafa’urrasyidin, nah…diantaranya adalah penolakan atas hal baru selama itu baik dan tak melanggar syariah, karena hal ini sudah diperbolehkan oleh Rasul saw dan dilakukan oleh Khulafa’urrasyidin, dan Rasul saw telah jelas-jelas memberitahukan bahwa akan muncul banyak ikhtilaf, berpeganglah pada Sunnahku dan Sunnah Khulafa’urrasyidin, bagaimana Sunnah Rasul saw?, beliau saw membolehkan Bid’ah hasanah, bagaimana sunnah Khulafa’urrasyidin?, mereka melakukan Bid’ah hasanah, maka penolakan atas hal inilah yg merupakan Bid’ah dhalalah, hal yg telah diperingatkan oleh Rasul saw.</p>
<p>Bila kita menafikan (meniadakan) adanya Bid’ah hasanah, maka kita telah menafikan dan membid’ahkan Kitab Al-Quran dan Kitab Hadits yang menjadi panduan ajaran pokok Agama Islam karena kedua kitab tersebut (Al-Quran dan Hadits) tidak ada perintah Rasulullah saw untuk membukukannya dalam satu kitab masing-masing, melainkan hal itu merupakan ijma/kesepakatan pendapat para Sahabat Radhiyallahu’anhum dan hal ini dilakukan setelah Rasulullah saw wafat.</p>
<p>Buku hadits seperti Shahih Bukhari, shahih Muslim dll inipun tak pernah ada perintah Rasul saw untuk membukukannya, tak pula Khulafa’urrasyidin memerintahkan menulisnya, namun para tabi’in mulai menulis hadits Rasul saw. Begitu pula Ilmu Musthalahulhadits, Nahwu, sharaf, dan lain-lain sehingga kita dapat memahami kedudukan derajat hadits, ini semua adalah perbuatan Bid’ah namun Bid’ah Hasanah. Demikian pula ucapan “Radhiyallahu’anhu” atas sahabat, tidak pernah diajarkan oleh Rasulullah saw, tidak pula oleh sahabat, walaupun itu di sebut dalam Al-Quran bahwa mereka para sahabat itu diridhoi Allah, namun tak ada dalam Ayat atau hadits Rasul saw memerintahkan untuk mengucapkan ucapan itu untuk sahabatnya, namun karena kecintaan para Tabi’in pada Sahabat, maka mereka menambahinya dengan ucapan tersebut. Dan ini merupakan Bid’ah Hasanah dengan dalil Hadits di atas, Lalu muncul pula kini Al-Quran yang di kasetkan, di CD kan, Program Al-Quran di handphone, Al-Quran yang diterjemahkan, ini semua adalah Bid’ah hasanah. Bid’ah yang baik yang berfaedah dan untuk tujuan kemaslahatan muslimin, karena dengan adanya Bid’ah hasanah di atas maka semakin mudah bagi kita untuk mempelajari Al-Quran, untuk selalu membaca Al-Quran, bahkan untuk menghafal Al-Quran dan tidak ada yang memungkirinya.</p>
<p>Sekarang kalau kita menarik mundur kebelakang sejarah Islam, bila Al-Quran tidak dibukukan oleh para Sahabat ra, apa sekiranya yang terjadi pada perkembangan sejarah Islam ? Al-Quran masih bertebaran di tembok-tembok, di kulit onta, hafalan para Sahabat ra yang hanya sebagian dituliskan, maka akan muncul beribu-ribu Versi Al-Quran di zaman sekarang, karena semua orang akan mengumpulkan dan membukukannya, yang masing-masing dengan riwayatnya sendiri, maka hancurlah Al-Quran dan hancurlah Islam. Namun dengan adanya Bid’ah Hasanah, sekarang kita masih mengenal Al-Quran secara utuh dan dengan adanya Bid’ah Hasanah ini pula kita masih mengenal Hadits-hadits Rasulullah saw, maka jadilah Islam ini kokoh dan Abadi, jelaslah sudah sabda Rasul saw yg telah membolehkannya, beliau saw telah mengetahui dengan jelas bahwa hal hal baru yg berupa kebaikan (Bid’ah hasanah), mesti dimunculkan kelak, dan beliau saw telah melarang hal-hal baru yg berupa keburukan (Bid’ah dhalalah).</p>
<p>Saudara-saudaraku, jernihkan hatimu menerima ini semua, ingatlah ucapan Amirulmukminin pertama ini, ketahuilah ucapan ucapannya adalah Mutiara Alqur’an, sosok agung Abubakar Ashiddiq ra berkata mengenai Bid’ah hasanah : “sampai Allah menjernihkan dadaku dan aku setuju dan kini aku sependapat dengan Umar”.</p>
<p>Lalu berkata pula Zeyd bin haritsah ra :”..bagaimana kalian berdua (Abubakar dan Umar) berbuat sesuatu yg tak diperbuat oleh Rasulullah saw??, maka Abubakar ra mengatakannya bahwa hal itu adalah kebaikan, hingga iapun(Abubakar ra) meyakinkanku (Zeyd) sampai Allah menjernihkan dadaku dan aku setuju dan kini aku sependapat dengan mereka berdua”.</p>
<p>Maka kuhimbau saudara-saudaraku muslimin yg kumuliakan, hati yg jernih menerima hal-hal baru yg baik adalah hati yg sehati dengan Abubakar shiddiq ra, hati Umar bin Khattab ra, hati Zeyd bin haritsah ra, hati para sahabat, yaitu hati yg dijernihkan Allah swt, Dan curigalah pada dirimu bila kau temukan dirimu mengingkari hal ini, maka barangkali hatimu belum dijernihkan Allah, karena tak mau sependapat dengan mereka, belum setuju dengan pendapat mereka, masih menolak bid’ah hasanah, dan Rasul saw sudah mengingatkanmu bahwa akan terjadi banyak ikhtilaf, dan peganglah perbuatanku dan perbuatan khulafa’urrasyidin, gigit dengan geraham yg maksudnya berpeganglah erat-erat pada tuntunanku dan tuntunan mereka.</p>
<p>Allah menjernihkan sanubariku dan sanubari kalian hingga sehati dan sependapat dengan Abubakar Asshiddiq ra, Umar bin Khattab ra, Utsman bin Affan ra, Ali bin Abi Thalib kw dan seluruh sahabat.. amiin.<br />
<strong>IV. Pendapat para Imam dan Muhadditsin mengenai Bid’ah</strong></p>
<p>1. Al Hafidh Al Muhaddits Al Imam Muhammad bin Idris Assyafii rahimahullah (Imam Syafii)<br />
Berkata Imam Syafii bahwa bid’ah terbagi dua, yaitu bid’ah mahmudah (terpuji) dan bid’ah madzmumah (tercela), maka yg sejalan dengan sunnah maka ia terpuji, dan yg tidak selaras dengan sunnah adalah tercela, beliau berdalil dengan ucapan Umar bin Khattab ra mengenai shalat tarawih : “inilah sebaik baik bid’ah”. (Tafsir Imam Qurtubiy juz 2 hal 86-87)</p>
<p>2. Al Imam Al Hafidh Muhammad bin Ahmad Al Qurtubiy rahimahullah<br />
“Menanggapi ucapan ini (ucapan Imam Syafii), maka kukatakan (Imam Qurtubi berkata) bahwa makna hadits Nabi saw yg berbunyi : “seburuk-buruk permasalahan adalah hal yg baru, dan semua Bid’ah adalah dhalalah” (wa syarrul umuuri muhdatsaatuha wa kullu bid’atin dhalaalah), yg dimaksud adalah hal-hal yg tidak sejalan dengan Alqur’an dan Sunnah Rasul saw, atau perbuatan Sahabat radhiyallahu ‘anhum, sungguh telah diperjelas mengenai hal ini oleh hadits lainnya : “Barangsiapa membuat buat hal baru yg baik dalam islam, maka baginya pahalanya dan pahala orang yg mengikutinya dan tak berkurang sedikitpun dari pahalanya, dan barangsiapa membuat buat hal baru yg buruk dalam islam, maka baginya dosanya dan dosa orang yg mengikutinya” (Shahih Muslim hadits no.1017) dan hadits ini merupakan inti penjelasan mengenai bid’ah yg baik dan bid’ah yg sesat”. (Tafsir Imam Qurtubiy juz 2 hal 87)</p>
<p>3. Al Muhaddits Al Hafidh Al Imam Abu Zakariya Yahya bin Syaraf Annawawiy rahimahullah (Imam Nawawi)<br />
“Penjelasan mengenai hadits : “Barangsiapa membuat-buat hal baru yg baik dalam islam, maka baginya pahalanya dan pahala orang yg mengikutinya dan tak berkurang sedikitpun dari pahalanya, dan barangsiapa membuat buat hal baru yg dosanya”, hadits ini merupakan anjuran untuk membuat kebiasaan kebiasaan yg baik, dan ancaman untuk membuat kebiasaan yg buruk, dan pada hadits ini terdapat pengecualian dari sabda beliau saw : “semua yg baru adalah Bid’ah, dan semua yg Bid’ah adalah sesat”, sungguh yg dimaksudkan adalah hal baru yg buruk dan Bid’ah yg tercela”. (Syarh Annawawi ‘ala Shahih Muslim juz 7 hal 104-105)</p>
<p>Dan berkata pula Imam Nawawi bahwa Ulama membagi bid’ah menjadi 5, yaitu Bid’ah yg wajib, Bid’ah yg mandub, bid’ah yg mubah, bid’ah yg makruh dan bid’ah yg haram. Bid’ah yg wajib contohnya adalah mencantumkan dalil-dalil pada ucapan ucapan yg menentang kemungkaran, contoh bid’ah yg mandub (mendapat pahala bila dilakukan dan tak mendapat dosa bila ditinggalkan) adalah membuat buku buku ilmu syariah, membangun majelis taklim dan pesantren, dan Bid;ah yg Mubah adalah bermacam-macam dari jenis makanan, dan Bid’ah makruh dan haram sudah jelas diketahui, demikianlah makna pengecualian dan kekhususan dari makna yg umum, sebagaimana ucapan Umar ra atas jamaah tarawih bahwa inilah sebaik2 bid’ah”. (Syarh Imam Nawawi ala shahih Muslim Juz 6 hal 154-155)</p>
<p>4. Al Hafidh AL Muhaddits Al Imam Jalaluddin Abdurrahman Assuyuthiy rahimahullah<br />
Mengenai hadits “Bid’ah Dhalalah” ini bermakna “Aammun makhsush”, (sesuatu yg umum yg ada pengecualiannya), seperti firman Allah : “… yg Menghancurkan segala sesuatu” (QS Al Ahqaf 25) dan kenyataannya tidak segalanya hancur, (*atau pula ayat : “Sungguh telah kupastikan ketentuanku untuk memenuhi jahannam dengan jin dan manusia keseluruhannya” QS Assajdah-13), dan pada kenyataannya bukan semua manusia masuk neraka, tapi ayat itu bukan bermakna keseluruhan tapi bermakna seluruh musyrikin dan orang dhalim.pen) atau hadits : “aku dan hari kiamat bagaikan kedua jari ini” (dan kenyataannya kiamat masih ribuan tahun setelah wafatnya Rasul saw) (Syarh Assuyuthiy Juz 3 hal 189).</p>
<p>Maka bila muncul pemahaman di akhir zaman yg bertentangan dengan pemahaman para Muhaddits maka mestilah kita berhati-hati darimanakah ilmu mereka?, berdasarkan apa pemahaman mereka?, atau seorang yg disebut imam padahal ia tak mencapai derajat hafidh atau muhaddits?, atau hanya ucapan orang yg tak punya sanad, hanya menukil-menukil hadits dan mentakwilkan semaunya tanpa memperdulikan fatwa-fatwa para Imam?</p>
<p>Walillahittaufiq</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/6/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/6/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=6&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/bid%e2%80%99ah/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>Kehancuran Sunnah</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/kehancuran-sunnah/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/kehancuran-sunnah/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 13:43:13 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/?p=5</guid>
		<description><![CDATA[Maha Suci Allah Yang Maha Menguasai setiap sudut Angkasa Raya semesta yang Tunggal adalah milik Nya, Maha Suci Allah Yang Maha Tunggal menghamparkan Jagad Raya dengan kemegahan dan kesempurnaan, Maha Suci Allah Yang Maha Abadi dalam Kesempurnaan dan Keindahan Nya,Segala Puji Bagi Allah Yang Menyemarakkan Angkasa Raya dengan cahaya Keagungan Nya, Segala Puji Bagi Allah [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=5&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Maha Suci Allah Yang Maha Menguasai setiap sudut Angkasa Raya semesta yang Tunggal adalah milik Nya, Maha Suci Allah Yang Maha Tunggal menghamparkan Jagad Raya dengan kemegahan dan kesempurnaan, Maha Suci Allah Yang Maha Abadi dalam Kesempurnaan dan Keindahan Nya,Segala Puji Bagi Allah Yang Menyemarakkan Angkasa Raya dengan cahaya Keagungan Nya, Segala Puji Bagi Allah Yang Menampilkan keajaiban ciptaan Nya di segenap langit dan bumi, Allah.. Nama Yang Maha Abadi dan Tunggal dalam Kekuasaan, Allah.. Nama Yang Maha Abadi dan Tunggal dalam Menentukan, Gema kewibawaan Nya menundukkan seluruh Alam Semesta, ketika kekuatan Nya ditampilkan Nya maka runtuhlah benteng kekuatan hamba Nya, direnggut Nya kekuasaan Raja penguasa dengan kematian.., mereka terenggut dari singgasana mulia untuk berlutut ketakutan mempertanggungjawabkan setiap nafasnya,</p>
<p>Telah Kuciptakan engkau dari ketiadaan, kutumbuhkan sel dirimu pada tubuh ayahmu, lalu kubenamkan sel dirimu di rahim ibumu, lalu Aku Mengasuhmu siang dan malam di rahim ibumu dalam kesendirian, hingga terangkailah 40 hari sebagai air mani, 40 hari kemudian sebagai gumpalan darah, 40 hari kemudian menjadi gumpalan daging, 40 hari kemudian kupecah-pecah bentuk tubuhmu dengan panca indera, lalu kuhembuskan padamu ruh.. (rujuk shahih Bukhari hadits no.3036, 3154, 6221, 7016).</p>
<p>Lalu kubuat kau lahir ke muka bumiku, hidup, makan dan minum dari rizki yang kuciptakan, engkau bertebaran diatas bumiku, kusiapkan untukmu nafkahmu, ayah ibu yang menyayangimu, teman-teman yang menemanimu, pohon-pohon yang menaungimu, kubuat kau melihat dan mendengar, kuciptakan dua kaki agar kau bisa berjalan, kujadikan milyaran sel tubuhmu taat pada keinginanmu?</p>
<p>Akan datang waktu Aku akan memanggilmu, Kuperintah Kau untuk menghadap Ku dengan perintah yang tak mampu kau tolak, kau harus berpisah dengan penglihatanmu, pendengaranmu, hartamu, kerabatmu, kehidupanmu, karena itu semua memang bukan milikmu, itu semua adalah Milik Ku, dan dirimu pun sepenuhnya adalah Milik Ku..</p>
<p>?Apakah manusia tidak memandang bahwa sungguh kami menciptakannya dari air mani, maka kemudian ia hidup dan mendebat (menentang dan membangkang) pada kami? (QS Yaasiin 77). ?Sungguh mereka melihatnya jauh (hari kiamat) dan kami melihatnya (hari kiamat) sangat dekat, hari dimana langit luluh mencair, dan jadilah gunung-gunung bagai debu berserakan, maka saat itu para bunda yang mengasuh bayinya tak lagi memperdulikan bayi yang diasuhnya, ketika diperlihatkan atas mereka, hari saat para pendosa bermaksud menukar azab dengan anak-anaknya, atau menukar azab itu dengan suami atau istrinya, atau dengan kelompok teman-temannya yang dahulu bersamanya, atau menukar azab dengan seluruh penduduk di bumi asal ia selamat sendiri, sungguh itu sia-sia.., namun itulah Api yang bergejolak, (Api yang demikian dahsyatnya) Mencerai beraikan tulang rusuk satu sama lain, Bergemuruh memanggil mereka yang berbuat jahat dan berpaling dari kebenaran, (QS Alma?arij 1-17).</p>
<p>Saudara-saudaraku yang kumuliakan, sungguh musuh-musuh islam terus mengobarkan api kegelapan yang menghanguskan sunnah Muhammad saw, alangkah mengejutkannya ketika justru dirimu terlibat dalam penghancuran sunnah Nabi kita saw, kita jadikan bibir ini terlibat menghancurkan sunnah Nabi kita saw, kita jadikan akal logika kita untuk merubuhkan sunnah Nabi kita saw, Saudara-saudaraku yang kumuliakan, sungguh Poligami adalah salah satu dari ajaran Nabi Kita Muhammad saw, dan telah berjaya diatas ummat ini berabad-abad lamanya, namun hari-hari ini muncullah musuh-musuh islam yang mengobarkan api itu, maka kitapun bermunculan pula untuk mendukung mereka menghancurkan ajaran Nabi kita saw, Tak ada ikhtilaf oleh seluruh Ulama, Muhaddistin, para Imam, sahabat, yang punya satu pendapatpun melarang poligami, hanya muncul di zaman kita ini yang mengingkari ajaran Nabi kita saw, Poligami diperbolehkan tanpa syarat apapun selain syarat akad nikah biasa..,</p>
<p>Sungguh.. kita ini diperintahkan menyembah Allah dan bukan menyembah logika, apakah kita harus menjadikan hukum Nya itu dibawah logika kita?, kita tak perlu menjadikan hikmah yang tersimpan dalam poligami atau sunnah lainnya sebagai syarat untuk membenarkannya, lalu bila hikmahnya belum kita temukan maka kita kufur dan menolaknya, kita menyembah Nya dan sungguh Dzat Nya swt tak terpecahkan oleh Logika, karena yang paling gaib adalah Dia swt, maka bila kita menolak hukum hanya karena tak masuk akal, maka kita sudah menentang Nya, menyembah akal kita dan tidak beriman kepada Nya dan tidak pula mengakui Muhammad saw sebagai utusan Nya, karena ada hal yang kita akui merupakan kesalahan dari ajaran sang Nabi saw,</p>
<p>Sungguh.. Poligami ini menjadi momok yang mengerikan bagi kaum istri, mengapa?, bukankah Allah Yang Maha menentukan segala-galanya, dan selama ini semua orang tahu bahwa poligami adalah boleh dalam islam, namun barangkali tidak 1 dari 1000 suami yang melakukan poligami walaupun itu diperbolehkan, lalu apa yang mereka risaukan?, seakan mereka sudah tidak punya tuhan untuk dijadikan sandaran perlindungan, Betul, banyak kaum istri yang belum mampu bersabar dalam hal ini, namun belum mampu bukanlah menginkari, sama halnya dengan orang yang tak punya uang untuk Umrah dan haji yang sunnah (sudah melakukan yang wajibnya), maka apakah kita mengatakan haji sunnah itu batil dan dilarang?, apa hak kita mengatakan batil pada sunnah Nabi saw?, jauh beda antara yang tidak mampu dengan yang mengingkari,</p>
<p>Betul.. poligami banyak diselewengkan oleh para suami, hingga dijadikan alat pengumbar syahwat, merebut kekayaan, menyombongkan diri, berkhianat pada istri, dan contoh lainnya, dan banyak pula diselewengkan oleh istri muda untuk merebut harta atau lainnya, namun itu semua adalah oknum, dan penyelewengan itu terjadi dalam segala hal dan bukan hanya dalam poligami, contohnya dalam pernikahan monogami pun demikian, banyak terdapat penyelewengan dalam pernikahan yang demi keduniawian atau demi kelicikan, atau demi syahwat dan lainnya, demikian pula pada shalat, bisa saja diselewengkan dengan untuk mencari perhatian misalnya, atau agar dianggap shalih, atau lainnya, demikian pula puasa, haji, zakat dan lainnya, penyelewengan mestilah ada, dan penyelewengan oknum tak dapat menafikan (menghapuskan) suatu ajaran syariah, kesalahan adalah pada oknum dan bukan pada hukum,</p>
<p>Tak mustahil sebentar lagi akan bermunculan pula pendapat mengingkari hal-hal yang fardhu, tak mustahil pula pendapat kelak mengingkari puasa, kenapa harus menahan lapar?, atau mengingkari haji, kenapa harus tawaf dan sa?i?, kenapa harus melempar batu di Mina dengan 7 batu selama 3 hari berturut-turut..?, kenapa harus berpanas-panas terik berdesak-desakan bahkan bisa mati terinjak injak hanya sekedar untuk melempar batu-batu kerikil?, bukankah ini merusak kulit?, bisa pula tertular wabah batuk, atau penyakit-penyakit yang dibawa dari seluruh dunia..?, akhirnya kita akan terjebak pada puncak kekufuran, yaitu.. : kenapa aku menyembah sesuatu yang tak terlihat.., tak terdengar, tak terasa, kenapa harus menyembunyikan diri Nya, kenapa tak tunjukkan..?</p>
<p>Maka jadilah logika kita menjadi tuhan kita, runtuhlah seluruh kemuliaan iman dan tauhid dari sanubari kita, sirnalah seluruh amal ibadah kita, dalam jurang kemurtadan yang menuju kehinaan yang abadi.. diawali dari hembusan penolakan pada Poligami, yang kita turut berperan serta untuk menghancurkan sunnah Nabi saw, ketika dipadang Mahsyar kelak.., ketika terdengar seruan.., Fulan bin fulan maju kehadapan Allah..!, maka satu wajah tertunduk maju.. maka Allah swt berkata : Engkau.., Engkau.., Engkau kah yang terlibat menghancurkan sunnah Nabi Ku?, Engkau? Engkau.. engkau kah yang turut mencari 1000 dalil agar sunnah Nabi Ku diubah..?</p>
<p>Saudaraku, adakah kau calonkan dirimu sebagai pengkhianat Nabimu?, Naudzubillah dari hal ini.., saudara-saudaraku bangkitlah.., saudari-saudariku bangunlah.. bela sunnah Nabimu, mereka sedang menghanguskan bendera sunnah Nabimu saw, mereka menginjak panji sunnahnya saw, siapa mereka?, mereka saudara-saudaramu, kerabatmu, tetanggamu, teman-temanmu.. Saudaraku bangkitlah.. jangan berpangku tangan atas penghinaan pada sunnah Nabimu saw, tunjukkan baktimu pada nabi kita saw.</p>
<p>Katakanlah : <strong>?AKU MENCINTAI SUNNAH NABIKU MUHAMMAD SAW, WALAUPUN SELURUH BARAT DAN TIMUR MENGANGGAPNYA BURUK, DIMATAKU TETAP SUNNAH NABIKU JAUH LEBIH AGUNG DIATAS SEMILYAR LOGIKA KUFFAR..! AKU BERIDOLAKAN NABIKU MUHAMMAD SAW, DAN BAGIKU SEMUA SUNNAH NYA INDAH, DAN TAK ADA YANG LEBIH INDAH DIMATAKU SELAIN SUNNAH NABIKU SAW..!&#8221;</strong>,</p>
<p>Dan ketika namamu terpanggil bertemu dengan nabimu Muhammad saw, jelanglah wajahnya dengan gembira, katakanlah : <strong>?WAHAI KEKASIHKU, WAHAI NABIKU, WAHAI KEBANGGAANKU, AKU DIKELOMPOK PEMBELA SUNNAHMU SAAT BANYAK ORANG MENGINKARINYA..!?</strong></p>
<p>Sabda Rasulullah saw : ?Barangsiapa yang bepaling dari sunnahku maka ia bukan dari golonganku? (shahih Bukhari hadits no. 4776, shahih Muslim hadits no.1401), ?Barangsiapa yang menghidupkan sunnahku maka sungguh ia mencintaiku, dan yang mencintaiku akan bersamaku di sorga? (HR Tirmidziy) ?Barangsiapa yang berpegang pada sunnahku dimasa rusaknya ummatku, maka baginya pahala 100 orang yang mati syahid? (Azzuhdulkabir hadits no.207).</p>
<p>Dalam kegelapan di lobang kubur yang panas dan sempit terdengarlah rintihan memelas? Gusti? kasihanilah aku.. yang telah lancang menolak kemuliaan-kemuliaan yang diajarkan Nabi Mu saw.. Gusti? adakah kesalahan lebih besar kuperbuat daripada menentang sunnah Nabi Mu.. Gusti? aku telah berani mengangkat akalku diatas hukum Mu dan menganggap buruk apa-apa yang kau muliakan, Gusti? ada apakah pada diriku ini.. Gusti.. hanya engkaulah yang memiliki diriku sepenuhnya, maafkan hamba, kasihani hamba..</p>
<p>?Mereka beriman kepada Rasul dengan apa-apa yang diturunkan kepadanya dari Tuhannya dan juga orang-orang mukmin, kesemuanya beriman kepada Allah dan malaikat-malaikat Nya, kitab-kitab Nya, dan Rasul-Rasul Nya, (mereka berkata), kami tidak membeda-bedakan (mendustakan) diantara Rasul-Rasul Nya, dan mereka berkata : Kami dengar maka kami taat, maka pengampunan Mu wahai Tuhan Kami dan hanya kepada Mu lah kami kembali, tiadalah Allah memaksa seseorang kecuali menurut kemampuannya, maka baginya pahala semua yang ia kerjakan dan baginya dosa yang dikerjakannya, Wahai Tuhan Kami Jangan Kau siksa kami bila kami lupa atau kami salah, Wahai Tuhan Kami jangan Kau bebani kami beban berat sebagai beban yang telah kau bebankan pada mereka yang sebelum kami, Wahai Tuhan Kami janganlah kau bebani kami apa-apa yang kami tak mampu menanggungnya, maafkanlah kami, ampunilah kami, kasihanilah kami, Engkaulah Tuan kami, maka tolonglah kami atas orang-orang kafir (QS Albaqarah 285-286).</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/5/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/5/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=5&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/kehancuran-sunnah/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>Kebangkitan Sunnah</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/kebangkitan-sunnah/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/kebangkitan-sunnah/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 13:38:50 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/?p=4</guid>
		<description><![CDATA[Dimasa mulai redupnya cahaya syariah maka para pembela sunnah segera memperbaharuinya, sebagaimana ketika wafatnya Rasulullah saw dan Mahkota Dakwah pada Khalifah Abubakar Asshiddiq ra, mulailah terjadi hal-hal yang mesti dimunculkan yang sebelumnya belum pernah dilakukan, Khalifah Abubakar Asshiddiq ra memerangi muslimin yang tak mau mengeluarkan zakat, sebagaimana sabda Nabi saw bahwa aku diperintahkan memerangi manusia [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=4&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Dimasa mulai redupnya cahaya syariah maka para pembela sunnah segera memperbaharuinya, sebagaimana ketika wafatnya Rasulullah saw dan Mahkota Dakwah pada Khalifah Abubakar Asshiddiq ra, mulailah terjadi hal-hal yang mesti dimunculkan yang sebelumnya belum pernah dilakukan, Khalifah Abubakar Asshiddiq ra memerangi muslimin yang tak mau mengeluarkan zakat, sebagaimana sabda Nabi saw bahwa aku diperintahkan memerangi manusia hingga mereka bersaksi tiada tuhan selain Allah, melakukan shalat, mengeluarkan zakat, bila mereka melakukan itu maka amanlah darah mereka dariku dan harta mereka, dan perhitungan mereka atas Allah swt (shahih Bukhari dan Muslim). Rasul saw belum pernah memerangi orang muslimin dimasa hidupnya, namun dengan hadits ini Khalifah Abubakar Shiddiq ra beristinbat dan memerangi kaum muslimin yang tak mau berzakat, maka Khilafah islamiyah selamat dari kehancuran,</p>
<p>Kemudian terjadilah pembantaian pada Ahlul Yamamah, yaitu para sahabat yang hafal alqur&#8217;an, maka berkata Umar bin Khattab ra agar Alqur&#8217;an ditulis dan dikumpulkan dalam satu jilid, maka Abubakar ra berkata : Bagaimana aku berbuat hal yang tak pernah diperbuat oleh Rasulullah saw?,(tak pernah ada hadits atau ayat yang memerintahkan untuk membukukan Alqur&#8217;an dalam satu kitab sebagaimana sekarang, Alqur&#8217;an masih bertebaran di hafalan sahabat, tertulis di tembok-tembok dan di kulit onta), namun Umar ra terus membujuknya demi maslahat muslimin, akhirnya Khalifah Abubakar ra setuju dan ia memerintahkan Zeyd bin tsabit ra untuk mulai menulis dan menjilid Alqur&#8217;an (Shahih Bukhari hadits no.4402 dan 6768). Penulisan Alqur&#8217;an dan penjilidannya diresmikan dimasa Khilafah Usman bin Affan ra, hingga kini Mushaf Al Qur&#8217;an disebut Mush haf Utsmaniy.</p>
<p>Di zaman Umar bin Khattab ra ia mengeluarkan fatwa shalat tarawih berjamaah, dan ini tak pernah diperintahkan di zaman Rasul saw, walaupun pernah diberlakukan namun kemudian dibubarkan dan tak pernah diperintahkan Rasul saw untuk dilakukan kembali, dan tak pernah dilakukan lagi hingga beliau saw wafat, baru dimasa Umar ra shalat tarawih dilakukan berjamaah, seraya berkata : &#8220;inilah sebaik baik bid&#8217;ah&#8221; (shahih Bukhari hadits no.1906). Khalifah Usman bin Affan ra merubah Adzan pada shalat jumat menjadi dua adzan, maslahat bagi muslimin karena muslimin mulai berdatangan dari tempat yang jauh, dan hal itu tak pernah dilakukan dimasa Rasul saw, dan dimasa khalifah-khalifah sebelumnya.</p>
<p>Kemudian selesai masa Muhajirin dan Anshar, wafatlah para sahabat radhiyallahu&#8217;anhum, wafatlah kesemua wajah mulia yang menyaksikan hadits dan turunnya ayat, maka mulailah para Tabi&#8217;-Tabi&#8217;in risau hadits-hadits Rasul saw akan dilupakan, atau dipalsukan, maka mereka mulai menulis hadits-hadits itu, serta mulai mentashihkan hadits dengan Ilmu Musthalahul Hadits, yang sebelumnya tak pernah diperintahkan oleh rasul saw untuk memilah-milah hadits beliau saw, namun hal ini diada-adakan oleh para Ulama demi terjaganya syariah Islamiyah dan Sunnah Nabawiyyah. Kemudian mulailah timbul Ikhtilaf dalam pemahaman hadits dan ayat, maka demi menyelamatkan ummat terbentuklah Madzhab, agar muslimin bisa berpedoman pada satu Imam dalam pengamalan Ibadahnya.</p>
<p>Kemudian mulai redup pula lah semangat ummat untuk perduli pada sunnah, semakin banyak orang yang meninggalkan shalat, semakin banyak orang yang hanya berfikir dunia dan dunia, maka barat dan timur dipenuhi Fasad dan kedhaliman, maka para pejuang sunnah mulai mencari cara untuk Kebangkitan sunnah dan Medan Dakwah Akbar yang dapat memadukan muslimin dalam satu perkumpulan, demi silaturahmi, demi mereka mendengarkan Tabligh dan demi bangkitnya semangat baru, namun kebangkitan semangat ini butuh lambang pembangkitnya, bukan Ramadhan, bukan idulfitri, bukan idul adha, karena hari-hari itu sudah umum, maka mereka mengambil kesimpulan bahwa simbol kebangkitan Ummat adalah hari kelahiran Rasul saw, hari mulia yang mengawali kebangkitan Risalah, karena Rabi&#8217;ul awwal bukan hanya bulan kelahiran nabi saw, namun juga bulan Hijrahnya Rasul saw ke Madinah, sebagaimana dijelaskan dalam semua buku sejarah bahwa Hijrah Rasul saw bukanlah pada bulam Muharram, namun Umar bin Khattab ra memulai penanggalan Hijriah pada 1 Muharram karena di bulan itulah sahabat mulai berhijrah ke Madinah, namun Hijrah Rasul saw adalah pada Rabiul awal, maka dibulan itu pula wafatnya Rasul saw.</p>
<p>Kejadian-kejadian agung yang merupakan kebangkitan risalah kesemuanya berpadu pada hari kelahiran Rasul saw, yaitu kelahiran beliau adalah lambang seluruh kebangkitan islam, lalu hari hijrah beliau saw yang merupakan lambang semangat tersuci dalam islam, yaitu berpadunya semangat Muhajirin yang meninggalkan kampung halamannya yang tercinta ke negeri asing, dan semangat Anshar yang menerima tamu-tamu asing untuk dibagi dua harta mereka, dan rumah mereka. Dua semangat agung dari penegak Risalah ini berpadu pada hijrah Rasul saw yaitu yang juga pada senin 12 Rabiul awwal. Kemudian hari wafatnya Rasul saw yang juga pada senin 12 Rabiul awwal, saya menamakan hari wafatnya Rasul saw adalah hari kebangkitan semangat terdahsyat setelah wafatnya Rasul saw yg mana para sahabat berpecah belah dan putus asa, Namun di hari 12 Rabiul awal saat jenazah rasul saw masih terbujur, maka bangkitlah Da&#8217;I Agung, Sayyidina Abubakar Asshiddiq ra yang berpidato membangkitkan semangat muhajirin dan anshar agar tak putus asa, maka bangkitlah semangat mereka.</p>
<p>Tiga kejadian besar berpadu pada 12 Rabiul awwal, yaitu Kelahiran sang Nabi saw yang mengawali kebangkitan Risalah, peristiwa Hijrah yang mengawali penyebaran risalah dan kekuasaan Islam, dan peristiwa wafatnya Rasul saw yang melambangkan kebangkitan semangat para sahabat untuk terus berjuang dan setia pada perjuangan Nabi mereka. Maka para pembesar ulama mengambil munasabah 12 Rabiul awal dengan perayaan, Medan Tabligh, Medan pembangkit semangat muslimin, untuk kembali pada Panji Rasulullah saw, nama beliau saw di elu-elukan, dipuji, dimuliakan, sejarahnya dibacakan, kesemuanya demi menyemangati muslimin agar kembali beridolakan Sang Nabi saw sebagaimana para sahabat radhiyallahu&#8217;anhum. Maka hal ini berhasil, Medan Dakwah dan Tabligh terbesar didunia sepanjang tahun adalah pada Rabiul awal, tak ada medan dakwah terbesar didunia melebihi perayaan hari kelahiran Rasul saw, dimana hampir setiap masjid, majelis taklim, musholla, bahkan perkantoran, sekolah, bahkan rumah-rumah masyarakat, dipenuhi dengan kesibukan merayakan Maulid Nabi saw, merupakan adat istiadat agung yang diajarkan para salfussholeh demi bangkitnya cinta ummat ini pada Nabi mereka,</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/4/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/4/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=4&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/kebangkitan-sunnah/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>Bersatulah wahai Makmum Sayyidina Muhammad saw</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/bersatulah-wahai-makmum-sayyidina-muhammad-saw/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/bersatulah-wahai-makmum-sayyidina-muhammad-saw/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 13:21:15 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Add new tag]]></category>

		<guid isPermaLink="false">http://firstbloodpart3.wordpress.com/?p=3</guid>
		<description><![CDATA[Hari hari terakhir ramadhan adalah malam malam tangis sedih bagi hamba hamba Nya swt, mereka sangat sedih berpisah dengan Ramadhan, seraya merintih : Selamat berpisah wahai Bulan Sujud.., Selamat berpisah wahai Bulan Puasa, Selamat berpisah wahai Bulan Taubat, Selamat berpisah wahai Bulan Al Qur;an, Selamat berpisah wahai Bulan Ahlul Badr, Selamat berpisah wahai Bulan Fatah [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=3&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hari hari terakhir ramadhan adalah malam malam tangis sedih bagi hamba hamba Nya swt, mereka sangat sedih berpisah dengan Ramadhan, seraya merintih :<br />
Selamat berpisah wahai Bulan Sujud..,<br />
Selamat berpisah wahai Bulan Puasa,<br />
Selamat berpisah wahai Bulan Taubat,<br />
Selamat berpisah wahai Bulan Al Qur;an,<br />
Selamat berpisah wahai Bulan Ahlul Badr,<br />
Selamat berpisah wahai Bulan Fatah Makkah,<br />
Selamat berpisah wahai Bulan Nuzulul Qur&#8217;an,<br />
Selamat berpisah wahai Bulan Sabar,<br />
Selamat berpisah wahai Bulan Syukur,<br />
Selamat berpisah wahai Bulan pengampunan,<br />
Selamat berpisah wahai Bulan Rahmat Nya swt,<br />
Selamat berpisah wahai Bulan Pelepasan dari api neraka,</p>
<p>Ahlussunnah waljamaah bersujud setiap malamnya dalam shalat Tarawih sebanyak 40 kali sujud, sebagaimana seluruh madzhab Ahlussunnah waljamaah, berupa madzhab Syafii, Maliki, Hambali, dan Hanafi kesemuanya menjalankan tarawih paling sedikit sebanyak 20 rakaat yg berarti paling sedikit mereka 40X bersujud setiap malamnya, dan dalam sebulan penuh Ramadhan mereka menyempurnakan paling sedikit 1200X sujud pada Allah swt, Inilah malam malam ribuan sujud ummat Muhammad saw.., dan Rasul saw telah bersabda : Allah mengharamkan api neraka untuk membakar anggota sujud (Shahih Muslim), Ya Rabb Jadikan Kami ahlussujud..</p>
<p>Berakhir di penghujung Ramadhan, 1 syawal 1428 H, saya menghimbau seluruh muslimin untuk bersatu dalam shaf Ahlussunnah waljamaah, jangan memisahkan diri dari kelompok besar muslimin Arba&#8217;a Madzahib (4 madzhab besar), bersatulah, sungguh Rasul saw bersabda : &#8220;Jika kalian melihat hal yang tak kalian senangi pada penguasa kalian, maka bersabarlah, sungguh barangsiapa yang keluar sejengkal dari Jamaah Muslimin lalu ia wafat, maka ia akan mati dalam kematian Jahiliyah&#8221; (Shahih Bukhari).</p>
<p>Jangan pisahkan dirimu dari ahlussunnah waljamaah, sungguh keempat madzhab besar dimuka bumi ini memperbolehkan Maulid Nabi Muhammad saw, sungguh keempat madzhab besar ini bertawassul, sungguh keempat madzhab besar ini berziarah kubur, sungguh keempat madzhab besar ini bertabarruk pada shalihin, sungguh keempat madzhab besar ini tak ada yang melakukan tarawih 11 rakaat, mereka bersujud paling tidak 40X setiap malamnya dalam tarawih,</p>
<p>Dan kita mengikuti pengumuman pemerintah kita, kita bukan budak pemerintah, namun kita bukan pula pemberontak, kita adalah Ummat Sayyidina Muhammad saw, dan Rasulullah saw telah menginstruksikan untuk jangan berpisah dari Jamaah Muslimin, dan bersabar atas kesalahan penguasa kita, dan kita diinstruksikan untuk taat selama tak diperintah untuk bermaksiat,</p>
<p>Sungguh Imam Imam kita telah berbuat demikian, mereka tak memberontak pada pemerintahan dan penguasa, padahal penguasa masa lalu sangatlah keji, banyak Imam Imam yang disiksa, dibantai, dicambuk, namun Imam Imam kita lebih menyukai kedamaian dan membangun generasi mulia, saya pernah bertanya kepada Mufti Tarim Al Allamah Almusnid Alhabib Ali Almasyhur bin Hafidh (Hadhramaut, Yaman), mengenai bagaimana kalau ternyata yang benar dalam memutuskan Idul Fitri itu justru yang memisahkan diri dari jamaah muslimin?, beliau menjawab : &#8220;Berpuasa di hari Idulfitri demi mengikuti jamaah muslimin jauh lebih afdhal daripada berbuka namun memisahkan diri dari jamaah muslimin dan menyebabkan perpecahan muslimin&#8221;.</p>
<p>Demikian pendapat yang sama oleh Al Allamah Mufti Madinah Almunawwarah Al Musnid Alhabib Zein bin Ibrahim bin Smeith (Madinah). Karena menyebabkan kebingungan muslimin, perpecahan dan memisahkan diri dari jamaah muslimin telah diancam mati dalam kekufuran oleh Nabi saw sebagaimana hadits diatas.</p>
<p>Maka dengan ini kita mengangkat kedua tangan kita, di malam malam terakhir penghujung bulan agung ini, agar Allah menyatukan sanubari muslimin, mengembalikan mereka yg memisahkan diri dari jamaah Muslimin, untuk kembali pada Ahlussunnah waljamaah wa madzahibul Arba&#8217;ah,</p>
<p>Yaa Rabb.., kembalikan mereka pada shaf Jamaah Muslimin, Yaa Rabb mereka keluarga kami, teman, kami, saudara kami muslimin, genggam jiwa mereka dan kembalikan mereka pada shaf kami, Ya Rahman.. Yaa Rahiim..</p>
<p>Saudara dan saudariku, jadikanlah Idulfitri ini persatuan muslimin, mereka yg berlebaran berbeda, jangan diikuti dan jangan pula dimusuhi, kita semua bertanggung jawab menyeru mereka untuk kembali, kita berlapang dada untuk pelahan lahan mengembalikan mereka pada shaf mulia ini.</p>
<p>Rabbiy jangan kau haramkan kami dari sekecil kecilnya Anugerah Mu di bulan agung ini, Rabbiy kami tak rela berpisah darinya kecuali kau halalkan bagi kami seluruh anugerah Mu yg tersimpan pada setiap kejap di bulan Ramadhan ini, Wahai Yang Maha Memiliki Ramadhan, Wahai Yang Maha Memiliki setiap Anugerah sepanjang Zaman, wahai Yang Maha Memiliki Kebahagiaan setiap waktu dan masa, Wahai Yang Maha Kekal dan Tunggal sebelum segalanya ada, hingga kesemuanya ada, hingga kesemuanya Sirna, wahai Cahaya Keabadian yang menerangi jiwa hamba hamba Nya dengan Iman dan kesejukan,</p>
<p>Terangi jiwa kami dengan Cahaya Nama Mu, jadikan Nama Mu adalah Nama teragung dalam jiwa kami, Nama yang paling kami rindukan, nama yang paling kami harapkan, nama yang paling kami dambakan dan cintai..</p>
<p>Yaa Allah..</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/3/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/3/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=3&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/bersatulah-wahai-makmum-sayyidina-muhammad-saw/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
		<item>
		<title>Hello world!</title>
		<link>http://firstbloodpart3.wordpress.com/2008/06/18/hello-world/</link>
		<comments>http://firstbloodpart3.wordpress.com/2008/06/18/hello-world/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 12:55:19 +0000</pubDate>
		<dc:creator>firstbloodpart3</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=1&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome to <a href="http://wordpress.com/">WordPress.com</a>. This is your first post. Edit or delete it and start blogging!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firstbloodpart3.wordpress.com/1/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firstbloodpart3.wordpress.com/1/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstbloodpart3.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firstbloodpart3.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firstbloodpart3.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firstbloodpart3.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/firstbloodpart3.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/firstbloodpart3.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/firstbloodpart3.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/firstbloodpart3.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firstbloodpart3.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firstbloodpart3.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firstbloodpart3.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firstbloodpart3.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firstbloodpart3.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firstbloodpart3.wordpress.com/1/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firstbloodpart3.wordpress.com&amp;blog=4010143&amp;post=1&amp;subd=firstbloodpart3&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://firstbloodpart3.wordpress.com/2008/06/18/hello-world/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f25185a14deb77b957ea4e3e9c205a50?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firstbloodpart3</media:title>
		</media:content>
	</item>
	</channel>
</rss>
