topiniskala.com

PHP programming tutorial

Page index:

Introduction to PHP


Even with all of it's faults, PHP still might be my favourite programming language, at least when it come to web development. Unlike Java or .NET, PHP is very easy and effortless to deploy and you can get going with your project as soon as inspiration hits. This of course can be a double edged sword as the ease of coding makes it also easy to write bad code and ignore good practices. Having worked quite a bit with legacy PHP apps you can imagine the horrors I have witnessed...
But anyway, as PHP is my favourite language and I have been itching for some kind of easy and casual coding project outside of work, might as well go through a PHP tutorial book I found from flea market and write some kind of guide for the language based on it. Of course there are much better resources on PHP all over the internet, so if you stumble upon this and are interested in PHP, maybe explore the other ones first. This is just a casual hobby project, not a proper learning resource.

To get started with PHP, I recommend using Linux. I won't recommend any IDEs or editors as I personally enjoy programming most in a pure command line enviroment with Nano or Vi, but that might be too excentric for most. As for any specific flavour of Linux, Ubuntu (or more lightweight Xubuntu) is an easy recommendation as it is propably the most used and thus most documented, but personally I prefer CentOS for server use. On top of Linux you will propably need a server, a database system and of course the PHP engine to run your code. I will cover the basics of setting up a full LAMP stack (Linux, Apache, MySQL, PHP) at some point later and also cover some basic server hardening to take care of security, but for now i'll focus on programming.

PHP is a scripting language which means that instead of compiling your code to binary, you need a php run time enviroment to run your code, which is written as script files with .php extension. These files must start with <?php tag for the PHP engine to recognize them as proper scripts. You can test and run your scripts on the command line with the command php [SCRIPT NAME]. As PHP is a very web oriented language you almost never see any actual php programs that are run with the php command, but instead you place your PHP code into a web server and run it by accessing it on browser or programs like cURL.

In the following chapters I will go through the basics of programming in PHP before moving to the server and database stuff, but for now I end with two "Hello World" examples in PHP; the first to be run in command line and the next built into a website to be accessed by browser from server.

Command Line Hello World
<?php
echo "Hello World";
?>
Web page Hello World
<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <?php echo "Hello World!"; ?>
</body>
</html>

Variables and text


Strings

In the previous chapter we used the "echo" command to print text, so let's start this chapter with how to create text, either to command line or the web page. In programming a line of text is called a "string". A single character data type is called a 'char', so a line of text is therefore a 'string' of 'chars'. To print strings PHP has two main options, either the aforementioned "echo" or "print". These two have some differences between them, but for us these differences are not important for now, so i'm not going to go deeper into them, but for now we will focus on "print".

strings.php
<?php
print "This is a line.";
print "This is another line.";
?>

If you run the program above (with php strings.php on command line) you can propably see a problem with the code. Everything is printed into one row without any line changes. This is because print considers the text to be just a line of characters and does not assume anything about the text. Thus we need to add line changes in text form and this is done with "\n". Just add that to the end of each of the print lines to get line changes after each of the strings. But why the "\n" marker? The backlash ("\") character is used as an "escape marker". It basically means that the character coming after the escape marker is something special and should be treated differently. Thus when we type "\n" the letter n should not be treated as a character "n" but instead as a line change marker. This is also how we can add quotations to our text without them cutting off a string like this: print "Be mindful of using "quotations" in strings";. By adding escape markers before the two double quotes within the string makes them regular double quote characters. You can also use single quote strings and they behave differently to normal ones:

strings.php
<?php
print "\nThis is a line.\n";
print "This is another line.\n";
print 'This is not a new line\n, this is
a new line';
?>

As you can see, single quote strings treat the print statement as is and ignores things like escape markers. Also you can insert variables (we get to these soon) directly inside the string with double quotes, but not single quotes. We can also use "print" to print out a block of html for web pages. This can be done by using "Here Document" syntax like in the next example. You can use all of the same escape markers in "Here Documents" as with double quotes.

here_document.php
<?php
print <<<HTMLBLOCK
<html>
<head>
    <title>Example</title>
</head>
<body>
    This is a "Here document" example.
</body>
</html>
HTMLBLOCK;
?>

Final basic concept regarding string we explore is combining strings together. This is done with period, or "." key like this: print "This is a string" . " and this is another string.";. Again remember that print does not assume anything about the string and thus you have to place the whitespace on either side of the combination. Now that we have basics of strings under control, we can move on to validating and formatting them with built-in PHP functions.


String validation

In web services one of the most common string operations we must perform is input validation. Many web services require user input of some kind and often we have to check if the input is of the correct form. One of the basic string validations we can perform is to check the string length. To explore this, we need to use functions and conditional statements. Both of these will be explored in later chapters in length. This is done using the function strlen(), which takes a text input and returns the number of characters in it. You might also require the trim() function with strlen(), which removes all of the whitespace characters from the beginning and end of the string. You use these functions by adding the input string within the parenthesis as the function parameter. Here is and example:

string_length.php
<?php
if (strlen(trim(" String ")) == 6) {
    print "\nIt's working!\n\n";
} else {
    print "\nError!\n\n";
}
?>

In the script above we combined the two functions into a single line to make the code more compact and easy to read. Then we use two equals signs to compare the return value of the functions to a number (one equal declares, to equals compare). If the comparison is a TRUE statement, we print a message that everything is working correctly. After running that program and making sure it runs properly, try changing the comparison to a FALSE statement to get the error message. If you want to compare strings while ignoring the letter case you can use the function strcasecmp("StRiNg", "sTrInG");. This function returns TRUE if the strings (ignoring case) are the same and FLASE if not.


String formatting

Instead of the usual print we can use the function printf() to have more control over how we print a string. This function takes a format string and various items to format and print. There's quite a lot to unpack with printf so instead of spending a lot of time going through it, i'll show some common examples of how to use it.

Links: