Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

PHP Introductory Tutorial

Rated 4.26 (Ratings: 8) (Add your rating)

Log in to add a comment
(10 comments so far)

Want more?

  • More articles in Code
  • More articles by Seb
 
Picture of Seb

Seb Potter

Member info | Full bio

User since: April 21, 1999

Last login: December 16, 2008

Articles written: 19

PHP - The PHP Hypertext Pre-processor

What you need to know

First, you should be aware that this is not a tutorial for complete beginners. There are already a large number of resources that can cover an introduction to programming far better than I could ever hope to. For those who are new to server-side programming, I would suggest a search through the code section of evolt.org, and the excellent Newbie Network.

That said, I will not assume a great deal of specific knowledge of PHP. These tutorials will be written for those of you who have some limited programming knowledge, and are able to rapidly pick up the specific details of a new syntax whilst recognising the underlying principles. If you have some prior experience with a web-centric language (ASP, JavaScript, Java, PERL, etc.) then you'll be fine.

For those that do not have access to a PHP server, I would suggest heading over to our very own members.evolt.org which provides free web hosting, including PHP, MySQL, and an e-mail account for the wonderful purpose of helping developers like us in a friendly environment. All the code that will form these tutorials has been developed as part of my learning process, and much if it now forms my own site. Needless to say, everything I discuss should work for any members.evolt.org account.

Getting to it: your first PHP script

No "hello world" applications here. We're going to dive right in with a simple form acknowledgement script that (for now) does nothing more than output the contents of a simple HTTP POST form to an HTML page. First the code, then a brief explanation.

Please ignore the fact that some vital HTML is missing. Consider this to be pseudo-code for exemplary purposes only. You can find links to all of the complete code at the bottom of the page.

The form input, your_comments.html

<html>
	<head>
		<title>Please send us your comments</title>
	</head>
	<body>
		<p>Enter your details in the boxes below, then hit the submit button.</p>
		<form action="ack_comments.php" method="post">
		your name : <input type="text" size="20" name="your_name"><br>
		your email : <input type="text" size="20" name="your_email"><br>
		your comments : <textarea cols="30" rows="10" wrap="virtual" name="your_comments">Some comments here...</textarea><br>
		<input type="submit" name="submit" value="submit">
		</form>
	</body>
</html>

Right, this is your most basic HTML form. Hopefully, it shouldn't require any comment or explanation. The only thing to note that is we are POSTing to the script "ack_comments.php".

The form reponse, ack_comments.php

<?
$your_name = $HTTP_POST_VARS['your_name'];	// from the array created by the HTTP Request.
$your_email = $HTTP_POST_VARS['your_email'];
$your_comments = $HTTP_POST_VARS['your_comments'];
$error_msg = false;							// created as a boolean type, so useful as a flag.

if ($your_email == NULL){
	$error_msg = "You did not enter an email address!";		
	// no email address, so we set the flag true (any non-zero value)
}


?>
<html>
	<head>
		<title>Thanks for your comments</title>
	</head>
	<body>
		<p>You entered the following information:</p>
		<p>your name : <?= $your_name ?><br>
		<? if (!$error_msg) {
			?>your email : <?= $your_email ?>
		<?
		} else {
			?><?= $error_msg ?>
		<?
		}
		?><br>
		your comments : <?= $your_comments ?></p>
	</body>
</html>

Let's break this down, step-by-step.

<? and ?> are our script delimiters. PHP will process anything inside these, and treat anything outside them as being a literal string. Basically, when all is done, the results of your script inside the delimiters is concatenated with anything outside the delimiters, and returned as the HTTP Response.

$your_name = $HTTP_POST_VARS['your_name'];
Here we are delcaring a variable $your_name, and assigning a value to it. The value is held in an associative array, in this case a built-in array created by the HTTP Request, called $HTTP_POST_VARS. In common with many languages, you can access the elements of an array either by specifying a zero-relative index (eg: $someArray[2] to get the third element) or, if you have an associative array, by specifying a key (eg: $someAssocArray['colour']). Each element of an array can hold any value, including other arrays, and objects.

Next we have set an error flag, $error_msg, to be false. We have declared $error_msg as a standard boolean type (either true or false). PHP treats false and 0 (zero) to be equivalent when evaluating a boolean expression, and any other value (including strings, objects, and negative integers) are treated as true.

We now make use of this behaviour by checking to see if the variable $your_email holds a value. Later, we will add checking for a valid address, but for now we just check to see if the variable is NULL (ie: not set). If it is not, we assign a string to $error_msg, which we will display later. Equality is tested using the == operator, and the expression must be enclosed within parentheses. Our if-statement uses braces ({}) because the conditional spans more than 1 line. We could have written:
if ($is_this_true)
do this;

which would be identical, but can cause confusion for anyone that's reading your code and expecting the braces.

With our variables all assigned, we can get down to the business of displaying the results. We close off the PHP script tag (?>), and start writing out the HTML page. You'll notice that when we write out the variable $your_name, we use a shortened syntax within the HTML : <?= $your_name ?>. This is a shortcut for the language construct echo(value). ASP coders will recognise this as being a handy way of substituting script variables into your HTML markup without the need for lengthy blocks of script.

The last part of interest in this script lies with the final if-statement. We are now testing the value of $error_msg, which needs to return either true or false. This makes sense when we consider that PHP treats non-zero values as true, including strings. So, if an error message has been assigned to $error_msg, it will be displayed.

Your Next Step

If you have not already done so, grab the code listings above, put them into appropriate files, and try them out.

Finally, please, please use the comment facility below to provide feedback on these articles. This is the first tutorial that I have written, and I can only make them better if you tell me how. You can also email me directly for further discussion. If you have questions about any aspect of PHP, you can pose it to evolt.org's mailing list where there is a high chance that I will answer it.

Seb is a Jedi Master in the art of creating sites and keeping servers running. This often means hitting them repeatedly with forces that defy rational explanation, though he prefers to descibe it as "administration". When he's not practising his percussive skills on E450s and AS400s, he can be found masquerading as the senior developer for some widely varied clients. It's still not certain whether or not the meanings of CMS, CRM, and B2B have penetrated the alcoholic fog enveloping his brain, but he makes convincing noises to customers about XML, XSLT, Python, J2EE, PHP, Perl, C++, and OpenGL.

Seb has been in the web game pretty much since it began, and still has fond memories of the time when a web could be swept aside with a duster and spam was pork luncheon meat. Despite being the developer of one of the first commerce sites in Europe, he has yet to make any real money.

Being English, Seb doesn't like SOAP, but instead has recently discovered something called ZOPE. Zope is a platform that runs Plone which he thinks is the coolest thing since high-performance, real-time 3D APIs, which he often writes small games in.

Seb lives in the best little city in the world, and used to commute 5 hours a day on British trains. He is subsequently immune to all forms of torture techniques.

Files to download...

Submitted by Seb on July 23, 2001 - 11:03.

If you can't be bothered cutting+pasting the listings above into an editor and hitting the save button, you can grab a zip of the files here. Just drop them into a folder on any PHP-enabled webserver and away you go.

login or register to post comments

horses for courses

Submitted by andlang on July 29, 2001 - 21:18.

Having looked through the PHP code (and this means my FIRST look at PHP code), it seems to be very similar to VBScript (ASP). Of course, each language has its own syntax peculiarities, but the structure and logic are similar. I was wondering if anyone's done a "bench test" between ASP and PHP. What are advantages for an ASP programmer to use PHP and vice versa? Is PHP faster than ASP?

login or register to post comments

ASP vs PHP

Submitted by skamp on August 1, 2001 - 08:45.

I don't know of any benchmark, but I see two reasons for using PHP rather than ASP : - VBScript is Micro$oft, and to me that's BAD. - PHP is an open source language, that means it will evolve constantly. I'm using PHP since a year ago, and I'm happy with it :)

login or register to post comments

ASP vs PHP

Submitted by Seb on August 1, 2001 - 09:25.

Sorry Skamp, I have to disagree. The fact that ASP is a Microsoft product doesn't automatically make the technology bad. ASP is excellent for a site that requires Windows COM integration.

Where PHP gains over ASP is in the fact that it is Object Oriented, it's free, it's cross-platform, it's faster, it's easier to learn, it's more robust (generally a function of the underlying platform), etc. If you want to know what makes PHP special, just read through the built-in functions that are listed in the manual.

Seriously though, PHP is a brilliant language, and the amount of development that is being done for it is phenomenal. Check out 7 reasons why PHP is better than ASP, and a comparison of PHP and ColdFusion, to make up your own mind.

login or register to post comments

ASP vs PHP

Submitted by mwarden on August 1, 2001 - 22:08.

Of course, Seb, my friend, some of those points are highly subjective. Easier to learn? Seriously? I guess it's preference, but I have never been able to code PHP without the function reference open. I mean, look at all those functions. It would be very difficult to memorize those functions, especially when many of them are very similar.

I don't want this to turn into a server-side language debate, especially because it ALWAYS comes down to two things:

preference and the task at hand

But it's always fun to bash microsoft...

login or register to post comments

Submitted by robbie_dee on August 4, 2001 - 05:46.

One advantage of PHP over ASP is that it's free. Also, it works very well with MySql which is reported to be 25% faster than ms sql server and is also free. It runs natively on linux, which many cheap hosts use. Again, that is free. I can see a few advantages there. Why pay much more for a microsoft host when unix is so great ? It's perfect for new starters that want to gain experience and knowledge without spending a small fortune on hosting and software. The fact that its open source means that it's widely supported and you don't have to pay for resources like MSDN. Also, there's no danger of it being unsupported in the future. I love to bash microsoft because I hate monopolies. There are many advantages to open source products and I hope that more people will see the light and start to use them.

login or register to post comments

robbie_dee...

Submitted by mwarden on August 4, 2001 - 20:44.

ASP costs the same as PHP. You are making a common mistake. The difference is the operating system, not the language. On an NT host, ASP costs the same as PHP. You could even view it as less cost because of the extra effort it takes to install PHP.

MySQL? ASP works with MySQL too, friend. So, that's not even an issue. And I'm not sure what you are talking about when you refer to paying for MSDN. You can buy a MSDN subscription, but that's something a little bit different. As far as documentation and information, msdn.microsoft.com is free to use.

login or register to post comments

Deprecated

Submitted by Kristopher on May 30, 2002 - 10:25.

Just to let you know, $HTTP_POST_VARS is deprecated. Read up on the superglobals.

login or register to post comments

mwarden

Submitted by Kristopher on May 30, 2002 - 10:28.

ASP doesn't cost the same as PHP. PHP is free. Yes, there is a difference in operating system. NT cost money, Linux is free. *sighs*

login or register to post comments

HotScripts

Submitted by nainil on April 8, 2004 - 17:59.

Hi,

You might want to consider visiting
http://www.hotscripts.com/PHP/Tips_and_Tutorials/index.html

It has PHP tutorials on the following topics:

Ad Management (4)
Calendars (3)
Chat Systems (4)
Classified Ads (3)
Content Management (29)
Cookies and Sessions (18)
Counters (14)
Database-Related (98)
Date and Time (13)
Development (58)
Discussion Boards (8)
E-Commerce (8)
Email Systems (16)
Error Handling (4)
File Manipulation (25)
Flash and PHP (15)
Form Processing (38)
Guestbooks (7)
Image Manipulation (28)
Installing PHP (38)
Introduction to PHP (49)
Link Indexing (1)
Mailing List Management (10)
Miscellaneous (68)
Networking (5)
News Publishing (7)
PHP vs Other Languages (3)
Polls and Voting (2)
Postcards (1)
Randomizing (18)
Redirection (5)
Searching (11)
Security (16)
Site Navigation (11)
User Authentication (19)
WAP and WML (4)
Web Fetching (6)
Web Traffic Analysis (12)
XML and PHP (17)

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.