Showing posts with label IT. Show all posts
Showing posts with label IT. Show all posts

Before decrying the latest cyberbreach, consider your own cyberhygiene


The theft of 80 million customer records from health insurance company Anthem earlier this month would be more shocking if it were not part of a larger trend. In 2013, the Department of Defense and some US states were receiving 10–20 million cyberattacks per day. By 2014, there was a 27% increase in successful attacks, culminating with the infamous hack of Sony Pictures.

Much of the media focus is on the losses rather than the process by which such breaches take place. Consequently, instead of talking about how we could stop the next attack, people and policymakers are discussing punitive actions. But not enough attention is given to the actions of individual end users in these cyberattacks.


We are the unintentional insiders

Many of these hacking attacks employ simple phishing schemes, such as an e-card on Valentine’s Day or a notice from the IRS about your tax refund. They look innocuous but when clicked, they open virtual back doors into our organizations.

It is you and I who click on these links and become the “unintentional insiders” giving the hackers access and helping spread the infection. Such attacks are hard to detect using existing anti-virus programs that, like vaccines, are good at protecting systems from known external threats — not threats from within.

Clearly, this virtual battle cannot be won using software alone. In the same way personal hygiene stymies the spread of infectious disease, fixing this cyber quandary will require all of us to develop better cyberhygiene. We need to begin by considering the cyberbehaviors that lead to breaches.

My research on phishing points to three. Firstly, most of us pay limited attention to email content, focusing instead on quick clues that help expedite judgment. A picture of an inexpensive heart-shaped valentine gift gets attention, oftentimes at the cost of looking at the sender’s email address.

This is coupled by our ritualized media habits that our always-on and accessible smartphones and tablets enable. Many of us check emails throughout the day whenever an opportunity or notification arises, even when we know it is dangerous to do so, such as while driving. Such habitual usage significantly increases the likelihood of someone opening an email as matter of routine.

And finally, many of us just aren’t knowledgeable about online risks. We tend to hold what I call “cyber risk beliefs” about the security of an operating system, the safety of a program, or the vulnerability of an online action, most of which are flawed.

Sit on down and get educated.  Matt Grimm, CC BY-NC-SA


Cleaning up our cyberhygiene act

Developing cyberhygiene requires all of us — netizens, educators, local government, and federal policymakers — to actively engage in creating it.

To begin, we must focus on educating everyone about the risks of online actions. Most children don’t learn about cybersafety until they reach high school; many until college. More troublingly, some learn through risky trials or the reports of someone else’s errors.

In an age where online data remain on servers perpetually, the consequences of a privacy breach could haunt a victim forever. Expanding federal programs such as the National Initiative for Cybersecurity Education, which presently aims to inspire students to pursue cybersecurity careers, could help achieve universal cybersecurity education.

Second, we must train people to become better at detecting online fraud. At the very least, all of us must be made aware of online security protocols, safe browsing practices, secure password creation and storage, and on procedures for sequestering or reporting suspicious activity. Flawed cyber-risk beliefs must be replaced with objective knowledge through training.

Although some training programs address these issues, most target businesses that can pay for training. Left out are households and other vulnerable groups, which, given the recent “bring your own device to work” (BYOD) trend, increases the chances that a compromised personal device brings a virus into the workplace. Initiatives such as the Federal Cybersecurity Training Events that presently offer free workshops to IT professionals are steps in this direction, but the emphasis must move beyond training specialists to training the average netizen.

President Obama calls for beefing up cybersecurity laws on Feb 13, 2015. Kevin Lamarque / Reuters

Finally, we must centralize the reporting of cyber breaches. The President’s proposed Personal Data Notification and Protection Act would make it mandatory for companies to report data breaches within 30 days. But it still doesn’t address who within the vast network of enforcement agencies is responsible for resolution. Having a single clearing house that centralizes and tracks breaches, just like the Centers for Disease Control and Prevention tracks disease outbreaks across the nation, would make remediation and resource allocation easier.

Across the Atlantic, the City of London Police created a system called Action Fraud, which serves as a single site for reporting all types of cyberattacks, along with a specialized team called FALCON to quickly respond to and even address impending cyberattacks. Our city and state police forces could do likewise by channeling some resource away from fighting offline crime. After all, real world crime is at a historically low rate while cybercrimes have grown exponentially.


PHP: Build an online calendar


In the last tutorial, we covered the basics of PHP, including how the language was created and subsequently grew. Wewere also introduced to various parts of the language, such as variables, strings, integers and PHP’s internal date() function. In this tutorial, we’ll expand on those parts, but we’ll also introduce the concept of arrays and functions to make a fully working calendar.


We’ll assume that you have your Linux platform configured and serving PHP pages through your web browser, as outlined in the previous tutorial. If not, please refer to the previous article or the section titled Installing PHP on your Linux platform. So what exactly is an array? Well, to help us define this, let’s go back to the last tutorial, where we made use of a variable ($display_text) to hold a simple string message. The problem with variables is that they can hold only one piece of information at any one time. Wouldn’t it be great if we could store multiple items inside a variable? Well, this is where arrays come in.



Introducing arrays

The best way to think of an array is a special variable that holds other variables. An array allows you to hold as many items inside it as necessary (the only limitation on the size of the array is based on how much memory PHP is allocated). You can step through all the items inside an array (known as
traversing), and PHP comes with more than 70 functions, allowing you to perform certain actions on your array, such as searching inside, counting the number of items inside it, removing duplicate items, and even reversing the order.


“An array allows you to hold as many items inside it as necessary.”


There’s almost nothing to it when creating an array either: $data = array(); We have now created a new, empty array called $data.Arrays are structured using a key index and value data architecture. By default, when you add an item to an empty array, that item’s position in the array is 0. If you add another item, that item’s position becomes 1 in the array. You can also create your array with pre-populated data (if you already know what’s going to be in it). To do this, we just create the array as before, but this time we supply the data in a comma-separated list:

$data = array(‘Red’,
Orange’, ‘Yellow’, ‘Green’,
 ‘Blue’);

This is where the key system comes in to place. The way that PHP interprets this array will be as follows: 0 = ‘Red’, 1 = ‘Orange’, 2 = ‘Yellow’, 3 = ‘Green’ , 4 = ‘Blue’

As you can see, each key is associated to the value in the array. The most important part to remember is that arrays always start at key 0 and not key 1 as many might assume; it’s easy at first to forget.



Associative arrays

Arrays also have the flexibility of allowing us to specify our own keys (known as associative arrays). This helps a lot when you want to store a value against a specific key instead of having to rely on automatic indexes. Let’s say we wanted to store data about a person in an array; to do that we can do the following:

$person = array(‘name’ => ‘Mike Mackay’, ‘location’ =>
Essex’, ‘age’ => 29);

By using the associate instruction (=>), we’re telling PHP that we want to create a key called name and store the value Mike Mackay against it. You can store any data type in an array even other arrays. The way that PHP interprets our person array is how we would expect:

‘name’ = ‘Mike Mackay’, ‘location’ = ‘Essex’, ‘age’ = 29

When you want to use an array item, all you have to do is call the array and key you want: 
echo $data[0]; This echos out the word Red to the screen. To echo out the word Orange, you would simply change the key from 0 to 1. On our person array it’s just as simple  to echo the name to the screen, all I need to do is: echo $person[‘name’];



Add data to your array

If we have our existing array, but want to add more data to it, how do we accomplish that? There are a few ways in which we can do this and often it depends largely on whether your array has custom key indexes or not; but to add another item to our $data array we can simply do: $data[] = ‘Indigo’;

By supplying square brackets next to the array name, PHP recognises this action as wanting to push a value in to the array. PHP has a built-in function that does the same trick: 

array_push($data, ‘Indigo’);

This function takes a minimum of two arguments. The first is the array you want to push the data to, then any items afterwards are pushed to the end of the array. This conveniently allows you to push multiple items in to the array at once, for example: array_push($data, ‘Indigo’, ‘Violet’);

If you need only to push one item, the first method (using the square brackets) is recommended, as it has no system overheads of calling a function. If we wanted to add another item to our $person array, we need only to specify the key we wish to use, along with the required value:

$person[‘profession’] = ‘Developer’;



Arrays within arrays

As I mentioned before, an array can hold any type of item inside  this includes other arrays. The practice of multiple arrays is quite common, and you’ll find it extremely useful. Again, there are a couple of different ways of achieving this, and the one you use will be based on your array structure. For this example, let’s say we have an array of McLaren F1 racing drivers. Open up a text editor, enter the following PHP code and save it as drivers.php in your web root:

<?php
$drivers[] = array(
 ‘name’ => ‘Jenson Button’,
 ‘nationality’ => ‘British’,
 ‘championships’ => 1,
);
$drivers[] = array(
 ‘name’ => ‘Lewis Hamilton’,
 ‘nationality’ => ‘British’,
 ‘championships’ => 1,
);
?>

We’re using the square brackets to instruct PHP that we wish to push the driver data to the end of the array. Each item inside the master array() must be separated by a comma. Our $drivers array now contains two items these items are arrays of data containing driver information that we wish to display. In PHP’s eyes, the data for Jenson Button is located in $drivers[0], while the data for Lewis Hamilton is located in $drivers[1]. We could have created custom keys instead of using 0 and 1, but it’s not strictly worthwhile for this example. We could simply display the data using echo and then
specifying the array index key (such as $drivers[0]), but how would we display each item when we don’t know how long the array is? Thankfully for us, there’s a simple control function called foreach() that allows us to do this.

So you might be asking why we wouldn’t know the length of an array? Well, we know what driver data is contained in each item (name, nationality and championships), but a database query (or similar function) might return one driver, or it might return five drivers. We could get the the total number of items in the array by using a PHP function, but using foreach() is simpler and lets us write shorter code. The foreach() control gives us an easy way to iterate over an array. Using drivers.php that we’ve just created, copy the code just below the PHP block that contains the drivers array:

<?php
foreach($drivers as $driver) {
 echo ‘Name: ‘ . $driver[‘name’]. ‘<br />’;
 echo ‘Nationality: ‘ . $driver[‘nationality’]. ‘<br />’;
 echo ‘World Championships: ‘ . $driver[‘championships’].
 ‘<br /><br />’;
}
?>

When you view the file in your browser, you should see a basic list of drivers on your screen:


  •  Name: Jenson Button
  •  Nationality: British
  •  World Championships: 1
  •  Name: Lewis Hamilton
  •  Nationality: British
  •  World Championships: 1


Using a code editor that has built-in syntax checker (such as Eclipse, the
winner of our IDEs Roundup in LXF152) can save a lot of time and frustration!


On each loop of $drivers, the value of the current item is assigned to $driver (the first loop being Jenson Button), and the internal array pointer is moved on by one; so on the next loop you’ll get the next item from the array (Lewis Hamilton). This continues throughout each item in the array until the end is met. The foreach() function requires two parameters – the first is the array we want to loop through. We then use a PHP keyword as, then we enter a temporary variable name that we want to assign the loop item to (this variable is only available inside the loop). In literal terms, we’re saying: loop through each item in the $drivers array and store each driver item to a temporary array called $driver.

Hopefully, in the example you’ll recognise a few parts from the last tutorial; we’re echoing out a string concatenated by a variable  this being each bit of information about the driver in the array. We then concatenate another string which is HTML, allowing us to format the output in a basic manner. On the last array item, $driver[‘championships’], we echo out two line breaks; this just gives us a bit of separation between each driver. 

The 2012 F1 calendar we’ll be recreating with our code.




Let’s talk about functions

There are two types of functions in PHP:
1.  Built-in PHP functions, such as date() and array_push().
2.  User-defined functions.

We’ll be focusing on the second type for now (we’ve already covered a few built-in PHP functions).
A user-defined function is a special block of PHP code that we write that can perform custom operations any time it’s called. Some functions are written to manipulate data and then send that new value back, while others perform one-way operations, such as writing data to a file or inserting the data in to a database. To create a function, all we need to do is write the word function followed by the name we wish to call our function (It’s important to note that function names can only start with letters or underscores), followed by parenthesis and then a pair of curly braces:

function shout() {
}

We can also supply data, known as arguments, to our function to be used inside it. When calling this function and sending information to it, the function assigns this data to the internal variable called $text, where it can manipulate it, or do as required. This data is then held locally to the function
and does not overwrite any variables outside of it:

function shout($text) {
}

If we want the newly-modified data back, we can use return to send it back:

function shout($text) {
 return $text;
}

To call a function, all you need to do is write the function name followed by parenthesis either with or without any parameters (based on the function’s requirements): shout(); We have our basic function, but all it does is send back exactly what we sent to it - pretty pointless I’m sure you’ll
agree. Let’s make our function do something a bit more interesting. Create a new PHP file, copy the following code in to it and save it as function.php:

<?php
echo shout(‘Hello World’);
function shout($text) {
 return strtoupper($text);
}
?>

If you run that in your browser, you should see ‚‘HELLO WORLD’ being displayed. What’s happening is we’re sending a string straight to the function, where we echo the returned value out. The built-in PHP function strtoupper() has a simple purpose – take the string input and convert it to uppercase. We could modify the function to perform the echo inside instead of using return, but our original method gives us greater flexibility for multi-purpose use (we may not always want to echo a value out immediately). We could write any kind of code inside our function, and we’re not limited to doing string transformations.



If() and else()

You’ll notice something else with our code… we’ll be performing a conditional check using if() and else(). If/else provides a simple way of evaluating which code to run, based on the outcome of a particular check, or condition. If() is only executed when the condition inside the parenthesis equates (or returns) TRUE, otherwise else() is called – just the code between the curly braces is executed, but only one of them will ever be run:

if(condition is true) {
 // Run the code in this block
}
else {
 // Run the code in this block instead
}

In literal terms, all we’re going to say is: If today’s date is found as an index in the array, then echo out the race data, otherwise echo the no races message instead. Let’s now create a basic events calendar using our arrays and function knowledge. 



Put it all together

We don’t want anything over the top, so for now we’ll create an F1 2012 race calendar. We’ll send today’s date to a function and return a current race if one is happening on that day, otherwise we’ll echo out a generic message. Start off by creating a new PHP file called calendar.php, then create a function that initially holds an array of the race dates:

<?php
function is_race_day() {
 $race_dates = array(
 ‘18/3/2012’ => array(‘title’
 => ‘Australian Grand Prix’,
 ‘location’ => ‘Melbourne’),
 ‘25/3/2012’ => array(‘title’
 => ‘Malaysia Grand Prix’,
‘location’ => ‘Kuala
Lumpur’),
 15/4/2012’ => array(‘title’ => ‘Chinese Grand Prix’,
‘location’ => ‘Shanghai’),
 ‘22/4/2012’ => array(‘title’ => ‘Bahrain Grand Prix’,
location’ => ‘Sakhir’),
 ‘13/5/2012’ => array(‘title’ => ‘Spanish Grand Prix’,
‘location’ => ‘Catalunya’),
 );
}
?>

I’ve included just the first five dates of the season for now, but feel free to add more. Next, let’s update the function. Get today’s date (see the first tutorial on the date() function) and check whether it has a Grand Prix or not; for this we’ll use a built-in function, array_key_exists().


“Get today’s date and check whether it has a Grand Prix or not.”


Write the following just below the end of the array and before the functions’ closing curly brace:

$date = date(‘m/d/Y’);
if(array_key_exists($date, $race_dates)) {
 echo “Today’s race is the “ . $race_dates[$date][‘title’] . “ in “
 . $race_dates[$date][‘location’] . “.”;
}
else {
 echo “There is no race today.”;
}

We use the value of $date inside the array_key_exists() function  this function accepts two parameters: the first is the key you’re looking for (in our case it’s the date) and the second is the array you wish to check against (our $race_dates array). The array_key_exists() function returns a boolean of TRUE if the key exists, or FALSE if it doesn’t. If the race is found, we’re going to echo out the race details. We can retrieve this data because we know the key exists, therefore we use the $date variable as a shortcut to retrieve the information. Essentially, it’s the same as writing:

 echo $race_dates[‘13/5/2012’]
 ‘title’];

All that’s left for us to do is to call the script. We do this in exactly the same way as our earlier function script and put the function name (with parenthesis) at the top of our script:

is_race_day();

We can then run this script in our browsers by going to calendar.php, or we can use includes() to embed it on an existing website. If a race exists on the day the script is run, we’ll be presented with the details. To test this, simply hardcode a date in the $date variable: 

$date = ‘13/5/2012’;



And with that, we’re done!

This might all feel like quite a lot to take in at once if you’re new to arrays and functions, but hopefully you’ll see that what we’ve learnt here is extremely important and intrinsic to programming. Try modifying the calendar; you could be more specific with your dates and have something on every day of a month if you wish. As an exercise, look at the date() function and alter the calendar to echo messages based on the hour of the day. Remember, you won’t need an entry for every day  only every hour. 

In the following tutorial Mike Mackay explains how to add the functionality to dynamically select races and view details. 

Be sure you subscribe to our Newsletter below :)

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