Learn PHP: a PHP tutorial
PHP is a server-side interpreted open source script language that is most commonly used for the creation of dynamic web content. This acronym originally stood for ‘Personal Home Page Tools’, but today is commonly used as a shortened version of ‘PHP: Hypertext Preprocessor’.
While client-side languages like HTML, CSS, or JavaScript are only interpreted by the web browser during web page loading, a PHP code is already running on the web server. Here, the PHP generates HTML content that is passed onto the web browser. As a result, this content doesn’t contain a code (the PHP script), but instead just receives the results of the coding.
The central application area of PHP is in server-side programming. The main focus is the generation of dynamic web pages and apps. Other application uses include the writing of desktop applications as well as command-line programming. Despite its beginner-friendly syntax, PHP offers an impressive range of functions. The scripting language supports a wide variety of databases, can be used across multiple platforms, and is subject to a specific PHP license that allows open usage and editing of the source code. The combination of these three factors makes PHP an impressive tool.
Four of the most popular content management systems, namely WordPress, TYPO3, Joomla!, and Drupal, are based on PHP. And the combined reach of these top CMSs means that the PHP scripting language is used for an astounding 82.3% of all web pages on the World Wide Web, according to market analysis from W3Techs (Findings accurate as of: 18th November 2016). This makes PHP the most popular server-side programming language by some distance when it comes to web development. And this information alone is reason enough for anyone interested in web development or website management to become familiar with the options that PHP: Hypertext Preprocessor has to offer.
Our PHP tutorial will help take you through the initial steps, to give you an insight into server-side programming. However, some examples that we’ll be exploring will assume a fundamental knowledge of web development. And if HTML is new to you, it’s also a good ideal to get to know this language first, too.
The quickest way to learn PHP with this tutorial will be to follow the examples given here in real time on your own computer and tailor them to the needs of your web project. All that you need for server-side programming with PHP is a web server that includes a PHP interpreter, a text editor (e.g. Notepad++ or Vim) and a web browser. When it comes to choosing a server, we’d recommend the local test environment XAMPP for beginners. It can be downloaded free of charge from Apache Friends for the operating systems Windows, Linux, and macOS.
PHP Hosting from IONOS enables you to benefit from the best features of the latest PHP version. If you have any questions, your personal consultant is always on hand to help.
Installing PHP
Before you can start running PHP scripts, you’ll first need a web server that’s capable of interpreting the scripting language. This will also need to be equipped with what’s known as a PHP interpreter. An interpreter is a software component that’s able to identify the passages within a file that contains PHP code – in other words, it can understand the PHP language. Fortunately, PHP is typically supported by all modern web servers, and its corresponding interpreter is included in the PHP download package. The latest version of this PHP package is available from the project’s official website, php.net, and can be downloaded free of charge.
As a rule, your PHP interpreter will be integrated via a server module or as a FastCGI. The use of an interpreter as a CGI program isn’t recommended as it will affect performance. An industry-standard practice is to combine PHP with the Apache HTTP Server. If this connection is extended with one of the database systems MySQL or MariaDB, then, depending on the operating system used, they form what’s known as either a LAMP (Linux), WAMP (Windows), or MAMP. Web stacks like this are often offered as a pre-configured bundle package.
For this PHP tutorial, we recommend you use the complete package XAMPP. This includes a local installation on the Apache web server, including the database system MariaDB as well as the scripting languages Perl and PHP. To help with this, we’ve compiled an extensive installation guide as part of our XAMPP tutorial on the IONOS Digital Guide.
XAMPP is purely a test server. The software bundle offers web developers the opportunity to create a complete testing environment for scripts, HTML pages, and style sheets in as short a time as possible. There is no guarantee that it will function securely as a web server online. For this reason, XAMPP should only be used locally. This means that you should ensure there’s no online access to your XAMPP services.
PHP basics: the syntax of the scripting language
Once you’ve set up your local web server (i.e. with the help of XAMPP), you should check to make sure that PHP was correctly installed and is ready to create scripts.
a script is usually a small computer program that isn’t constructed in advance using binary code. Scripts are written in one of several programming languages like PHP, Perl, or JavaScript, and are read by an interpreter on the web server (server side) or an engine in the web browser (client side).
Open your text editor of choice and enter the following PHP script:
<?php
phpinfo();
?>
PHP scripts are always built in the same way. The opening PHP tag <?php signals that a script environment is being started. This is then followed by the actual PHP code in the form of an instruction. So in our example above, this was a command to start the function phpinfo(). Most functions require one or more parameters that are included within the brackets; with phpinfo(), this is actually optional: phpinfo( INFO_ALL ). Every command ends with a semicolon (;). When you want to close a script environment, you’ll need to include the PHP closing tag, ?>.
Functions are subprograms that enable you to outsource parts of the program code. To avoid redundancy, tasks that recur often can be defined once as a function and then called into command with use of the function name. Web developers also make use of pre-defined PHP functions or create their own subprograms.
The example file can now be loaded in your web browser via the following URL: http:// localhost/ test.php. If you’re using a different web server or an individual configuration of the XAMPP software, you can find your URL by following the respective file path.
http://localhost/test.php
Verwenden Sie einen anderen Webserver oder eine individuelle Konfiguration der XAMPP-Software, wählen Sie die URL dem jeweiligen Dateipfad entsprechend.
While internet addresses use a forward slash (/) as a separator for levels, the Windows Explorer uses a backward slash (\). Modern web browsers usually convert backward slashes to forward slashes automatically, too.
By entering the URL http:// localhost/ test.php, you’ll be commanding your web browser to request the file test.php from the web server. The Apache HTTP server (or the web server software you’ve chosen) will retrieve the file from the appropriate folder.
The ending .php confirms that the file contains a PHP code. This alerts the web server’s integrated PHP interpreter. The interpreter parses the document and reads the opening PHP tag <?php, which informs it of the start point for the PHP coding. The interpreter then works its way through the PHP code and presents the results in HTML format, which is subsequently delivered from the web server to the web browser.
If the PHP has been correctly installed, then you should now be able to see your script execution in the form of a web page like below:
The function phpinfo() is a shortened version of the standard command phpinfo( INFO_ALL ). This command gives detailed information about the PHP configuration of your web server. If no PHP version can be located, then your web browser will display an error message or simply deliver the PHP code to the browser without interpreting it.
‘Hello World!’ – How to add text using the echo command
If PHP has successfully installed without errors, then it’s time to write your first script. To do so, you’ll need to use the echo command. Unlike phpinfo(), echo isn’t a function command. Instead, it should be thought of as a language construct enabling the string of information to be displayed in text format.
Language constructs are commands that are used in PHP to control the programming sequence. There are several forms of language construct, including echo, if, for, do, include, return, exit, and die. Unlike functions, these commands don’t require brackets.
Have a go at creating your first script as a PHP file by using the following:
<?php
echo 'Hello World!';
?>
The opening tag <?php will start the scripting environment. The language construct echo then follows, with the actual text string Hello World! enclosed in quotation marks. The tag ?> then closes the script. Don’t forget about the semi colon in the command. You can follow our example or customize it with a different expression than Hello World!.
The term ‘string’ is used in IT to describe a collection of characters of variable length – usually in the form of a chain of letters, numbers, and special characters. In programming, strings are regarded as a standalone data type and are differentiated from other types of data like integrators or floats.
Save your script in the htdocs folder of your web server under the title hello.php and open the file in your web browser via the URL http:// localhost/ hello.php. If you created the code correctly, then your browser window should now display the following page:
Every text that you create with echo can be extended with HTML tags. These will be interpreted by your web browser based on the HTML specification included. Try it yourself by running the following script:
<?php
echo '<h1>Hello World!</h1>
<p>This is my first PHP page.</p>';
?>
The <h1> tag for the string Hello World! will automatically be interpreted by your browser as a top heading. This is then followed by an automatic line break and the indicator for a text paragraph <p>.
The echo command can be used with a simple single quotation mark (‘) as well as with the double quotation marks (“). If you’re just planning to add straightforward text then it won’t make a huge difference which of these quotation marks you choose to use. Things only change here when variables come into play.
Variables
The language construct echo has more functions to offer than just the replication of text. This can also be implemented to great effect without PHP, using HTML as a basis. But the true added value of echo is in the dynamic generation of texts using particular variables in combination with the function.
PHP users might come across variables in the following form:
$example
Every variable consists of a dollar sign ($) followed by the name of the variable. Variables are used in PHP scripts to integrate external data into web pages. These variables can cover many different types of values – from simple numbers and character strings, to entire texts or HTML document structures.
PHP has 7 different forms of variable:
Variable Types | Description |
---|---|
String | A string is a collection of characters. It can be presented in the form of a word, a sentence, a text, or even the HTML coding for an entire web page. |
Integer | An integer is a whole number without decimal places. This can be positive or negative. |
Float | A float is a numerical value with decimal places included. The decimal point is displayed just as a normal decimal would be (e.g. 12.914). PHP can support up to 14 decimal places. |
Boolean | Boolean variables are the result of a logical operation and can only have two values: TRUE and FALSE. This type of variable is used when you’re working with conditions. |
Array | An array is a variable that can contain multiple elements. Simply put, it’s a grouping of several similarly structured data files that have been combined to form one entry. |
Object | The object variable type enables programmers to define their own types of data. This is typically used for object-oriented programming. In this PHP tutorial for beginners, we’ll be disregarding object variables as they’re a more advanced technique. |
NULL | The NULL value represents variables that have no value. For NULL variables, this is the only possible value. |
The central management of content is usually controlled by the database system, but values for variables can also be defined directly in the script. This type of command is carried out like this:
$example = "value";
The dollar sign indicates a variable, and is then followed by the type of variable (in this case example). The equals sign (=) then indicates the value of the variable.
Values for variables in the form integer and float forms are written without quotations marks (e.g. $example = 24; or $example = 2.7;)
PHP gives you the freedom to name variables at your own discretion. There are just a few restrictions that apply:
- Every variable must begin with a dollar sign
- All variable names must be made up of any combination of letters, numbers, and underscores (e.g. $example_1)
- A valid variable name must always begin with a letter or an underscore (VALID: $example1 or $_example), but never with a number (INVALID: $1example)
- PHP is case-sensitive. The scripting language differentiates between lower case and upper case characters ($example ≠ $Example)
- The variable name may not include any spaces or line breaks (INVALID: $example 1)
- Titles that are reserved for other purposes within PHP can’t be used as user-defined variables (e.g. $this)
Let’s look at an example:
<?php
$author = "John Doe";
echo "<h1>Hello World!</h1>
<p>This dynamic web page was created by $author.</p>";
?>
After the open PHP tag, we’ve defined our variable: Whenever $author is used, it should be understood as the value John Doe. Then, when we come to write our script, the variable $author will be replaced by the value John Doe for every single use throughout the script itself. The following graphic demonstrates how this will look when displayed in the web browser.
If a mistake has been made, and it turns out that our web page wasn’t created by John Doe at all, but instead by his German colleague Max Mustermann, then all we need to do is redefine the value for the variable $author to correct the error.
The benefit and efficiency of this becomes increasingly evident the more often a variable appears in a script. If, for example, the author’s name appeared 20 times throughout our whole script, then using $author would mean that we’d only need to change the value of this variable once to change the name of the author for all 20 instances in the script, making alterations much easier and quicker to manage.
This is the biggest strength of PHP: Content can be included in the form of variables. This feature is the foundation of dynamic web development. Unlike static web pages, which are already available as pre-prepared HTML pages, dynamic web pages are instead generated as a page is in the process of being called. This means the PHP interpreter loads individual elements of the whole web page using variables from different databases and compiles them into a customized HTML page.
The advantage of this design concept is obvious: If certain elements of a website (e.g. the website footer) need to be changed, then this adjustment doesn’t need to happen for every single web page within the website project. Instead, you can just update the corresponding entry in your database. Once this is done, the new variable value for your website footer will be instantly visible across all pages of your website.
If a variable is defined multiple times within a script, then the latest definition is taken for all information moving forward.
<?php
$author = "John Doe";
echo "<h1>Hello World!</h1>
<p>This dynamic web page was created by $author.</p>";
$author = "Max Mustermann";
echo " <p>Supported by $author.</p>";
?>
In the coding example, the variable $author is initially attributed to the value John Doe and then subsequently altered to stand for the new value Max Mustermann.
Now let’s explore quotation marks further. Unlike with strings, individual variables don’t need to be enclosed in quotation marks themselves:
<?php
$author = "John Doe";
echo $author;
?>
So, what happens if your variable is meant to appear within a string? In this case, you can work with double quotation marks (“). This signals to the PHP interpreter that it should first search the string for variables, as these may have to be replaced by other, previously defined values. Strings enclosed in single quotation marks (‘) are interpreted and rendered as pure text information, even if they contain variables. You can try this yourself:
<?php
$author = "John Doe";
echo '<h1>Hello World!</h1>
<p>This dynamic web page was created by $author.</p>';
?>
You might be wondering what happens if you omit the quotation marks altogether. In these cases, PHP simply produces a syntactic error message.
Error messages and masking
When it comes to syntactic errors, there’s no valid PHP code and the PHP interpreter will simply produce an error message. If, for example, we were to code an echo statement but omitted the quotation marks around the string, as below, then we’d expect to receive an error message.
<?php
echo Hello World!;
?>
In the above example, the program has detected an error in line 2 of our program code – which is exactly where we left out the quotation marks to demonstrate.
Syntactic errors also occur when you want to create text using certain character combinations that are associated with a specific task in PHP. One example of this would be if you wanted to display single quotation marks (‘) in your actual text output. The quotation marks within this string will only be interpreted as quotation marks in the displayed text if you make it clear to the interpreter that the characters have been relieved of their defined task. When you’re using single quotation marks, there are two ways to deal with this: You can either enclose a string that features single quotation marks with another set of double quotation marks, or you can mask the single quotation marks with a pre-defined backward slash (\):
<?php
echo '\'Hello World!\' ';
?>
As mentioned above, the combination of single and double quotation marks also works:
<?php
echo " 'Hello World!' ";
?>
But not two sets of single quotation marks:
<?php
echo ' 'Hello World!' ';
?>
In the above examples, the spaces between the quotation marks have been inserted for readability.
String Operators
If you want to use several variables within a PHP script at the same time, you can do so fairly easily, as we’ve already seen:
<?php
$author1 = "John Doe";
$author2 = "Max Mustermann";
echo "<h1>Hello World!</h1>
<p>This dynamic web page was created by $author1 and $author2.</p>";
?>
Simple write both variables, together with the rest of the text, inside a string encased by double quotation marks. PHP automatically recognizes the use of variables thanks to the dollar sign ($) and replaces the values accordingly.
However, as far as programming is concerned, this is considered to be quite messy work. In fact, it’s considered dogma that variables should never be part of strings. One reason for this is that many programming languages demand a separation between the two. But even more important is the fact that PHP requires separation of string and variables when it comes to function calls or more complex variables. It’s recommended to implement this separation consistently from the beginning, even in cases of pure text output, because this will help discipline your approaches for more complicated coding in the future.
When working with variables, we’re always having to deal with several separate elements that require linking together for output. In PHP, this means making use of a string operator.
If we were programming the same example above but in a ‘clean’ way, it would need to look as follows:
<?php
$author1 = "John Doe";
$author2 = "Max Mustermann";
echo '<h1>Hello World!</h1>
<p>This dynamic web page was created by ' . $author1 . ' and ' . $author2 . '.</p>';
?>
In this instance, we’ve combined three strings and two variables, concentrated together into a single command.
String1 | Variable1 | String2 | Variable2 | String3 | ||||
---|---|---|---|---|---|---|---|---|
'<h1>Hello World!</h1> | . | $author1 | . | ' and ' | . | $author2 | . | '.</p>' |
<p>This dynamic web page was created by ' |
The link between the separate strings and variables is the string operator, the dot. It should be noted that string operators connect strings and/or variables without spaces. To include a spare, you’ll need to do so within the quotation marks, as in our example above.
Programmers don’t just use string operators to link strings and variables for text output – they’re also used to extend variables themselves. The following example demonstrates how this is possible:
<?php
$beispiel = 'Hallo ';
$beispiel .= 'Welt';
echo $beispiel;
?>
To extend the value of a variable, we can first define this, before then redefining it with the string ‘dot’ operator (.) before the equals sign. This enables the new variable to account for both the previous definitions together: $example = $example . 'World'.
PHP responds by adding the new value to the previously defined value. If you want to add a space between the two values, include this at the end of the first string, as in the example code.
Embed PHP into HTML
The PHP interpreter is only interested in code that comes between an opening and closing PHP tag:
<?php [Dieser Bereich wird vom PHP-Interpreter geparst] ?>
All other parts of the document will be ignored by the interpreter and handed over to the web server exactly as they are. This means that PHP code can be integrated into HTML documents – to create a template for a content management system, for example. It’s important to make sure that HTML documents containing PHP code are stored as PHP files – otherwise the document won’t be processed by the PHP interpreter, and will instead be delivered directly to the web browser – meaning that the programming code is displayed on the website as a coding text.
To help you remember this, think of the PHP interpreter as your web server’s lazy colleague, who will only work when explicitly told to do so – in the form of a file saved in PHP format, which includes an opening and closing PHP tag.
If you want to combine HTML and PHP, you should write your HTML page as usual according to the classic document structure and save it as a .php file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first PHP page</title>
</head>
<body>
<h1>Hello World</h1>
<p>What is the current time and date?</p>
</body>
</html>
Now, you can expand your HTML document with a PHP script. Make sure that you include the PHP opening and closing tags around the PHP program code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first PHP page</title>
</head>
<body>
<h1>Hello World</h1>
<p>What is the current time and date?</p>
<p>Your current time and date is:
<?php
echo date("d.m.Y H:i:s");
?>.</p>
</body>
</html>
In the above example, we’ve used the language construct echo in combination with the function date(), in order to display the current date and time in text format on the server side. The parameter of the function offers the desired format in the form of a string:
d.m.Y H:i:s = Day.Month.Year Hours:Minutes:Seconds
When the web browser requests this file, the PHP interpreter will first process the script and write the current date and time into the HTML document in text format. This is then delivered from the web server and displayed in the form of a web page in the browser.
The PHP comment function
Just as in HTML code, PHP allows you to include comments. Comments in the source code will be ignored by the PHP interpreter, as long as they have been marked according to the syntax. PHP gives you three different ways to do this.
If you want to mark an entire line as a comment and stop it from being interpreted, you can use the hashtag (#) or two consecutive forward slashes (//). The following coding example features both methods:
<?php
#This is a single-line comment!
echo '<h1>Hello World!</h1>
<p>This is my first PHP page.</p>';
//This is also a single-line comment!
?>
The text editor Notepad++ highlights comments in green. The sections marked as comments in the text coding do not appear in the web browser – unlike HTML comments – as they’ve already been ignored by the PHP interpreter during the script execution.
The above example is of single-line comments, but you also have the option of adding comments that stretch across multiple lines. To do this, simply mark the start of the comment section with a forward slash, followed by an asterisk (/*), and the end with the reversed order of an asterisk followed by a forward slash (*/).
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
echo '<h1>Hello World!</h1>
<p>This is my first PHP page.</p>';
?>
Programmers use comments to structure the source code of their scripts, to leave notes for later editing, or to create internal information, such as the author of particular sections, or the date that certain sections were finished.
Comments are optional and should be used sparingly to ensure your source code remains legible.
Making calculations with variables
By now, you should be fairly familiar with how to input variables. So far, we’ve only looked at variables that are assignd to string values. We’re now going to turn our attention to variables that represent integers or floats.
If variables store numeric values, then PHP offers you the ability to perform calculations with these variables. We’ll start by looking at a simple addition of two integer variables:
<?php
$number1 = 237;
$number2 = 148;
$result = $number1 + $number2;
echo "result: " . $result;
?>
We start by defining the variables $number1 and $number2 as the respective integers 237 and 148. Then we define the addition of these two variables to be the value for the variable $result, using our arithmetic operator for addition, the plus symbol (+). This means that $result will always display the result of $number1 and $number2, even if we change the value of these two numbers. Then, we can use the language construct echo to explain this result in text format. Note that we don’t need quotation marks when assigning numeric values to variables.
The following code example shows a selection of mathematical calculations that can be performed using PHP on the server side. The operations largely correspond to the standardized symbols for mathematics.
Arithemtic Operator | Operation | Result |
---|---|---|
$number1 + $number2 | Addition | Sum of $number1 and $number2 |
$number1 - $number2 | Subtraction | Difference between $number1 and $number2 |
$number1 * $number2 | Multiplication | Product of $number1 and $number2 |
$number1 / $number2 | Division | Division of $number1 by $number2 |
$number1 ** $number2 | Exponentiation | $number1 to the power of $number2 |
<?php
$numbe1 = 10;
$number2 = 5;
$addition = $number1 + $number2; //Addition
$subtraction = $number1 - $number2; //Subtraction
$multiplication = $number1 * $number2; //Multiplication
$division = $number1 / $number2; //Division
$exponentiation = $number1 ** $number2; //Exponentiation
?>
<?php
echo "Result addition: " . $addition ."<br />";
echo " Result subtraction: " . $subtraction . "<br />";
echo "Result multiplication: " . $multiplication . "<br />";
echo "Result division: " . $division . "<br />";
echo "10 to the 5th power (10^5): " . $exponentiation . "<br />";
echo "Square root of 81: " . sqrt(81) . "<br />";
?>
For more complex calculations, we’ll need to combine different arithmetic operators in one script:
<?php
$number1 = 10;
$number2 = 5;
$result = 2 * $number1 + 5 * $number2 - 3 * sqrt(81);
echo "Result: " . $result;
?>
The PHP interpreter will read the variables in the coding above and calculate the following equation:
2 * 10 + 5 * 5 - 3 * √81 = 20 + 25 – 27 = 18
The function sqrt() calculates the square root of the number contained within the brackets. PHP follows the classic mathematical rules of BODMAS when calculating equations. Once again, we’ve used the echo statement to display the result as a string for the web browser.
Bracketed terms are naturally also prioritized in PHP. Here’s an example of this, on this occasion using decimals for a more complex result:
<?php
$number1 = 2.5;
$number2 = 3.7;
$result = 2 * ($number1 + 5) * ($number2 - 3) * sqrt(81);
echo "Result: " . $result;
?>
Like all modern programming languages, PHP also offers operators that can increase or decrease values by 1. The different options here are pre-increment operator, the pre-decrement operator, the post-increment operator, and the post-decrement operator.
Operation | Operator | Result |
---|---|---|
Pre-increment | ++$number | The operator ++ increases the value of the variable $number. This will increase its value by 1. The result will be presented as a new value for $number. |
Pre-decrement | --$number | The operator -- decreases the value of the variable $number. This will decrease its value by 1. The result will be presented as a new value for $number. |
Post-increment | $number++ | The current value for $number is first restored and then increased by 1. |
Post-decrement | $number-- | The current value for $number is first restored and then decreased by 1. |
Next we will look at how these calculations with increment and decrement operators in an example. The following script will increase the value of the variable $number by 1, store the new value as the variable $result, and lastly present the value as a string:
<?php
$number = 0;
$result = ++$number;
echo "Result: " . $result;
?>
To calculate the pre-decrement of the variable $number, we can use basically the same script, simply substituting the pre-increment operator (++) for the pre-decrement operator (--):
<?php
$number = 0;
$result = --$number;
echo "Result: " . $result;
?>
An increase before and after output (pre- and post-increment) of a value can be explained in the following script:
<?php
$x = 0;
echo '<p>Result: ' . ++$x;
echo '<br>x has the value ' . $x;
echo '<p>Result: ' . $x++;
echo '<br>x has the value ' . $x, '</p>';
?>
The superglobals $_GET and $_POST
At this stage, we’ve talked about the basics of PHP, discussed how to implement variables, link them in strings, and calculate equations. Next, we’ll show you why variables are such a central concept in the programming of scripts.
An important function in scripting languages is the option to evaluate user input and transfer these values into another script. When it comes to this data transfer, PHP relies on the superglobals $_GET and $_POST – predefined system variables that are available in all scopes of application. $_GET and $_POST store a set of variables in the form of strings in a variable, known as associative arrays.
You should think of these arrays like a wardrobe with several drawers. Each drawer gives you the opportunity to store data. To make sure you know what’s being stored in each drawer, you can label these with a variable name. Depending on the type of array, this can either be an index or a key. While indexed arrays require an index in the form of a number for each drawer, the drawers of associative arrays are labelled with a key in the form of a string.
The superglobals $_GET and $_POST contain a range of variables in the form of keys that enable you to utilize the values associated with these keys. We’ll explain this in further detail as we take a closer look at the different superglobals $_GET and $_POST individually.
Data transfer via $_GET
The superglobal $_GET depicts an array of variables that are given to a PHP script with the help of a URL. If you regularly visit blogs, online shops, or internet forums, you might have noticed the strange URLs you encounter on these types of site. Usually, the structure of the URL follows the pattern below:
http://hostname/folder/filename.php?variablenname=variablevalue
Transferring this to a blog will usually result in an appearance like this:
http://www.example-blog.com/index.php?id=1
A URL like this can be broken down very easily: On the web server with the domain example-blog.com, there’s a file by the name of index.php that is used to create a dynamic web page. This would typically contain HTML and PHP code as well as references to outsourced template files and external style sheets – in short, everything that you need for a fully operational web page to display. It’s probably a dynamic web page in this instance, because of the additional (?): id=1. This is known as an HTTP query string and contains a variable (id) and a value (1), connected by an equals sign (=). URL parameters like this are used, for example, to generate a dynamic web page, load content from a database, or call up a suitable template.
Dynamic web pages enable you to separate content and presentation. So, while the index.php contains all the necessary information about the structure of a website, it needs to be filled with content as well. This content is usually found in a database and can be called up using the parameters in the HTTP query string. In our example, the URL gives the index.php the parameter id=1. This determines which content is to be read from the database and loaded in the index.php. As far as weblogs are concerned, this usually means the ID for a particular article. In forums, this will usually be a particular entry, and with online shops it will generally represent a particular product.
If a URL contains more than one parameter, this will usually be connected using the ampersand symbol (&).
www.example-blog.com/index.php?page=article&id=1
To illustrate the use of $_GET in a coding example, we’ve simplified things to demonstrate it without a database. In the following script, we’ve used the superglobal $_GET to read the variables forename and surname from an HTTP query string and to write them into the PHP variables $variable1 and $variable2:
<?php
$variable1 = $_GET['forename'];
$variable2 = $_GET['surname'];
echo "Hello " . $variable1 . " " . $variable2 . "!";
?>
Calling up this script is done using the following URL:
localhost/hello.php?forename=John&surname=Doe
By doing this, we’ve assigned the parameters forename=John and surname=Doe. Once again, the language construct echo is used to produce the values in text format for display.
A data transfer with $_GET inevitably leads to the transferred data being visible in the address bar. This means it’s always possible to understand and register the parameters that are being transferred. This has the advantage that variables can be stored in the form of hyperlinks. Internet users also have the option of bookmarking certain URLs with their HTTP query string in their browser.
The downside to using the GET parameter in clear sight as displayed in the URL is obvious: it’s not a method that can be used for transferring sensitive data, such as the results of online forms. Additionally, the amount of data that the $_GET method can transfer is limited by the maximum length of URLs.
These limitations can be avoided by using the HTTP method POST. The data that’s transferred using this method can be found in the superglobal $_POST.
Data transfer via $_POST
While data transfers are made via URL parameters with the GET method, information is transmitted in the body of an HTTP request with $_POST. This enables developers to transmit very large amounts of data from one script to another without difficulty.
A central application field for the HTTP POST method is the transfer of HTML form data. We’ll demonstrate this by showing you how to construct your own newsletter sign-up form.
Create a new PHP file with the name page1.php and write out the following code block inside it:
<form method="post" action="page2.php" >
Please send the newsletter to: <br />
Forename: <input type="text" name="forename" /><br />
Surname: <input type="text" name="surname" /><br />
Email address: <input type="text" name="email" /><br />
<input type="submit" value="Submit form" />
</form>
When creating a form like above, you’ll need to use the HTML element <form>. This contains two primary attributes: method and action. The method attribute defines the transmission method, so in this case, HTTP POST. The action attribute stores the URL of the script that receives all the data collected by the input fields listed. The example shows an HTML form with three input elements (input type="text") and a send button (input type="submit"). The file page2.php is defined as the recipient of the data.
To illustrate the data transfer using $_POST, we’ve used a simple script to evaluate the form data, one that stores the transmitted values as PHP variables and outputs them in text form. To do this, create a file called page2.php and copy out the following program code:
<?php
$forename = $_POST["forename"];
$surname = $_POST["surname"];
$email = $_POST["email"];
echo "Hello " . $forename . " " . $surname . ", <br />
You are registered with the following email address: " . $email . ".";
?>
Store both your PHP files in the htdocs folder of your test server and call up the page1.php via the following URL in the web browser: http://localhost/page1.php. Your browser should now show you the interactive web interface for your HTML form.
Enter any registration data you like and click on the submit button to send variables from one script to the other. As soon as you’ve confirmed submission of data on page1.php, you’ll be automatically forwarded to page2.php. The browser window shows the results of the script execution based on the data that’s been transferred.
User entries that are collected via the input field on page1.php will be called up by page2.php using the following formula:
$_POST["Name of the input field"]
For example, the entry $forename = $_POST["forename"] will retrieve the input for the input field forename and store this as the variable $forename. The variable $forename can then be outputted in text format using the language construct echo.
The if construct and the PHP comparison editors
So far, we’ve defined what variables are, looked at how to transfer them from one script to another, and demonstrated how to present them as string. In this next section, we’ll show you how to execute certain fragments of code depending on certain conditions.
The language construct if gives you the option to write scripts with commands that only come into place after a certain pre-defined condition is fulfilled – such as a correct password entry, for example.
Conditions can be defined in PHP using the following basic framework:
<?php
if(expression)
{
statement;
}
?>
This comes with the following consequence: the statement will only be executed once the condition in the expression has been fulfilled. A condition is only considered to be fulfilled once the if construct has produced the result TRUE. Any other result will be listed as FALSE. In these cases, the command will simply be ignored.
Generally speaking, the if construct checks whether or not the value of a variable corresponds to the value defined in the condition. This control structure is normally carried out using comparison operators.
Comparison operators
Comparison operators are used to formulate conditions. They assess two arguments in a logical relationship that can be evaluated as TRUE or FALSE. If comparison operators are used in a PHP control structure, they’re applied to two variables in the expression of an if construct:
if ($a == $b)
{
statement;
}
To put this into words, the control structure is basically saying: If variable $a is the same as variable $b, then the command defined by statement will be executed.
The PHP comparison operators are based on the programming language C and often make use of some of the classic mathematical symbols. Here’s an overview of the most common ones in the table below.
Comparison Operator | Description | Function |
---|---|---|
== | Is the same as | The condition is fulfilled when $a and $b have the same value. |
=== | is identical to | The condition is fulfilled when $a and $b have the same value and belong to the same type of data. This is best explained with an example. Here, we’ll compare the integer (1) with a string (“1”): 1 == "1" //TRUE and 1 === "1" //FALSE. For conditions that require two variables to be completely identical, always make sure you use the comparison operator === (is identical to). |
!= | is not the same | The condition is fulfilled if $a and $b have unequal values. |
!== | not identical | The condition is fulfilled if $a and $b have unequal values or are different types of data. |
< | Is smaller than | The condition is fulfilled if the value of $a is smaller than the value of $b. |
> | Is bigger than | The condition is fulfilled if the value of $a is bigger than the value of $b. |
<= | Is smaller or the same as | The condition is fulfilled if the value of $a is smaller than the value of $b or if the two variables have the same value. |
>= | Is bigger or the same as | The condition is fulfilled if the value of $a is bigger than the value of $b or if the two variables have the same value. |
The following script should help to explain these control structures. To do so, we’ll be comparing two integers. As our comparison operator, we’ve chosen to go for < (is smaller):
<?php
$number1 = 10;
$number2 = 20;
if($number1 < $number2) {
echo "The condition is fulfilled";
}
We’ve defined the variables $number1 and $number2 using the values 10 and 20 respectively. In the next line, we’ve stipulated our condition: If $number1 is smaller than $number2, then the echo command should display the string value ‘The condition is fulfilled’.
The result of the script execution contains an answer: 10 is smaller than 20. This means that the if construct will give the result TRUE. The condition is fulfilled.
If you want to define commands that should only be executed provided that a condition is not fulfilled. you can extend the if control structure with the language construct else according to the following formula:
<?php
if(Condition a)
{
Command b;
}
else
{
Command c
}
?>
This script will also check whether the condition a has a TRUE or FALSE result. If condition a is fulfilled (TRUE), then command b will be carried out.
But if condition a isn’t fulfilled (FALSE), then command b will be skipped and command c executed instead.
Let’s extend our script with the else construct and switch our comparison operator from < (is smaller) to == (is the same):
<?php
$number1 = 10;
$number2 = 20;
if($number1 == $number2)
{
echo "The condition is fulfilled";
}
else
{
echo "The condition is not fulfilled";
}
?>
This time, the if construct has returned a FALSE result. The value of the variable $number1 isn’t equal to the value of the variable $number2. The condition isn’t fulfilled. As a result, the first if command will be overridden and the else command executed instead.
If the execution of a code fragment relies upon the equality of two values, then you need to ensure you use the double equals sign in PHP (==). The single equals sign (=) can only be used when assigning values to variables.
You can make a condition negative by using an exclamation mark (!) within the expression.
<?php
$zahl1 = 10;
$zahl2 = 20;
if ($zahl1 == $zahl2)
{
echo "Die Zahlen sind gleich.";
}
if (!($zahl1 == $zahl2))
{
echo "Die Zahlen sind nicht gleich.";
}
?>
This example uses the condition $number1 == $number2 and the negation of this. !($number1 == $number2) corresponds to ($number1 != $number2).
A practical application of if and else could be in the use of password queries based on an HTML form. We’ll simulate this now with the help of our PHP files page1.php and page2.php.
Open page1.php and enter the following formula code:
<form action="page2.php" method="post">
Please enter your password: <input type="password" name="password" />
<input type="submit" value="Submit" />
</form>
The structure of this is similar to the form we’ve created before. But this time, we’re adding an input field: the password query. Just like before, user input is passed to the page2.php script. Now we can include the following code to ensure that the password entered by the user is matched with a stored password:
<?php
$password = $_POST["password"];
if($password=="qwertz123")
{
echo "The password was correct";
}
else
{
echo "The password was incorrect";
}
?>
The code reads as follows: First, we’ve assigned the variable $password in line 2 to a value that we’ve called up via the HTTP POST method. Next, we’ve defined the following control structure: The if construct in line 3 is designed to check whether the value of the variable $password agrees with the string qwertz123. If this is the case, then the string The password was correct will be displayed. But if the if result comes back as FALSE, then the else condition in line 7 comes into action, and so the string The password was incorrect is presented.
So let’s call up the script page1.php via our URL http://localhost/page1.php and see our password query in action!
The web browser will automatically load page2.php. Behind the scenes, the if control structure has reviewed the password we entered and reached the conclusion that ‘qwertz123 == qwertz123 is TRUE’, meaning the string The password was correct has been produced and displayed in the browser.
To prove this works, check your password submission coding by entering an incorrect password into the input field and seeing what happens when you press submit.
Logical operators
Conditions that are defined through the expression of an if construct with the help of comparison operators can be linked to other conditions within the same expression if required. PHP supports this with the logical operators AND and OR.
Higher precedence | Lower precedence | Description |
---|---|---|
&& | AND | Both conditions that are connected by the logical operator have to be TRUE. |
// | OR | Only one of the two conditions connected by the operator has to be TRUE. |
To link conditions, PHP provides logical operators with both higher and lower precedence. On the whole, if you use just one of either the higher or the lower precedence logic operator for your chosen form, you won’t notice a difference. But if you combine both ways of writing the logical operator, you’ll find that OR and // have higher precedence than AND and OR. While AND and && have a higher precedency than OR and //. This is comparable to the operator rank order of BODMAS that exists in mathematics.
We can return to the password query again for a practical example of how this works. In general, login data doesn’t just feature a secret password; this usually has to be paired with a username as well. It’s only when both entries are deemed to match the data stored within the system that a login is successful.
We’ll open our formula for password requests in page1.php again and extend it with an input field for a username:
<form action="page2.php" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
</form>
Now, we need to change the next few steps to make sure that the control structure for our if construct meets our new requirements. Let’s use the logical operator AND link the condition for the password query to the condition for username query.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
if($username=="John Doe" AND $password=="qwertz123")
{
echo "Welcome to the internal area " . $username . "!";
}
else
{
echo "Access denied";
}
?>
Our script page2.php now receives the values for username and password, and stores these as the variables $username and $password. The expression of the if construct contains two conditions that are connected with the logical operator AND. It’s only when both conditions are fulfilled (username=="John Doe" and $password=="qwertz123") that the if construct will return a TRUE result.
Since we want to enter a username in the input field username, we can use it directly for the text output via echo: Welcome to the internal area is followed directly by the variable $username. If either of the conditions goes unfulfilled, the text output will simply read: Access denied.
Logical operators can be combined as desired. This is when important precedence rules come into play: AND has a higher operator rank position than OR. If you want to change this, you can use brackets in PHP just the same way as you can in mathematical equations to influence the ranking of precedence.
Loops (while, for)
Sometimes it’s necessary for a script to run a particular section of code several times before the rest of the programming code is executed. In programming-speak, this is known as a loop. There are three different types of loop:
- while loops
- do-while loops
- for loops
while loops
A while loop is the simplest type of loop that exists in PHP. Its basic syntax is as follows:
while (expression)
{
Loop step and other instructions
}
The while loop instructs PHP to execute other, subordinate instructions for as long as the while condition is fulfilled. To do this, the PHP interpreter checks the condition at the beginning of each loop run. The execution of the subordinate code will only stop once the while expression is no longer fulfilled.
This principle can be showcased easily with the use of a straightforward number counting script:
<?php
$number = 1;
while ($number <= 10) {
echo $number++ . "<br />";
}
?>
To do this, we’ve returned to the principle of incrementing values that we previously introduced during the section ‘calculating with variables’. Building on this tool, we’re using a post increment operator to increase the value of the integer variable $number by 1 in the text output echo after each loop pass. The condition for the while loop is defined: $number must remain the same as or smaller than 10. The echo command will continue to repeat its task until the $number variable reaches a value higher than 10.
The result of the script execution is a string that produces the value of the variable $number at the completion of every loop before it’s incremented. Because of our condition, the script counts from 1 to 10 and then ends the coding sequence because the while expression is no longer fulfilled.
do-while loops
The structure of the do-while loops is very similar to that of the while loop. The only difference is that the condition isn’t checked at the beginning of each loop cycle; it’s simply checked at the end. The basic syntax for a do-while loop is as follows:
do {
Loop steps and other instructions
}
while (condition)
If programmed as a do-while script, our previous script would now look like this:
<?php
$number = 1;
do {
echo $number++ . "<br />";
}
while ($number <= 10);
?>
The result remains the same in our example. But the special thing about do-while loops is that they will run at least once even if the condition isn’t passed in any of the loops.
for loops
The basic idea behind a for loop in PHP scripting is the same as the while loop. However, unlike the while or do-while loops, the for loop features a start value, condition, and statement recorded within one row rather than over three or more rows. This means that the syntax for a for loop looks like this:
for (Start value; Condition; Loop steps)
Statement
Returning to the same example again, we can document it in a compact format as a for loop like so:
<?php
for($number = 1; $number <= 10; $number++) {
echo $number . "<br /> ";
}
?>
We’ve now defined the variable $number with the value 1. Next, PHP will check whether the condition $number <= 10 has been fulfilled. Provided this is the case, the loop will continue and the commands underneath the loop will be executed (in this case, the echo instruction). The loop is then repeated; in this example, it doesn’t make a difference whether you select a pre- or post-incrementing operation, because the command will always be executed before output. Once the loop step is closed the next loop cycle begins.
Start value, condition, and loop step are optional elements of a for loop. Theoretically, even empty loops are possible (although these would be redundant).
It’s basically up to you whether you write PHP scripts with a for loop or a while loop. But there is one argument for using for loops as your main method of looping: When you use for loops, you have a better view of the data for the loop. This prevents the risk of accidentally writing a forever loop that continues running until the interpreter’s memory is full. This could happen if you forgot to increase the value of the variable $number, for example.
If the loop just needs to run at least once, regardless of the conditions, then the do-while loop is the loop of choice.
break and continue
The course of a while-, do-while or for loop can be influenced by the break and continue command. The break instruction can be used to interrupt the course of a loop at a designated point, and continue can skip a loop pass and restart a loop once more. Both statements are bound to a condition through the if command. The following example demonstrates how to use a number counting script with a break:
<?php
for ($number = 1; $number <= 10; $number++) {
if ($number == 5) {
echo "The script stops at 5";
break;
}
echo $number . "<br /> ";
}
?>
In the for loop, we’ve set the definition that the value of the variable $number to start at a value of 1 and to increase by a value of 1 for every loop until the variable reaches the value of 10. We’ve also set the condition that the loop should stop running at the command break, which will come into play as soon as the $number variable reaches the value 5. Because of this, the language construct echo will only produce the numbers 1 to 4.
If we only want to stop the script for the fifth round, but then continue the loop afterwards, we can replace the command break with continue:
<?php
for ($number=1; $number <= 10; $number++) {
if ($number == 5) {
echo "We skip number 5!<br />";
continue;
}
echo $number . "<br /> ";
}
?>
File operators
Dynamic web content is created because of a separation between content and presentation. Scripting languages like PHP offer various functions to enable you to load content from external data sources in central template files. These data sources are usually databases that can be managed via management systems like MySQL. To learn more about how this works, check out our MySQL tutorial for beginners.
There’s also the option of embedding data from files. In the next section, we’ll show you how to include files as part of a string in your PHP script and how to store your script’s text output in files.
Reading files into an array
There are a few different functions in PHP that allow you to read content from a file. For the purpose of our tutorial, we’re going to focus on file() and file_get_contents(). While the function file_get_contents() reads all of the content of a file into a string, the function file() stores content as an array. Each element of the array corresponds to one line of the file. Meanwhile, using file() makes it easier to output each line individually.
We’ll demonstrate the PHP file operators for the text file example.txt, which we’ll store in the htdocs folder of our test server. The contents of this file are four lines of text:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean commodo ligula eget dolor. Aenean massa.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
Now, let’s read the whole file in as a string. To do so, we’ll need to use the function file_get_contents() ,with the name of the corresponding file within the brackets. This should look as follows:
file_get_contents(‘example.txt')
We now have the chance to work with our new string. We could, for example, define it as a variable and output it as text in the web browser:
<?php
$example = file_get_contents(‘example.txt');
echo $example;
?>
The browser display shows us that the text string is outputted as one solid paragraph. The line breaks in the original file are no longer visible. This is because the web browser has interpreted the text output of the script as an HTML code. This means that breaks defined in the text editor are lost.
There are a few options available to us if we want to keep our original structure. We could enter the HTML coding for a line break (br) in the file manually using the Find and Replace tool, add a <pre> to set the file content, and then add the gaps with the CSS command white space, assign pre-wrap, or use the function nl2br(), to signal to PHP that line breaks (new lines) should be automatically carried out in HTML line breaks (breaks). This works using the following syntax:
<?php
$example = file_get_contents(‘example.txt');
echo nl2br($example);
?>
If you want to output lines of a file individually, then you can do so with the function file(). This reads a file in, numerates all lines starting at 0, and stores their content as elements of an array. By transferring our example to this function, we can see the following organization:
[0] = Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
[1] = Aenean commodo ligula eget dolor. Aenean massa.
[2] = Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
[3] = Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
To output this content using echo, all we have to do is enter the line number we want. For example, the following script provides just the first line of the example.txt file for our browser:
<?php
$example = file("example.txt");
echo $example [0];
?>
Write files
PHP doesn’t just let you read out files. The scripting language also gives you the option to create files and write them with content.
For this, we’ll use the PHP function file_put_contents(). This requires two parameters: The name of the file that is to be created or updated as well as the data in the form of a string or an array. The following script will create the file test.txt and write the string This is a test! in the first line. The addition of \r\n executes a line break in the target file.
<?php
file_put_contents("test.txt", "This is a test! \r\n");
echo "test.txt was created!";
?>
Since file_put_contents doesn’t deliver an output for the browser, we need to add an echo statement to show the action taken in the browser.
If a file with the same name already exists in the target folder, it will be automatically overwritten. To prevent this, you can set the FILE_APPEND parameter:
<?php
file_put_contents("test.txt","The test was successful! \r\n", FILE_APPEND);
echo "test.txt was updated!";
?>
You don’t have to define what PHP writes in the target file in the script. Alternatively, you have the option to transfer content from one file to another. The following script reads the content from example.txt and inputs it in the file test.txt:
<?php
$example = file_get_contents("example.txt");
file_put_contents("test.txt", $example, FILE_APPEND);
echo "test.txt was updated!";
?>