PHP: Write your first script


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 http://php.net/manual/en/install.unix.php.

Alternatively, 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.

The PHP website might not be the most eye-catching in the world, but it’ll be a
site you return to time and time again.


Getting started

Now we get to the fun part – working with, and writing, ourfirst 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. 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.

Easy embedding

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 <?php to indicate the start of our code and ?> 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:

<?php echo ‘Welcome to the world of PHP’; ?>

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 http://127.0.0.1/welcome.php – 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 thatyou 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
$display_text = ‘Welcome to world of PHP’;
echo $display_text;
?>

When you run this script you shouldn’t see any difference in output from the first file, but first you’ll notice a new line starting with $display_text. This is 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.

Believe it or not we used to write all our PHP code in Notepad, then we realised
how much nicer life is in colour. Text editors are heaven to coding eyes.
We are using Macromedia Dreamweaver

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 echoing the hard-coded string, to echoing 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.

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. As we’ve mentioned earlier in this o 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:
<?php
$display_text = ‘Welcome to the world of PHP. It is ‘;
echo $display_text . date(‘l, jS F’) . ‘, and the time is ‘ .
date(‘H:iA’);
?>

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.”

“To concatenate means to combine two or more ‘things’ together.”

At this point you might be wondering how we’ve specified the date that gets printed. That is 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 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: http://php.net/manual/en/function.date.php.


Put 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:

<html>
...
<body>
 <div id=”welcome-text”>
 <?php
 $display_text = ‘Welcome to the world of PHP. It is ‘;
 echo $display_text . date(‘l, jS F’) . ‘, and the time is ‘ .
date(‘H:iA’);
 ?>
 </div>
 ...
</body>
</html>

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:

<?php include(‘welcome-var.php’); ?>

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.

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:

<?php include(‘scripts/welcome-var.php’); ?>

While it’s not quite rocket science, we’ve actually covered some pretty decent fundamentals about PHP in this tutorial. We have 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.”

By now you’re hopefully beginning to understand a little of PHP’s potential, and be ready to tackle the next part of this chapter.

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. 

Take a few minutes to have a look through the official PHP documentation online, www.php.net/manual/en 
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.
On the next article, we will learn how to Build an Online Calendar in PHP.

Credits: Coding Academy UK

Make sure you subscribe to our Newsletter below so you won't miss a PHP lesson :)

Express Science Lab Engineer & Science Enthusiasm

Experience the Science of the Universe and IT Programming into a fun and creative way. Ever been fascinated about how the Universe works, about planets, Solar Systems and how to program a computer to write a code for you, ever asked yourself how a website works ? Let's find out, come step into your own laboratory of knowledge.

No comments:

Post a Comment

Shout here! Throw the pipettes, brake a Berzelius glass so we can hear you from the lab!