Category: PHP

Building a moderately complex Web page requires understanding a whole stack of technologies, from HTML to JavaScript. Now a researcher from the Massachusetts Institute of Technology (MIT) has wrapped these technologies into a single language that could streamline development, speed up performance and better secure Web sites.

The language, called Ur/Web, provides a way for developers to write pages as self-contained programs. It incorporates many of the most widely used Web technologies, freeing the developer from working with each language individually.

“I think this is a language with potential broad applicability to reduce costs of Web development in many different settings,” said Ur/Web’s author, Adam Chlipala, an MIT computer science assistant professor. “It brings some well-ad understood software engineering advantages to aspects of the Web that have been handled in more ad hoc ways.”

Chlipala will present his work next month at the Association for Computing Machinery’s Symposium on Principles of Programming Languages.

Developing a Web site requires understanding a range of different languages, as well as how they interact.

Hypertext Markup Language (HTML) offers basic formatting for the Web page, but there is a whole range of adjoining Web technologies that are usually deployed as well: Cascading Style Sheets (CSS) provides a way to modify the look of a Web page, and the Extensible Markup Language (XML) structures data for additional processing and classification. JavaScript provides the foundation for writing the business logic for user interactions. And if data is stored in a database, a developer will need to know SQL (Structured Query Language) as well.

Ur/Web encapsulates all the capabilities of such Web development tools within a single language, which is compiled into machine executable code.

Because Ur/Web code is compiled, it can be substantially more efficient to run than code from commonly used Web development languages, Chlipala said.

“In Ur/Web, everything is based on transactions, where a single client request is handled by what looks like an uninterrupted execution of a single function,” Chlipala said. “The language implementation has optimizations in it to support running many requests in parallel, on real servers. But the programmer can pretend everything is a transaction and think in a simpler concurrency model.”

In addition to potentially lessening the cognitive burden for developers, Ur/Web’s top-down approach offers some safety mechanisms that could make Web sites more secure.

The language prohibits unintended interactions among different page elements. With this limit in place, embedded code for supplying ads could not interfere with a calendar widget elsewhere on the page, for example.

Also, like traditional programming languages such as C and Java — and unlike Web languages such as JavaScript — Ur/Web is strongly typed. This means all variables and functions must conform to a preset data type, which limits the ability of an attacker to send maliciously formatted data through a Web form. Ur/Web also supports variable scoping, or the ability to limit where a variable can be called within a program.

The language does have a potential downside. For the average Web developer, Ur/Web could require a “very steep” learning curve, Chlipala admitted. It is what is known as a functional programming language, a style of programming that treats programs as a series of functions, which can be computationally more efficient but harder to learn for a programmer versed in more widely used procedural or object-oriented languages.

Chlipala compared Ur/Web to Haskell, a functional programming language considered esoteric by many programmers yet loved by a dedicated community that praises its computational functionality.

Chlipala is one of a number of MIT researchers who have been pushing the frontiers of software programming languages of late. Another MIT researcher is designing a language called Sketch that can automatically complete sections of code for a program being written. Another MIT effort, dubbed Stack, is designed to identify parts of code that compilers routinely disregard but that nonetheless could be useful.

News Source : ( | Image Source : Searched via Google Images

Google on Monday gave traditional Google plug-ins a stay of execution and instead outlined a three-step plan that will finalize their demise in 10 months.

The delay was the latest move in a year-long plan by Google to ban plug-ins built to a decades-old standard, a decision it has pitched as a security enhancement.

NPAPI (Netscape Plug-in Application Programming Interface) is the plug-in standard that harks back to Netscape, the 1990s browser that Microsoft buried in its antitrust-triggering battle over the browser market. NPAPI has long been the most popular plug-in standard, and is still supported by Apple’s Safari, Mozilla’s Firefox and Opera Software’s Opera. (Microsoft’s Internet Explorer (IE) has always relied on its own proprietary ActiveX architecture.)

But NPAPI has been criticized for slack security, with years of plug-in hacking proving opponents right. In response, Google has pursued its own plug-in architecture, dubbed PPAPI (Pepper Plugin API), pronounced “pepper,” that runs code inside a “sandbox,” an anti-exploit technology designed to at least hinder hackers from pushing malware onto machines.

Opera is the only other browser that currently supports NPAPI — not surprising, since it’s built atop the same browser engine that powers Chrome.

In September 2013, Google announced it would pull support for all NPAPI plug-ins from Chrome by the end of 2014. The Mountain View, Calif. company reiterated that pledge in May, although it hedged by applying the word “probably” to the timeline.

The end-of-2014 deadline has now been extended.

In a blog post Monday, Justin Schuh, a Google software engineer, provided an update that spelled out a new three-step process to gradually reduce NPAPI support rather than yank it in one quick move.

“Although plug-in vendors are working hard to move to alternate technologies, a small number of users still rely on plug-ins that haven’t completed the transition,” Schuh said to explain the change.

Those “alternate technologies” for managing and playing video and audio, generating other content, and serving as foundations for Web-based apps are predominately, but not exclusively, based on HTML5 and JavaScript.

In January, Google will discontinue the “whitelist” that currently lets only a handful of NPAPI plug-ins, including Oracle’s Java and Microsoft’s Silverlight, run without popping up a warning. At that point, NPAPI plug-ins will continue to work within Chrome, but all will present a pop-up alert and require user approval.

Come April 2015, Chrome will stop supporting NPAPI plug-ins by default, although users can override the ban. Consumers can switch support back on via the chrome://flags options, while corporations running the browser can do the same through the Google Apps control panel or Windows’ Group Policy. Also in April, Google will pull add-ons that require a NPAPI plug-in from the Chrome Web Store.

Chrome will finally be stripped of all NPAPI support in September 2015, when even an override won’t work.

As Google continues to deprecate NPAPI plug-ins and eventually eliminate support, some users may need to run an alternate browser — such as Firefox, Opera or Safari — to interact with sites that require the older technology.

“What about Web pages, like most — if not all — banks in Brazil, that need Java?” asked one user in a comment appended to Schuh’s blog.

Google offered more information on its Chrome plug-in strategy in a developers guide available on its website.

News Source : ( | Image Source : Searched via Google Images

Some fairly large Internet services are pressing into production Facebook’s open-source PHP runtime engine after being impressed with the performance metrics for the alternative to the ubiquitous open-source PHP package used across the Web.

WordPress hosting site WP Engine has found that the Facebook HipHip Virtual Machine (HHVM) executes PHP commands 5.6 times faster than a standard PHP interpreter.

“PHP, compared to HHVM, is wicked slow,” said Tomas Puig, WP Engine’s director of labs. “So I saw an opportunity for us to use HHVM to drive WordPress.”

Enterprise-focused cloud storage provider Box is also using the technology and has been pleased by the results — average request latency dropped by a factor of three when using HHVM.

“The performance gains we’re seeing with HHVM exceeded all expectations,” wrote Box engineer Joseph Marrama, in a blog post announcing Box’s use of HHVM. “Almost every request that touches Box goes through our PHP codebase, so the speed increase is felt almost everywhere.”

Facebook engineers created HHVM as a way to speed the social networking service, which was written largely in the PHP Web development language. Facebook found that many programmers were versatile with the open-source language, which was created in 1994 and is one of the most widely used languages on the Internet.

For Facebook, however, PHP’s performance left something to be desired. PHP itself translates the programmer code to machine code only when it is called by the user, which slows performance. So company engineers created a virtual machine that, like the Java Virtual Machine, would translate the code into machine-readable bytecode just before running it. If the code needed to be used again, a bytecode-ready version would be available in the cache ready to go.

HHVM now powers much of Facebook, with other Web companies starting to use it as well.

WP Engine is one of the largest providers of WordPress hosted services for enterprises. Built on PHP, the open-source WordPress content management platform is increasingly being used for powering rich Internet applications, such as providing the back end for mobile apps and cloud services.

WP Engine recently built its next-generation platform, called Mercury, for running WordPress on HHVM. The company found that Mercury had a 560 percent faster response time than the traditional PHP setup. The company is currently testing the platform, which is also running the site for Web consultancy firm 10up in full production mode.

Box already has HHVM running in production mode to power its core Web storage application, which is used by over 27 million people.

The company first looked at HHVM a couple of years ago, but found it would require too much work porting its code to HHVM. The development team behind HHVM, however, has since made it a priority to offer full compatibility with PHP, which swayed Box to use the technology.

Box did run into some transition challenges. One was the migration from the Apache Web server, which provided an PHP interpreter. HHVM runs an internal copy of the high- performance Nginx Web server instead. The Box engineering team also found a number of bugs in HHVM and sent fixes to the HHVM development team.

Because it is a just-in-time compiler, HHVM requires the code to be called a few times before the performance improvements kick in, to “warm up” the cache with material ready to be served, which was something else Box engineers had to get used to. Box changed internal operations to allow for a brief warm-up time before a new instance of HHVM goes live.

Puig agreed that moving to HHVM requires some up-front work.

“Supporting it from an infrastructure perspective is much better than loading a bunch of servers on a virtual machine with cPanel,” Puig said, referring to the open-source Web hosting control panel cPanel.

Source from : ( | Image Source : Searched via Google Images

Continuing to roll out new compute services at an impressive clip, Amazon Web Services has introduced a way for programmers to trigger operations in their AWS deployments without running a full virtual machine, potentially reducing maintenance work and cost.

The service, called AWS Lambda, will provide a virtual space for programmers to run scripts or business logic programs that can be activated when some event occurs, such as a user uploading a photo. The script can then trigger other services in the AWS arsenal, such as storing the photo on Amazon S3 (Simple Storage Service), or execute other operations, such as generating a series of thumbnails based on the photo. Lambda could be used to coordinate operations of complex event-driven back-end services, according to the company.dsc06122

“You can write code without having to manage any infrastructure,” said AWS chief technology officer Werner Vogels, who introduced the technology during his keynote Thursday at the company’s Re:Invent user conference in Las Vegas. “Your code will only run when needed. You can run it once a month, or run thousands of these functions a second.”

Al Hilwa, a software development analyst for IDC, said the Lambda service was born of the need to do small amounts of processing based on event triggers. “But the availability of such a simple service at an attractive price and pricing model is far reaching in its implications,” he wrote in an e-mail. “I predict there will be significant applications that will be built incrementally using this functional programming approach.”

For those running multiple AWS services as a single operation, coordinating these services usually involves running a program on a full Amazon virtual machine (VM). Lambda does away with the need to run a separate VM, as well as the chore of installing and maintaining the software needed to run the program. Instead, Lambda provides just a language runtime environment for running just the program itself.

“You are essentially just thinking about your code and what will trigger your code. We deal with all the rest,” said Ariel Kelman, AWS head of worldwide marketing, in a follow-up interview.

Lambda initially will run code written in JavaScript. To power Lambda, Amazon is running a version of the Node.js, a server-side JavaScript runtime environment. Any external JavaScript library can be used with Lambda, allowing developers to import their own sets of functionality or use third-party sources. Additional languages will be supported in the future.

A Lambda service can be triggered by an event that occurs in another AWS service. Initially, the service can recognize only events that occur in S3, the DynamoDB database service, or in the Amazon Kinesis real-time streaming service. Most all AWS services will eventually be supported, Kelman said.

Lambda seemed to excite the developer-heavy crowd at Re:Invent; the company held an explanatory technical session immediately after the keynote that packed a large meeting room.

Still, not all attendees were sold on the service immediately. Sean Du, a software architect for a financial services company that uses AWS, was concerned the service could potentially lock customers into AWS, because it incorporates higher-level business logic, rather than the generic infrastructure services that can be found elsewhere.

Lambda will also need debugging and testing tools, especially as the scripts people write may grow more complex, Du added.

AWS Lambda pricing will be based on the amount of compute time used to run the script, in increments of 100 milliseconds. The company is offering a preview of the service and expects to offer the full commercial version in 2015.

Lambda was one of a number of new services the company introduced at the Re:Invent conference. Vogels also detailed how AWS will start supporting Docker containers, a virtualization technology that provides a way to package applications so they can be easily deployed and moved around.

On Wednesday, the company introduced a new high-performance database service modeled on MySQL, called Aurora, and previewed a set of management tools for managing the development of new applications.

Source from : ( | Image Source from: Searched via Google Images


In the past 6 parts of this tutorial I have shown you the basics of writing PHP. In this final part I will show you a few small things which don’t really warrant a section of their own.


As with any programming language, it is quite important to comment in your script. If you are working on a script with someone else you must let them know what you code does and if you are distributing your script you will need to show people how to edit it. Even if you are the only one who will use your script it is useful to comment so that you can edit it at a later date.

In PHP there are two ways you can comment. One way is used for single line comments and the other is used mainly for comments that go over one line. A single line comment is written as follows:

// Your comment can go in here

Everything after the // will be ingnored when the script is executed. You can even place these on the end of another line e.g.

print “Hello $name”; // Welcome to the user

Another way of commenting is by using multi-line comments:

/* The following piece of code will take the input
the user gave and will check that it is valid before
adding it to the database */

Anything between the /* and the */ will be ignored. It is important that you always close this type of comment as not doing so could make your script not work.

Print, Echo and HTML

As you may have noticed during this tutorial I have actually used 4 different ways of outputting information to the browser:

echo(“Text here”);
echo “Text here”;
print(“Text here”;
print “Text here”;

To clarify, all of these do the same thing and you can use any or all of them in a script. There is no reason to even use the same type all through a script. The only problem you may find is that, as I explained in part 2, all the ” in the HTML code must be replaced with \” which, if you have a lot of code, could take a very long time. This brings me to a very useful part of PHP. If, for example, you created the header of a page dynamically in PHP, then had the static page and finally a dynamic footer you can do the following:

Top PHP code in here
Bottom PHP code in here

This gets even better as the PHP code will just continue from where it was left off so you could do the following:

IF Statement {
HTML For IF Being Correct
} else {
HTML For IF Being Wrong

You must always remember to close IF statements and loops, though, as it is very easy to forget.

One Line Prints

Being able to place HTML code into your PHP is very useful, but what happens if you want to put the value of a variable into the code. Unlike when using an echo or print statement, you can’t just put in the variable name as this section is not actually part of the PHP code. Instead you must just put in a little PHP.

For example if you wanted to print someone’s name from a script with HTML formatting you would do the following:

<font face=”Arial” size=”7″ color=”red”><b><? echo($variablename); ?></b></font>

In the above code you have just added in the following PHP:

<? echo($variablename); ?>

Which is exactly the same as the following PHP code:


But all put onto one line.


This tutorial has given you some of the basics of PHP and should allow you to do most things you will want to. For a much more in depth look you should visit, the official homepage of PHP. One major omission of this tutorial, you may have noticed, is using PHP with a database. As this is one of the major reasons that people use PHP and because there are many options
I will put this in a separate PHP/MySQL tutorial.


In the last part, I showed you how to use PHP to send e-mail messages using a script. In this part I will continue this and also show you how to use PHP and forms together to make your PHP scripts useful.

Setting Up Your Form

Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial I will not go into depth in how to write your form but I will show you three of the main pieces of code you must know:

<input type=”text” name=”thebox” value=”Your Name”>

Will display a text input box with Your Name written in it as default. The value section of this code is optional. The information defined by name will be the name of this text box and should be unique.

<textarea name=”message”>
Please write your message here.

Will display a large scrolling text box with the text ‘Please write your message here.’ as default. Again, the name is defined and should be unique.

<input type=”submit” value=”Submit”>

This will create a submit button for your form. You can change what it says on the button by changing the button’s value.

All the elements for your form must be enclosed in the <form> tags. They are used as follows:

<form action=”process.php” method=”post”>
Form elements and formatting etc.

The form’s action tells it what script to send its data to (in this case its process.php). This can also be a full URL (e.g. The method tells the form how to submit its data. POST will send the data in a data stream to the script when it is requested. GET is the other option. GET will send the form data in the form of the url so it would appear after a question mark e.g.

It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser’s address bar.

Getting The Form Information

The next step is to get the data the form has submitted into your script so that you can do something with it. This is. There are basically two different methods of getting the data into PHP, which depend on how they were submitted. There are two submission methods, GET and POST, which can both be used by forms. The difference between the two is that using GET, the variables and data will be shown in the page address, but using POST it is invisible. The benefit of GET, though is that you can submit information to the script without a form, by simply editing the URL.

This works the same as submitting a form using GET. The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For example you could create a script which will show different pages depending on the link clicked:

could show David’s page and:
could show Tom’s page, using the same script.

It is also possible to pass more than one piece of information to the script using this system by separating them with the & symbol:


These could all be accessed separately using the GET variables user, referrer and area.

To get a variable which has been sent to a script using the POST method you use the following code:
which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variablename.

Similarly, if you are using the GET method you should use the form:

This should be done for each variable you wish to use from your form (or URL).

Creating The Form To Mail Script

To finish off this section, I will show you how to use what you have learnt in this part and the last to create a system which will e-mail a user’s comments to you.

Firstly, create this form for your HTML page:

<form action=”mail.php” method=”post”>
Your Name: <input type=”text” name=”name”><br>
E-mail: <input type=”text” name = “email”><br><br>
<textarea name=”comments”></textarea><br><br>
<input type=”submit” value=”Submit”>

This will make a simple form where the user can enter their e-mail address, their name and their comments. You can, of course, add extra parts to this form but remember to update the script too. Now create the PHP script:

function checkOK($field)
if (eregi(“\r”,$field) || eregi(“\n”,$field)){
die(“Invalid Input!”);

$message=”$name just filled in your comments form. They said:\n$comments\n\nTheir e-mail address was: $email”;
if(mail($to,”Comments From Your Site”,$message,”From: $email\n”)) {
echo “Thanks for your comments.”;
} else {
echo “There was a problem sending the mail. Please check that you filled in the form correctly.”;

Remember to replace with your own e-mail address. This script should be saved as mail.php and both should be uploaded. Now, all you need to do is to fill in your comments form.

The first part of that script may look a bit strange:

function checkOK($field)
if (eregi(“\r”,$field) || eregi(“\n”,$field)){
die(“Invalid Input!”);

You don’t really need to worry about what this is doing, but basically, it stops spammers from using your form to send thier spam messages by checking special characters are not present in the input which can be used to trick the computer into sending messages to other addresses. It is a fuction which checks for these characters, and if they are found, stops running the script.

The lines:


etc. run this check on each input to ensure it is valid.


One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.

The Mail Command

Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:


In this example I have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail.

The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mai but you can also include other headers like cc and bcc.

Sending An E-mail

Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:

$to = “”;
$subject = “PHP Is Great”;
$body = “PHP is one of the best scripting languages around”;
$headers = “From:\n”;
echo “Mail sent to $to”;

This code will acutally do two things. Firstly it will send a message to with the subject ‘PHP Is Great’ and the text:

PHP is one of the best scripting languages around

and the e-mail will be from It will also output the text:

Mail sent to

to the browser.

Formatting E-mail

Something you may have noticed from the example is that the From line ended with \n. This is acutally a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.

The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.

Mail Without Variables

The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:

mail(“”,”PHP Is Great”,”PHP is one of the best scripting languages around”,”From:\n”);

But that would make your code slightly harder to read.

Error Control

As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:

if(mail($to,$subject,$body,$headers)) {
echo “An e-mail was sent to $to with the subject: $subject”;
} else {
echo “There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid”;

This code is quite self explanitory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.


In the last parts of this tutorial I have showed you how to deal with text and variables in PHP and how you can use IF statements to compare them and to make decisions. In this part I am going to show you how to use another important part of PHP, loops.

The WHILE Loop

The WHILE loop is one of the most useful commands in PHP. It is also quite easy to set up and use. A WHILE loop will, as the name suggests, execute a piece of code until a certain condition is met.

Repeating A Set Number Of Times

If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop. For instance if you wanted to print out the words “Hello World” 5 times you could use the following code:

$times = 5;
$x = 0;
while ($x < $times) {
echo “Hello World”;

I will now explain this code. The first two lines are just setting the variables. The $times variable holds the number of times you want to repeat the code. The $x variable is the one which will count the number of times the code has been executed. After these is the WHILE line. This tells the computer to repeat the code while $i is less than $times (or to repeat it until $i is equal to $times). This is followed by the code to be executed which is enclosed in { }.

After the echo line which prints out the text, there is another very important line:


What this does is exactly the same as writing:

$x = $x + 1;

It adds one to the value of $x. This code is then repeated (as $x now equals 1). It continues being repeated until $x equals 5 (the value of times) when the computer will then move on to the next part of the code.

Using $x

The variable counting the number of repeats ($x in the above example) can be used for much more than just counting. For example if you wanted to create a web page with all the numbers from 1 to 1000 on it, you could either type out every single one or you could use the following code:

$number = 1000;
$current = 0;
while ($current < $number) {
echo “$current<br>”;

There are a few things to notice about this code. Firstly, you will notice that I have placed the ++$current; before the echo statement. This is because, if I didn’t do this it would start printing numbers from 0, which is not what we want. The ++$current; line can be placed anywhere in your WHILE loop, it does not matter. It can, of course, add, subtract, multiply, divide or do anthing else to the number as well.

The other reason for this is that, if the ++$current; line was after the echo line, the loop would also stop when the number showed 999 because it would check $current which would equal 1000 (set in the last loop) and would stop, even though 1000 had not yet been printed.


Arrays are common to many programing languages. They are special variables which can hold more than one value, each stored in its own numbered ‘space’ in the array. Arrays are extremely useful, especially when using WHILE loops.

Setting Up An Array

Setting up an array is slightly different to setting up a normal variable. In this example I will set up an array with 5 names in it:

$names[0] = ‘John’;
$names[1] = ‘Paul’;
$names[2] = ‘Steven’;
$names[3] = ‘George’;
$names[4] = ‘David’;

As you can see, the parts of an array are all numbered, starting from 0. To add a value to an array you must specify the location in the array by putting a number in [ ].

Reading From An Array

Reading from an array is just the same as putting information in. All you have to do is to refer to the array and the number of the piece of data in the array. So if I wanted to print out the third name I could use the code:

echo “The third name is $names[2]”;

Which would output:

The third name is Steven

Using Arrays And Loops

One of the best uses of a loop is to output the information in an array. For instance if I wanted to print out the following list of names:

Name 1 is John
Name 2 is Paul
Name 3 is Steven
Name 4 is George
Name 5 is David

I could use the following code:

$number = 5;
$x = 0;
while ($x < $number) {
$namenumber = $x + 1;
echo “Name $namenumber is $names[$x]<br>”;

As you can see, I can use the variable $x from my loop to print out the names in the array. You may have noticed I am also using the variable $namenumber which is always 1 greater than $x. This is because the array numbering starts from 0, so to number the names correctly in the output I must add one to the actual value.


Over the past two parts I have shown you the basics of text in PHP and how to store it as variables. In this part of the tutorial I will show you how to use IF statements to make decisions in your scripts.

The Basics Of IF

If statements are used to compare two values and carry out different actions based on the results of the test. If statements take the form IF, THEN, ELSE. Basically the IF part checks for a condition. If it is true, the then statement is executed. If not, the else statement is executed.

IF Strucure

The structure of an IF statement is as follows:

IF (something == something else)
THEN Statement
} else {
ELSE Statement


The most common use of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example:

if ($username == “webmaster”)

which would compare the contents of the variable to the text string. The THEN section of code will only be executed if the variable is exactly the same as the contents of the quotation marks so if the variable contained ‘Webmaster’ or ‘WEBMASTER’ it will be false.

Constructing The THEN Statment

To add to your script, you can now add a THEN statement:

if ($username == “webmaster”) {
echo “Please enter your password below”;

This will only display this text if the username is webmaster. If not, nothing will be displayed. You can actually leave an IF statement like this, as there is no actual requirement to have an ELSE part. This is especially useful if you are using multiple IF statements.

Constructing The ELSE Statement

Adding The ELSE statement is as easy as the THEN statement. Just add some extra code:

if ($username == “webmaster”) {
echo “Please enter your password below”;
} else {
echo “We are sorry but you are not a recognised user”;

Of course, you are not limited to just one line of code. You can add any PHP commands in between the curly brackets. You can even include other IF statments (nested statements).

Other Comparisons

There are other ways you can use your IF statement to compare values. Firstly, you can compare two different variables to see if their values match e.g.

if ($enteredpass == $password)

You can also use the standard comparision symbols to check to see if one variable is greater than or less than another:

if ($age < “13”)

Or :

if ($date > $finished)

You can also check for multiple tests in one IF statement. For instance, if you have a form and you want to check if any of the fields were left blank you could use:

if ($name == “” || $email == “” || $password == “”) {
echo “Please fill in all the fields”;


In the last part of the tutorial I explained some of the advantages of PHP as a scripting language and showed you how to test your server for PHP. In this part I will show you the basics of showing information in the browser and how you can use variables to hold information.

Printing Text

To output text in your PHP script is actually very simple. As with most other things in PHP, you can do it in a variety of different ways. The main one you will be using, though, is print. Print will allow you to output text, variables or a combination of the two so that they display on the screen.

The print statement is used in the following way:

print(“Hello world!”);

I will explain the above line:

print is the command and tells the script what to do. This is followed by the information to be printed, which is contained in the brackets. Because you are outputting text, the text is also enclosed instide quotation marks. Finally, as with nearly every line in a PHP script, it must end in a semicolon. You would, of course, have to enclose this in your standard PHP tags, making the following code:

print(“Hello world!”);

Which will display:

Hello world!

on the screen.


As with other programming languages, PHP allows you to define variables. In PHP there are several variable types, but the most common is called a String. It can hold text and numbers. All strings begin with a $ sign. To assign some text to a string you would use the following code:

$welcome_text = “Hello and welcome to my website.”;

This is quite a simple line to understand, everything inside the quotation marks will be assigned to the string. You must remember a few rules about strings though:

Strings are case sensetive so $Welcome_Text is not the same as $welcome_text
String names can contain letters, numbers and underscores but cannot begin with a number or underscore
When assigning numbers to strings you do not need to include the quotes so:

$user_id = 987

would be allowed.

Outputting Variables

To display a variable on the screen uses exactly the same code as to display text but in a slightly different form. The following code would display your welcome text:

$welcome_text = “Hello and welcome to my website.”;

As you can see, the only major difference is that you do not need the quotation marks if you are printing a variable.

Formatting Your Text

Unfortunately, the output from your PHP programs is quite boring. Everything is just output in the browser’s default font. It is very easy, though, to format your text using HTML. This is because, as PHP is a server side language, the code is executed before the page is sent to the browser. This means that only the resulting information from the script is sent, so in the example above the browser would just be sent the text:

Hello and welcome to my website.

This means, though, that you can include standard HTML markup in your scripts and strings. The only problem with this is that many HTML tags require the ” sign. You may notice that this will clash with the quotation marks used to print your text. This means that you must tell the script which quotes should be used (the ones at the beginning and end of the output) and which ones should be ignored (the ones in the HTML code).

For this example I will change the text to the Arial font in red. The normal code for this would be:

<font face=”Arial” color=”#FF0000″>

As you can see this code contains 4 quotation marks so would confuse the script. Because of this you must add a backslash before each quotation mark to make the PHP script ignore it. The code would chang
e to:

<font face=\”Arial\” color=\”#FF0000\”>

You can now include this in your print statement:

print(“<font face=\”Arial\” color\”#FF0000\”>Hello and welcome to my website.</font>”);

which will make the browser display:

Hello and welcome to my website.

because it has only been sent the code:

<font face=”Arial” color=”#FF0000″>Hello and welcome to my website.</font>

This does make it quite difficult to output HTML code into the browser but later in this tutorial I will show you another way of doing this which can make it a bit easier.