-
Notifications
You must be signed in to change notification settings - Fork 16
/
start.html
222 lines (209 loc) · 17.7 KB
/
start.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
---
title: Down the rabbit hole
---
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>PHP101 - {{ page.title }}</title>
<link rel="stylesheet" href="stylesheets/styles.css">
<link rel="stylesheet" href="stylesheets/pygment_trac.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="javascripts/main.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
</head>
<body>
<header>
<h1>PHP101</h1>
<p>For the absolute beginner</p>
</header>
<div id="banner">
<span id="logo"></span>
<a href="https://github.com/ss23/php-tutorial" class="button fork"><strong>View On GitHub</strong></a>
</div><!-- end banner -->
<div class="wrapper">
{% include nav.html %}
<section>
<h2>The only acronym you'll ever need</h2>
<p>If you're new to Web development, you could be forgiven for thinking that it consists of no more than a mass of acronyms, each one more indecipherable thanthe last. ASP, CGI, SOAP, XML, HTTP - the list seems never-ending, and
the sheer volume of information on each of these can discourage the most avid programmer. But before you put on your running shoes and flee, there's a little secret you should know. To put together a cutting-edge Web site, chock full of all the latest bells and whistles, there's only one acronym you really need to know:</p>
<p>PHP</p>
<p>Now, while you have almost certainly heard of PHP, you may not be aware of just how powerful the language is, and how much it can do for you. Today, PHP has the enviable position of being the only open-source server-side scripting language that's both fun and easy to learn. This is not just advertising: recent surveys show that more than 16,000,000 Web sites use PHP as a server side scripting language, and the language also tops the list of most popular Apache modules.</p>
<p>Why, you ask? The short answer: it's powerful, it's easy to use, and it's free. Extremely robust and scalable, PHP can be used for the most demanding of applications, and delivers excellent performance even at high loads. Built-in database support means that you can begin creating data-driven applications immediately, XML support makes it suitable for the new generation of XML-enabled applications, and the extensible architecture makes it easy for developers to use it as a framework to build their own custom modules. Toss in a great manual, a knowledgeable developer community and a really low price (can you spell f-r-e-e?) and you've got the makings of a winner!</p>
<p>My goal in this series of tutorials is very simple: I'll be teaching you the basics of using PHP, and showing you why I think it's the best possible tool for Web application development today. I'll be making no assumptions about your level of knowledge, other than that you can understand basic HTML and have a sense of humor. On the off chance you were wondering, this tutorial covers PHP 5.2 and upwards. If we use anything newer than 5.2, we'll try make a note. Note however, that since the tutorial was adapated from an old version, there may be references to PHP 4. You can just ignore these, as no sane programmer bothers with it anymore.</p>
<p>Let's get going!</p>
<h2>The right enviroment</h2>
<p>PHP is typically used in combination with a Web server like Apache. Requests for PHP scripts are received by the Web server, and are handled by the PHP interpreter. The results obtained after execution are returned to the Web server, which takes care of transmitting them to the client browser. Within the PHP script itself, the sky's the limit - your script can perform calculations, process user input, interact with a database, read and write files… Basically, anything you can do with a regular programming language, you can do inside your PHP scripts.</p>
<p>From the above, it is clear that in order to begin using PHP, you need to have a proper development environment set up.</p>
<p>This series will focus on using PHP with the Apache Web server on Linux, but you can just as easily use PHP with Apache on Windows, UNIX and Mac OS. Detailed instructions on how to set up this development environment on each platform are available in the online manual, at <a href="http://www.php.net/manual/en/installation.php">http://www.php.net/manual/en/installation.php</a> - or you can just download a copy of PHP 5 from <a href="http://www.php.net">http://www.php.net</a> and read the installation instructions.</p>
<p>If you're on Windows, there's an even easier option - <a href="http://www.wampserver.com">WampServer</a> or <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a>. They're a bundle package of PHP, MySQL, and Apache, already set up for you. Either of these should work fine, however, you may have to look at their documentation.</p>
<p>Go do that now, and come back when you've successfully installed and tested PHP.</p>
<h2>Start me up</h2>
<p>There's one essential concept that you need to get your mind around before we proceed further. Unlike CGI scripts, which require you to write code to output HTML, PHP lets you embed PHP code in regular HTML pages, and execute the embedded PHP code when the page is requested.</p>
<p>These embedded PHP commands are enclosed within special start and end tags, like this:</p>
{% highlight php %}<?php echo "lol"; ?>{% endhighlight %}
<p>Here's a simple example that demonstrates how PHP and HTML can be combined:</p>
{% highlight php %}<html>
<head>
<title>My first PHP script</title>
</head>
<body>
Agent: So who do you think you are, anyhow?
<br>
<?php
// Print output
echo 'Neo: I am Neo, but my people call me The One.';
?>
</body>
</html>{% endhighlight %}
<p>Not quite your traditional "Hello, World" program... but then again, I always thought tradition was over-rated.</p>
<p>Save the above script to a location under your Web server document root, with a .php extension, and browse to it. You'll see something like this:</p>
<img src="images/part1-ex1.png" alt="The resultant HTML">
<p>Look at the HTML source:</p>
{% highlight html %}<html>
<head></head>
<body>
Agent: Who do you think you are, anyhow?
<br>
Neo: I am Neo, but my people call me The One.</body>
</html>{% endhighlight %}
<p>What just happened? When you requested the script above, Apache intercepted your request and handed it off to PHP. PHP then parsed the script, executing the code between the <code><?php...?></code> marks and replacing it with the output of the code run. The result was then handed back to the server and transmitted to the client. Since the output contained valid HTML, the browser was able to render it for display to the user.</p>
<p>A close look at the script will reveal the basic syntactical rules of PHP. Every PHP statement ends in a semi-colon. This convention is identical to that used in Perl, and omitting the semi-colon is one of the most common mistakes newbies make. That said, it is interesting to note that a semi-colon is not needed to terminate the last line of a PHP block. The PHP closing tag includes a semi-colon, therefore the following is perfectly valid PHP code:</p>
{% highlight php %}<?php
// Print output
echo 'Neo: I am Neo, but my people call me The One.'
?>{% endhighlight %}
<p>Now, for the rest of the examples, I may omit the extra <code><html></code> and other tags where they aren't required for an example, for breviety. Remember to write valid HTML in real applications.</p>
<p>Now back to PHP - it's also possible to add comments to your PHP code, as I've done in the example above. PHP supports both single-line and multi-line comment blocks:</p>
{% highlight php %}<?php
// This is a single-line comment
/* This is a
multi-line
comment */
?>{% endhighlight %}
<p>Which should I use, you might ask? Well, comments are only for us humans, so you should use whatever looks better. It may be counter-intuitive, but thats the way it is. Note though, you should try be consitent. That means, not choosing one randomly every time you want to make a comment, but rather deciding which you will use in which case, and sticking with it. Inconsistency is the arch-enemy of us programmers.</p>
<p>Also, blank lines within the PHP tags are ignored by the parser. Everything outside the tags is also ignored by the parser, and returned as-is. Only the code between the tags is read and executed.</p>
<h2>A case of identity</h2>
<p>Variables are the bread and butter of every programming language... and PHP has them too. A variable can be thought of as a programming construct used to store both numeric and non-numeric data; the contents of a variable can be altered during program execution. Finally, variables can be compared with each other, and you - the programmer - can write code that performs specific actions on the basis of this comparison.</p>
<p>PHP supports a number of different variable types: integers, floating point numbers, strings and arrays. In many languages, it's essential to specify the variable type before using it: for example, a variable may need to be specified as type integer or type array. Give PHP credit for a little intelligence, though: it automagically determines variable type by the context in which it is being used!</p>
<p>Every variable has a name. In PHP, a variable name is preceded by a dollar ($) symbol and must begin with a letter or underscore, optionally followed by more letters, numbers and/or underscores. For example, <code>$popeye</code>, <code>$one</code> and <code>$INCOME</code> are all valid PHP variable names, while <code>$123</code> and <code>$48hrs</code> are invalid.</p>
<p>Note that variable names in PHP are case sensitive, so <code>$me</code> is different from <code>$Me</code> or <code>$ME</code>.</p>
<p>Here's a simple example that demonstrates PHP's variables:</p>
{% highlight php %}Agent: So who do you think you are, anyhow?<br>
<?php
// Define variables
$name = 'Neo';
$rank = 'Anomaly';
$serialNumber = 1;
// Print output
echo "Neo: I am <strong>$name</strong>, the <strong>$rank</strong>. You can call me by my serial number, <strong>$serialNumber</strong>.";
?>{% endhighlight %}
<p>Here, the variables <code>$name</code>, <code>$rank</code> and <code>$serialNumber</code> are first defined with string and numeric values, and then substituted in the <code>echo</code> language construct. For now, you can think of <code>echo</code> as a function that you don't have to use parenthises for (as shown in the example). <code>echo</code>, along with the <code>print()</code> function, are commonly used to print data to the standard output device (here, the browser). Notice that I've included HTML tags within the call to echo(), and those have been rendered by the browser in its output. You can do this too. Really.</p>
<p>Once again you may be wondering: Which should I use? <code>echo</code> or <code>print</code>? Once again, it doesn't matter, as long as you're consitent. You'll find <code>echo</code> more common, so if you have no personal preference, using <code>echo</code> consitently is a good choice.</p>
<h2>An equal music</h2>
<p>To assign a value to a variable, you use the assignment operator: the <code>=</code> symbol. This is used to assign a value (the right side of the equation) to a variable (the left side). The value being assigned need not always be fixed; it could also be another variable, an expression, or even an expression involving other variables, as below:</p>
{% highlight php %}<?php
$age = $dob + 15;
?>{% endhighlight %}
<p>Interestingly, you can also perform more than one assignment at a time. Consider the following example, which assigns three variables the same value simultaneously:</p>
{% highlight php %}<?php
$angle1 = $angle2 = $angle3 = 60;
?>{% endhighlight %}
<h2>Not my type</h2>
<p>Every language has different types of variable - and PHP is no exception. The language supports a wide variety of data types, including simple numeric, character, string and Boolean types, and more complex arrays and objects. Here's a quick list of the basic ones, with examples:</p>
<ul>
<li><strong>Boolean</strong>: The simplest variable type in PHP, a Boolean variable, simply specifies a true or false value.
{% highlight php %}<?php
$sexy = true;
?>{% endhighlight %}</li>
<li><strong>Integer</strong>: An integer is a plain-vanilla whole number like 75, -95, 2000 or 1.
{% highlight php %}<?php
$age = 21;
?>{% endhighlight %}</li>
<li><strong>Floating-point</strong>: A floating-point number is typically a fractional number such as 12.5 or 3.141592653589. Floating point numbers may be specified using either decimal or scientific notation.
{% highlight php %}<?php
$temperature = 21.5;
?>{% endhighlight %}</li>
<li><strong>String</strong>: A string is a sequence of characters, like "hello" or "abracadabra". String values may be enclosed in either double quotes ("") or single quotes(''). (Quotation marks within the string itself can be "escaped" with a backslash (\) character.) String values enclosed in double quotes are automatically parsed for special characters and variable names; if these are found, they are replaced with the appropriate value. Here's an example:
{% highlight php %}<?php
$identity = 'James Bond';
$car = 'BMW';
// This would contain the string "James Bond drives a BMW"
$sentence = "$identity drives a $car";
echo $sentence;
// This would contain, literally, "$identity drives a $car"
$sentence = '$identity drives a $car';
echo $sentence;
?>{% endhighlight %}
The difference between single quotes an double quotes often confuses new programmers, so if you're having trouble, don't forget you can simple create a new .php file to test with. I highly recommend reading <a href="http://php.net/manual/en/language.types.string.php">http://php.net/manual/en/language.types.string.php</a> to learn how string parsing is done in PHP, including information on the difference between single and double quotes.</li>
</ul>
<p>To learn more about PHP's data types, visit <a href="http://www.php.net/manual/en/language.types.php">http://www.php.net/manual/en/language.types.php</a>.</p>
<h2>Market value</h2>
<p>If variables are the building blocks of a programming language, operators are the glue that let you build something useful with them. You've already seen one example of an operator - the assignment operator -, which lets you assign a value to a variable. Since PHP believes in spoiling you, it also comes with operators for arithmetic, string, comparison and logical operations.</p>
<p>A good way to get familiar with operators is to use them to perform arithmetic operations on variables, as in the following example:</p>
{% highlight php %}<?php
// Set quantity
$quantity = 1000;
// Set original and current unit price
$origPrice = 100;
$currPrice = 25;
// Calculate the difference in price
$diffPrice = $currPrice - $origPrice;
// Calculate percentage change in price
$diffPricePercent = (($currPrice - $origPrice) * 100) / $origPrice
?>
Quantity: <?php echo $quantity; ?><br>
Cost Price: <?php echo $origPrice; ?><br>
Current Price: <?php echo $currPrice; ?><br>
Absolute change in price: <?php echo $diffPrice; ?><br>
Percent change in price: <?php echo $diffPricePercent; ?><br>{% endhighlight %}
<p>Looks complex? Don't be afraid - it's actually pretty simple. The meat of the script is at the top, where I've set up variables for the unit cost and the quantity. Next, I've performed a bunch of calculations using PHP's various mathematical operators, and stored the results of those calculations in different variables. The rest of the script is related to the display of the resulting calculations in a neat table.</p>
<p>If you'd like, you can even perform an arithmetic operation simultaneously with an assignment, by using the two operators together. The two code snippets below are equivalent:</p>
{% highlight php %}<?php
// This...
$a = 5;
$a = $a + 10;
// ... is this same as this
$a = 5;
$a += 10;
?>{% endhighlight %}
<p>If you don't believe me, try echoing them both.</p>
<h2>Stringing things along</h2>
<p>Why stop with numbers? PHP also allows you to add strings with the string concatenation operator, represented by a period (.). Take a look:</p>
{% highlight php %}<?php
// Set up some variables
$a = 'the';
$b = 'games';
$c = 'begin';
$d = 'now';
// Combine them using the concatenation operator
// This returns 'the games begin now<br>'
$statement = $a.' '.$b.' '.$c.' '.$d.'<br>';
echo $statement;
// This outputs 'begin the games now!'
$command = $c.' '.$a.' '.$b.' '.$d.'!';
echo $command;
?>{% endhighlight %}
<p>As before, you can concatenate and assign simultaneously, as below:</p>
{% highlight php %}<?php
// Define string
$str = 'the';
// add and assign
$str .= 'n';
// $str now contains "then"
echo $str;
?>{% endhighlight %}
<p>To learn more about PHP's arithmetic and string operators, visit <a href="http://www.php.net/manual/en/language.operators.arithmetic.php">http://www.php.net/manual/en/language.operators.arithmetic.php</a> and <a href="http://www.php.net/manual/en/language.operators.string.php">http://www.php.net/manual/en/language.operators.string.php</a>.</p>
<p>That's about it for this tutorial. You now know all about the basic building blocks and glue of PHP - its variables and operators. In <a href="operators.html">Part Two</a> of this series, I'll be using these fundamental concepts to demonstrate PHP's powerful form processing capabilities.</p>
</section>
<footer>
<p><small>Hosted on GitHub Pages — Theme by <a href="http://twitter.com/#!/michigangraham">mattgraham</a></small></p>
</footer>
</div>
<!--[if !IE]><script>fixScale(document);</script><!--<![endif]-->
</body>
</html>