Coding Academy: write your first PHP script

PHP dates back to 1995 when its creator, Rasmus Lerdorf, began work on a scripting toolset dubbed Personal Home Page (PHP). The sudden demand for the toolset spurred Rasmus to further develop the language and, in 1997, version 2.0 was released with a number of enhancements and improvements from programmers worldwide. The version 2.0 release was hugely popular and spurred a team of core developers to join Rasmus in developing the language even further.

Version 3.0, in 1997, saw a rewrite and release of the parsing engine, and in 1998 it was estimated that more than 50,000 users were using PHP on their web pages. This version also saw the name change that we know now – PHP: Hypertext Preprocessor.

Fast-forward a year and with an estimated base of more than one million users, PHP was fast becoming one of the most popular languages in the world. Development continued at a frenzied pace with hundreds of functions being added. Two core developers, Zeev Suraski and Andi Gutmans, decided to rethink the way that PHP operated and so the parser was once again rewritten and released in version 4.0, dubbed the Zend scripting engine.

A few months after version 4.0 was released, Netcraft estimated that PHP had been installed on more than 3.6 million domains. Version 4.0 represented a massive leap forward at an enterprise and programming level, but the language still had some drawbacks, mainly due to its infancy.

Version 5.0 was released to the world in 2004 and with it came a myriad of improvements taking the language to a maturity – and installation peak; it’s thought that PHP is running on more than 20 million domains and it’s reported that it’s the most popular Apache module, available on almost 54% of all Apache installations. Version 6.0 is nearing public release and is intended to further improve the support, functionality and maturity of the language.

With websites such as Wikipedia, Facebook, Flickr and Digg all making use of it, it’s no wonder that PHP has become so widely adopted amongst web developers. Let’s see just how easy it is to get started with this dynamic, server-side scripting language.

Setup and installation

Most of the latest distributions of Linux come with PHP, so this tutorial already assumes that it’s been installed and set up on your Linux platform and is being parsed correctly through your web server of choice.

Although you can run PHP scripts via the command line, we’ll be using the browser (and therefore a web server) for this tutorial.

You can follow along by uploading your PHP files to a web server on the internet (if you have one). We’re using a default installation of Apache2 on our local Linux machine, though, because we find it easier and quicker to write and test PHP on a local machine instead of having to upload files via FTP each time.

If you require installation and/or setup instructions or guides for your local machine, we recommend reading the Installation on Unix Systems manual on the official PHP site, available at, there are hundreds of installation guides written for pretty much every flavour of Linux. Simply search Google for your distribution if the official guide doesn’t tick all the boxes.

Getting started

Now we get to the fun part – working with, and writing, our first PHP script. Historically, we’d write a basic “Hello World” script, but that can be, well, a little boring. Instead we’ll write some dynamic text output using PHP’s date() function.

Why Choose PHP?

PHP has long been a popular choice for web developers. Not only because it has a massive userbase, and therefore, support for developing (and debugging) your code is widely and freely available, but web servers or hosts with PHP installed and ready to use are ten-a-penny these days. The relative ease of the language has been one of the reasons for its massive uptake. PHP can also be very ‘forgiving’ when it comes to programming. For instance, you don’t have to declare your variables (or their type) before using or instantiating them and there are a couple of other ways in which you can bypass traditional programming methods. The easiest way to understand why PHP is so popular is to simply dive in and get started. If you’ve already worked with another programming language you’ll soon see just how easy PHP is to get to grips with. If this is your very first language, you’ll be pleasantly surprised at just how quickly you can get usable results.

Before we get into the real nitty gritty of the language, we must first understand how the interpreter reads in our PHP code and generates the necessary output.

One of the advantages of PHP is that you can embed your code directly into your static HTML pages – of which the entire page is sent directly to the interpreter. It’s extremely important to note that all of your PHP files must end in the .php extension. Embedding your PHP code in html or htm files means they won’t be run through the interpreter and won’t get executed – instead, you’ll just see the plain text code in your pages.

For your PHP code to be extracted from the rest of your content, it must be enclosed within delimiters. PHP will execute any code found within these delimiters – anything else is simply ignored by the interpreter. The default, and most common, delimiters that we use are to signal the end.

There are a few other options available for delimiters such as ‘short tags’, but some of these can have implications with XML and XHTML languages. For the purpose of this tutorial, we’re going to stick with the recommended default. With this in mind, open up your favourite text editor and write the following:

Save this file as welcome.php in your web server’s root folder – that is, the folder that your web server reads when you request the site in your browser. Once the file has been saved, open your web browser and point it to the file on your local web server, for me this is – this URL may differ based on your Linux setup/configuration. When run, you should simply see ‘Welcome to the world of PHP’ displayed in your browser.

If, instead, you see the raw PHP code, this means that you haven’t set up your web server to interpret your PHP files correctly. Go back, or find the relevant installation guide, and make sure you’ve followed all the steps outlined. If you successfully see the text without any PHP code, then we’re ready to move on.

Syntax, data types and functions

You’ll notice that we ended our code with a semi-colon before the closing delimiter. PHP uses a semi-colon to indicate the end of a line of code, or statement – without it PHP wouldn’t know when to stop evaluating our code, in turn breaking the script. PHP is very forgiving when it comes to formatting – it will ignore any white space and new lines (except when they’re contained inside string quotes) allowing you to be pretty free over how you format (indent etc) your code.

PHP supports many data types giving us enormous flexibility when writing our programs. To quote Wikipedia: “In computing, a data type is a classification identifying one of various types of data, such as floating-point, integer or Boolean.” PHP supports all of these data types and more, including strings and compound data types such as Arrays and Objects.

In the standard distribution of PHP, there are more than 1,000 functions available to use. These range from simple things such as date & time functions (which we’re using in this tutorial) to more advanced concepts such as LDAP and MySQL database functionality. For anything that’s missing (or something you want to improve) you can simply ‘roll your own’ function to give additional support. We won’t go into too much detail about functions here as we’ll be focusing on the basics and keeping things simple.

Flexible scripts

In our first example, we simply instructed PHP to output a specific string of text by using the echo function. The value of our string can come from many places – a database, the output of a function, a file on the server or even from user interaction on our site. By hard-coding this value we’re pretty much stuck on what the string value can be. Instead we’ll now assign the value to a variable, so open up a new file in your text editor, enter the code below and save it as welcome-var.php:

PHP 6 -- what's it all about?

So what can we expect in version 6? One of the core updates will be better support for Unicode strings, allowing for a much broader set of available characters to cover greater international support. For the more advanced developers, it’s bringing in better support for Namespaces. With the massive take up of Web 2.0 functionality, version 6 is also giving default support for the SOAP protocol and the library of XML features (for both reading and writing) are being overhauled. A handful of features are being dropped from the core language, these include magic_quotes(), register_globals(), register_long_arrays() and safe_mode(). The main reason is security related – some functions allowed for potential security holes to be exposed while others lead to poor programming practice. You can already download a developer version of PHP 6 to try out, but at the time of writing there’s no official public release date. Once it’s been released, you can expect a good wait before it’s available on public servers as most companies let it have a good run to iron out any bugs before installing it.

When you run this script you shouldn’t see any difference in output from the first file, however, first of all you’ll notice a new line starting with $display_text – this is known as a variable. Variables in PHP can hold a single piece of data at any one time. This data can change and can be of any type at any point.

Variables begin with a $ followed by the variable name, in this case, display_text. A variable can only begin with a letter or an underscore but the rest of the name can consist of any letters, underscores or numbers. An important note to be aware of is that variables are case-sensitive meaning that $Display_text is different (and a separate variable) from $display_text.

In our script above, we’re declaring and assigning the value simultaneously. Some languages do not allow this, however PHP is very flexible when it comes to programming. Value assignment is simply the process of copying a value to the assigned variable, such as:

$display_text = ‘Welcome to the world of PHP’;
$my_age = 29;

Typically, you would declare your variable before assigning a value but given the nature and context of this tutorial it’s acceptable to do the above.

The next line in our script simply changes from echo’ing the hard-coded string, to echo’ing the value of the variable (that we assigned in the previous line). Although they essentially do the same job of outputting the string value, this method allows us to be truly flexible with the output we see in the browser.

You can clearly see the rapid growth in PHP usage and the number of installations is still on the rise.

Time gentlemen, please

So far, so good... but static text is pretty boring. Let’s do something about that and add the date and time into the mix. For this, we’re going to make use of two things – the first is the date() function and the second is the concatenate operator. To concatenate means to combine two or more ‘things’ together to form one single entity; in this script we’re going to combine a welcome message with the date and time.

To do this, open up a new file in your text editor and enter the following code. Once you’ve done that save it as welcome-date.php:

When run, you should see the line of text with the current date and time embedded. It’s important to note that the date and time comes from the server and NOT your browser, as it would from a JavaScript program (or similar browser-based script).

The first line of our code is almost identical to the previous script; all we’ve changed here is the copy to reflect the more dynamic nature of the output. The second line is where the magic (also known as concatenation) happens. Essentially, and in non-computer talk, all the second line is saying is “print the display text, followed by the date command, then some more text, and finally append the date.”

You might be wondering how we’ve specified the date that gets printed. That’s all to do with the parameters that we supply to the date function. PHP’s date function accepts input parameters in order to represent exactly what value/string is returned from the function. It currently accepts 35+ date parameters, each one representing a unique ‘piece’ of date and/or time. In our example we’ve split the date and time into two different date() calls – it would be perfectly acceptable to merge them into one.

The more eagle-eyed readers amongst you will notice that I’ve hard-coded the text in the middle of the date functions. Again, this could be assigned to a variable instead (as we did for the initial text), for greater flexibility, in which case the line might look something like:

echo $display_text . date(‘l, jS F’) . $secondary_text . date(‘H:iA’);

For a full list of date input parameters, check out the date() function page of the official PHP docs: .

Putting it all together

We mentioned earlier that one of PHP’s great selling points is the ability to embed snippets of code into static HTML documents with ease.

This becomes apparent when we want to create ‘dynamic’ sections inside an otherwise static page, for example, our date script above. We could easily ‘drop’ this code into our existing template (if we have one). Let’s see how that might look:




In this case, I’ve pasted some trimmed and rudimentary HTML code and you can clearly see where I’ve embedded the PHP code to output my dynamic text on the page. The PHP code block can sit anywhere on the page and any amount of times inside a page – don’t be concerned if you have five, 10 or sometimes more code blocks within your HTML.

Something that’s really handy, is that internally, PHP will ‘communicate’ between each code block on your page. For example, if you set the value of a variable in the first code block at the top of your page, it will be available to the last code block at the bottom of your page. This can work wonders when you’re altering the display of the content based on the value of a variable elsewhere in the page – a really common use of this is a Login/Logout system where a user is presented with the Login or Logout options based on their logged in ‘state’.

Multiple updates

Don’t forget when doing this, that you must save your files with the .php extension otherwise your PHP code will fail to be executed and you’ll be left with plain text code on your page.

If you find that you’re adding the same block of code to multiple pages and you need to change it, going through each page and updating your code can be a treacherous job. Thankfully, PHP has got you covered. To help with this process, we can use the include() function. This allows us to write our PHP to a file (just as we have in our welcome-var.php file). Instead of embedding the full code in our HTML each time, we can instead do:

When the page is run, PHP will pick up the include() request and will read in and execute the code on that page, simply embedding the output – it works as if the code was directly on the page.

Facebook loves PHP so much. It even wrote its own Facebook Optimised version called HipHop.

A note of caution – the filename specified in the include() function is relative to the script that’s calling it, in other words, if your main HTML is located in the root folder and your welcome-var.php file is in a folder called scripts, your PHP code would look like this instead:

While it’s not quite rocket science, we’ve actually covered some pretty decent fundamentals about PHP. We’ve learned a little bit about how PHP got started and just how much it’s grown. You’ve been introduced to some basic, but core, programming skills and we’ve covered the basic syntax; by now you’re hopefully beginning to understand a little of PHP’s potential.

Over to you...

We’ve written our first script and now have first-hand experience of how easy it is to make use of PHP on a website. From here, why not play around further with the date example, try changing the input parameters to something different or even try embedding this code into an existing site. Have a look through the official PHP documentation online, and see what other functions PHP has to offer – you’ll be surprised how much you can achieve with just the standard installation. It’s worth bookmarking that URL as the more you use PHP the more you’ll use the website as a reference manual; and a great one at that.

Essential resources

There are plenty of books dedicated to learning PHP and it’s often hard to tell which one(s) to buy to steer you in the right direction. While I can’t help you chose the book that suits you the most, I can point you in the general direction of great ‘companion’ websites: The ultimate resource for anything PHP related. A taste of things that can be done with PHP. A great resource for any security related with PHP. Despite owning a few PHP books, I often find myself heading over to the official PHP documentation online – it’s often quicker than picking up a book and looking for the right page. For some inspiration, check out the second link – let your mind wander and think of something you’d love to build! The last link is equally important if you plan on installing PHP on a public-facing web server. Install the script, as it gives you some recommended base settings, then read up on general security practices.

John Doe

Articole publicate de la contributori ce nu detin un cont pe Continutul este verificat sumar, iar raspunderea apartine contributorilor.
  • | 340 articole

Nici un comentariu inca. Fii primul!
  • powered by Verysign