Back to basics - Part 2
So we're back with the Back to basics series of posts that I had promised, this being part two of who knows how many. In this post I'm going to try and cover the very basics of programming in PHP. I'm going to try and keep the concepts pretty general though, so you can apply them to any structured programming language.
I'm going to be coming at this from a windows user point of view, most people that use linux have a better grasp on things and are either already programmers or do some sort of network admin.
If you've downloaded and installed WAMP server and have got it running, then just skip to the next paragraph. If you've downloaded it and installed it, but for somereason you can't access the web server on your machine by accessing http://localhost/, check if you're running skype. If you are, open the main interface, go to Tools and then Options. Once you have the options window open, go to the Advanced tab and then the Connections sub tag. In the main window, you will see a little tick box that says "Use port 80 and 443 as alternatives for incoming connections". Make sure that is unticked and then save the settings. Port 80 is the default web port and we need this port open for the web server to be able to start. Once you've done that, find the wamp icon on your system tray, left click on it and select "Restart all services". The little guage should go from red, to yellow to white. You can then browse http://localhost/ and you should see the default apache test page. Everything should be working now.
By default, wamp installs to C:\wamp, off this directory is another called 'www' (C:\wamp\www), this directory is the root web folder for your web server. We will be working in this directory.
Create a new file and call in helloWorld.php. In the file, type in the following code (Hint, actually type it in, try not to copy and past it if you can. I find it easier to learn something when you type it out, as you tend to take it in better, kinda like when you were at school (or still are) and to help yourself learn something, you would write it out.
<?php echo "Hello World!"; ?>
Now to test the file, simply open your browser and go to the URL: http://localhost/helloWorld.php. You should see the following:
Hello World!Easy hey! Lets go through the code line by line quickly:
<?phpThis is open tag for PHP. It indicates that after this tag, everything that follows is PHP code and should be interpreted by the web server before it is sent off to the web browser (we went through that process in part 1).
Moving onto the next line:
echo "Hello World!";
This line prints the words Hello World out. This is achieved by using the calling the function echo (Echo isn't really a function, it's a language construct, but for simplicity, we'll be calling it a function for now). Echo takes one or multiple strings and prints them out to the output, in our case the output is the browser. Strings are encompassed by the quotes (" "). After the string we have something that is very important. The instruction seperator is the semicolon at the end of the line (;). This indicates that this is the end of the command. Generally, you would only have one instruction seperator per line, but is is possible to have multiple ones on a line, but then your code becomes very untidy and hard to read.
On the next line, we simply end off by closing off the PHP tag:
?>As in the first line, this tells the web server that this is the end of the block of PHP code and it no longer needs to translate everything after the tag as PHP code. The following lines of code will all achieve the same result:
<?php echo "Hello World!"; ?> <?php echo ("Hello World!"); ?> <?php echo "Hello World!"; ?>
Lets move forward a little bit and include a variable to our code. Variables basically store information for us. They come in a number for different formats, but that will all be covered later, for now we'll just think of them as a container for data. As in real life, containers are used to store things in and in this case, we're going to use it to store our string, Hello World!. The code looks like this:
<?php $var = "Hello World!"; echo $var; ?>
We use the dollar ($) sign to declare a variable named 'var'.
$var = "Hello World!";
Variable names are case sensative,
$var and $Var are different. Once we have the variable, we assign it a value. Assignment is done via the equals sign (=). This tells the compiler tha the $var variable will contain whats behind the equals sign. In this case, it contains the string Hello World!. Remember, we know it's a string because it is encompassed by the quotes. Again we end off the line with the instruction terminator (;).
On the next line, we use echo to print out our variable that we have created. This time around, echo takes the variable as an argument, rather than the string we used last time. Since $var contains a string, it is considered to be a string too.
So as you can see, this achieves the same thing as before, the only difference is, we have a string variable that contains the string "HelloWorld!". This means we can use the variable again later on to display the string again if we so wish, without having to assign the string again. Think of it in real life as if you had caught a cool looking bug and put it in a can. You then take the can and show your one friend the bug. You can then show another friend the bug, without having to catch the bug again. This is, as you can imagine, very useful and we'll see how in a moment.
Lets move forward now and cover basic functions. Functions are very hand pieces of code and we generally use them for two simple reasons.
The first reason is so that we can reuse blocks of code, without having to rewrite the code out over and over again. Say for instance, you have a web site that has multiple pages, but all the pages have the same footer code (The code that closes off the web page). You could write a function to output that bit of HTML code. Then, instead of writing out the HTML code over and over again, you simply call the function, which then outputs (or generates) the HTML code.
The second reason is so that you can group code together and make your life a little easier in terms of making your code more readable. Lets say for instance, you need to write to a file. This can usually consist of a number of steps, such as opening the file, writing to the file, closing the file and then handeling any errors that might have occurred on any one of those steps. You can write a function so that the code is all grouped together, which makes it easier to find and identify. When you're writing web pages or programs that consist for thousands of lines of code, this is a extreamly important thing.
Lets take a look at a very basic function:
<?php function myFunction() { echo "Hello World!"; } myFunction(); ?>
We declare our function with the word function. This tells the compiler that what follows is the function declaration. Aftwards we name the function, in this case it is called myFunction. Inside the brackets, we would declare any variables that need to be passed into the function, we'll cover that in a bit. The we get to the curley braces. This indicates the start and end of the function scope ({ and }). The code betwen these braces is considered to belong to the function. Code outside of the function scope can not access the code inside the function scope, it is basically invisable to it. Then inside the function, we simply print out our Hello World! string again. We then close off the function with the curley brace (}).
Now, if we had stopped the code here and closed the PHP tag (?>) and then opened the page in the browser, it would have greeted us with a blank screen. In order for functions to be useful, we need to call them when we need them. To call the function, we simple use the following code:
myFunction();
When we call the function, it will then print out the string we want it to print out.
"This is seems like a rather long winded way of printing out the Hello World! string, I don't see the point".
Well in that case, creating a function to print out a string when it's hard coded is pretty pointless, but lets see a way a function can be usefull to us. Lets say we want to create a function that prints out an error message string. We want a string to always start with "ERROR: ". Manually typing this out every time can be rather painful, so instead, we create a function to do this for us:
<?php function printError($errorMsg) { echo "ERROR: ".$errorMsg; } $myError = "This is an error message"; printError($myError); ?>
Lets run through this quickly. First we define our function called printError(). In the definition, we are telling the compiler that we are expecting one variable to be passed into the function. In the function scope, we will reference this variable by using $errorMsg. What this means is that no matter what the variable was called outside of the function scope, it will always be referenced by the same name in the function scope. Then we print out the string "ERROR: " and concatenate our variable string on the end:
echo "ERROR: ".$errorMsg;
To concatenate strings together in a quick manner, we use the period (.) between the strings. This tells the compiler that we treat them as strings and we should push the strings together. Outside of the function scope, we assign our error message to a variable and then call the function and pass in our variable containing the error message string:
printError($myError);
This will output the following to the browser:
ERROR: This is an error messageLets have a look at multiple calls to the function:
<?php function printError($errorMsg) { echo "ERROR: ".$errorMsg; } $myError = "This is an error message"; printError($myError); printError("This is another error message"); printError($myError." - added more to the error here"); ?>
This will output the following to the browser:
ERROR: This is an error messageERROR: This is another error messageERROR: This is an error message - added more to the error here
Hrrrmm, thats not really what we wanted. Because we are outputting to the browser, we need to include some HTML code to tell the browser to make a new line. So we change the code to the following:
function printError($errorMsg) { echo "ERROR: ".$errorMsg."<br>"; } $myError = "This is an error message"; printError($myError); printError("This is another error message"); printError($myError." - added more to the error here");
As you can see, we've simple concatenated a <br> to the end of each error message. This will create the following HTML code:
ERROR: This is an error message<br>ERROR: This is another error message<br>ERROR: This is an error message - added more to the error here<br>
Which will then output the following to the browser:
ERROR: This is an error message ERROR: This is another error message ERROR: This is an error message - added more to the error here
And there you can see how useful functions can be. We could make this function even more useful, by making it log the error to a file, rather than the browser. In the function we could open the file, append the error message to the end of the file and then close the file again. As you go along, you'll see how usefull functions are and you'll begin to love them.
I'm going to end off there as we've covered a fair bit already. Try playing around with functions and variables and see what you can get going, I'm sure you'll be surprised.
Synack

Recent comments
42 weeks 3 days ago
42 weeks 3 days ago
42 weeks 3 days ago
42 weeks 3 days ago
42 weeks 3 days ago
42 weeks 3 days ago