How do I learn PHP code

Part 1: Language characteristics, system requirements and getting started

more on the subject

Learning PHP: An Introduction to Programming Language

PHP is constantly being developed and now offers modern language concepts. The universal usability, the good database support and the availability for many systems speak for the frequent use.

In our basic introduction to programming, which was already published here onentwickler.de, we proceeded quite neutrally when it came to the choice of programming language. Of course we have shown one or the other example and have mostly used C # in conjunction with the .NET Framework. It is also a good choice for desktop applications, since many business applications in particular are created in this way.

In this series of tutorials, we would like to highlight another important topic for getting started in programming. It is about the development of web applications, which today offer an important opportunity to provide company applications. Multi-user and network operation can be implemented very easily with the help of such an application. The actual program runs on the server, the users access it via the network. The front end is provided by the user with the help of HTML, CSS and other modern browser technologies. The user therefore only needs a connection to the server and an up-to-date Internet browser to work with the application. The installation of additional software is usually unnecessary.

Learn PHP - the series

  • Part 1: Language characteristics, system requirements and getting started
  • Part 2: Form evaluation and object-oriented programming
  • Part 3: PHP and Databases: Working with the MySQL Database
  • Part 4: Database practice and file handling in PHP

These explanations on the topic should suffice for now, because we will come back to the structure and architecture of a web application in more detail later. Basically, there is an almost unmanageable variety of technologies available for programming web applications. It is not very productive to philosophize about the advantages and disadvantages of the individual approaches and concepts. In this series of tutorials, we introduce PHP. We are aimed at two addressees:

  1. Newcomers to programming: You can very well choose PHP as your first programming language, because you can find all common language concepts in PHP. If you later switch to another programming language, what you have learned can be profitably taken with you.
  2. Non-language and non-system developers: Has the intention of finally familiarizing yourself with the standard web language been at the top of your to-do list for a long time? You then have the advantage of finding a lot of related things from other languages ​​and you can start programming in PHP directly.

Whatever the motivation, in the following section of the text we will first deal with the basic properties of the programming language. Then we create the system requirements before we give a compact and systemic overview of PHP. In the following tutorials we will delve deeper into the subject. We will also implement one or the other example.

PHP - in a nutshell

PHP is short for PHP Hypertext Preprocessor. It enables developers to create dynamic Internet pages that can be used to create web applications. In contrast to static Internet pages, the content can change at any time due to user actions or data updates. In particular, PHP supports the simple evaluation of forms with which a user can send data to a website. It enables cooperation with many different database systems; MySQL, for example, is particularly well supported. Both components work together in the best possible way. Many content management systems are programmed in PHP and store their data in a MySQL database. Compared to other programming languages, PHP offers many advantages [2]:

  • Cross-platform: It supports a variety of platforms, including being easy to integrate into the frequently used Apache web server.
  • Easy to learn: Compared to other languages, PHP is relatively easy to learn because, unlike others, this language was developed exclusively for web server programming and therefore only contains the necessary components.
  • price: PHP is free. There is no need to buy a compiler or a development system. Programming can be done using a simple editor.

At this point we can already go into the basic functionality of a PHP program. The basis for this is a special variant of the client-server model. illustration 1 shows the principle. The user (client) does not need to have any software other than a conventional Internet browser installed.

At this point, the high flexibility of the approach becomes clear. Internet browsers are available for all operating systems and variants. It also doesn't matter whether it is a conventional desktop PC, a laptop or a smartphone or tablet. On the client side you don't come into contact with PHP, you only have to process HTML files (possibly CSS and JavaScript).

The application itself runs on the server. For this purpose, PHP is integrated into the web server and the actual PHP application is stored on it and, if necessary, installed. The user sends a request to the server via the browser. This request is processed by the PHP program. To do this, it may be necessary for the PHP program to call up data from a database. The database is also installed on the web server or can be accessed from there. On the basis of the request and its specific sequence (algorithm), the PHP interpreter now generates the response in the form of an HTML file that is transmitted to the client. The browser itself always receives an HTML file as a result and only needs to display this, i.e. H. it does not need to have any special properties related to the programming language of the server. The pages can therefore also be displayed by older browsers. In addition, this principle results in another, security-relevant advantage: The PHP program cannot be viewed by the client or can not be changed. Access to the server is necessary for this.

 

Fig. 1: The client-server model with PHP [2]

System requirements

For learning and practicing, we set up a minimal work and development environment locally on our PC / notebook. According to illustration 1 So we first need a web server with integrated PHP. Later on, the hardware of the web server will of course not be identical to the client computer, but this structure is useful for programming and learning. First, a few general remarks. The integration of PHP into the web server can be done in two different ways:

  1. SAPI module: It is a direct connection, but it is not available for all web servers. However, there are SAPI modules for important servers such as Apache and Microsoft IIS.
  2. CGI: The Common Gateway Interface allows PHP to be integrated into almost all servers.

The question of the type of installation does not have to concern us so much at the beginning, because the installation of PHP is considerably simplified with the help of the web server's automatic installer. This can be of interest if you later want to run finished PHP applications on a remote server. The type of installation, like the exact PHP version, is one of the properties that you have to pay attention to when renting a server. The question of a suitable web server immediately arises. Here it also depends on the operating system on which the installation takes place:

  • Microsoft Windows: On the one hand you can use the Internet Information Server (IIS). In current versions of the operating system, this can be done via the control panel | Activate or deactivate Windows Futures (Fig. 2). Apache is an alternative. This web server is the market leader and is available for a wide variety of systems. Apache runs on many web servers on the Internet, mostly under Linux. Ready-made installation packages are available to get you started easily.
  • Linux: The standard server is also an Apache. Many distributions already include support for Apache and / or PHP. For example, it only needs to be activated in the so-called runlevel editor under the Ubunto distribution.
  • Mac OS X: An Apache server is already installed in OS X. Here, too, it still needs to be activated (System Settings | Internet & Network | Sharing | Personal Web Sharing | Start).

Fig. 2: Installation of the IIS under Windows

Server installation

We have it easy and use a ready-made installation package for the Apache web server under Microsoft Windows. A very well-known project is XAMPP. It is also available for other operating systems and in different versions and configurations. From the website we choose under Downloads | Further downloads the current version (support of PHP 7) for Windows, specifically the portable version. It has the advantage that the server can be started immediately after downloading and unpacking the package.

An installation is not necessary, a minimal configuration is done automatically with the help of the enclosed script. We can therefore install the server on a USB stick and use it flexibly. Changes to the current PC configuration are not necessary. The package contains everything you need to start programming. After downloading (xampp-portable-win32-7.0.3-0-VC14.zip) the file has to be unpacked, in our case on a USB stick. For reasons of ease of use, we have put the directory in xampp renamed. The process can take a few minutes, time for a cup of tea!

Then the time has come. We look into the root directory. We are initially interested in the following files:

  • setup_xampp.bat: The setup (directories) for the web server takes place. This file must be executed before the web server is started for the first time.
  • xampp_start.exe: The web server is started.
  • xampp_stopp.exe: The web server can be stopped again.
  • xampp_control.exe: The control panel to display the status of the web server and to carry out the necessary basic configurations is executed.

So let's start with setup_xampp.bat. The process only takes a few moments. Then we start the web server for the first time (xampp_start.exe), the start process of which is displayed in a command line window (Fig. 3). For security reasons, the operating system may request the necessary releases the first time it is started. Also via the control panel (Fig. 4) the status of the server can be seen.

Fig. 3: The successful start of the Apache web server is logged in the console window

Fig. 4: Status and configuration of the Apache web server are made via the control panel

Once you have got that far, you can do a first test using the installed browser. We open the browser and enter the address: http: // localhost or.127.0.0.1 a. After that, the browser should display a page like in Figure 5 Show. The Apache web server dashboard is displayed. This offers references to help, FAQs, further configuration options and the possibility to run additional tools such as phpMyAdmin for the database configuration.

Fig. 5: The locally installed web server is accessed via the address "http: // localhost" or "127.0.0.1"

The question arises as to where the pages are located in the file system when using http: // localhost or 127.0.0.1 is accessed. In the standard configuration (and we want to leave it at that), this is the directory htdocs under the root directory of the server. In our case everything is on the USB stick. Our own PHP applications must therefore also be stored in this directory. To do this, we have another subdirectory called my within htdocscreated.

Hello World

We don't want to break with tradition and start with a classic "Hello World" program. PHP doesn't work without HTML. The PHP source code is either integrated directly into the HTML file or outsourced to external files and a reference is made. So that the web server knows that it is a file with PHP source code, its extension is set to php, for example test.php set. Basically, PHP files are pure text files, i. H. they can be created and read with any text editor. In fact, programming a dynamic web application does not necessarily require an integrated development environment; a text editor is sufficient; but a little more about this at the end of the tutorial. Table 1 shows the variants for integrating / labeling PHP code in an HTML file. The first variant is usually preferred. It is clear and yet short.

Table 1: Options for embedding PHP code in an HTML page [5]

For a first test we need an HTML file (Listing 1). The PHP source code is integrated in the body-Section. As already stated, by means of indicates that the following code is to be interpreted as PHP statements. This is just a single instruction. The function echo…“ is used to output a character string. The PHP section is created using ?> completed again. If we now call up the page in the browser (with the web server active), we will see exactly this character string as output (Fig. 6).

Fig. 6: Our first PHP program is traditionally a "Hello World"

You can also find out how the server is working by deactivating it and trying to display the page in the browser again. You will then receive an error message. This test is useful insofar as the browser would have processed a pure HTML file even without a server.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> <HEAD> <TITLE>Test von PHP</TITLE> </HEAD> <BODY> <?PHP echo "Hello World"; ?> </BODY> </HTML>

PHP - an overview of important language features

In the following we give a compact overview of important language features. The full language reference can be found at. In addition to the original documentation in English, it is available in many other languages, including also available in German. Let's start with the essential features of PHP:

  • Comments: These are through "#" or. „//"And apply until the end of the line.
  • Instructions: These are terminated with a semicolon and grouped by curly braces.
  • Numeric literals: Without a decimal point these are interpreted if they are marked with "0x“Or“ 0X ”begin; in all other cases as a decimal integer constant.
  • String literals: These are enclosed in single or double quotation marks (‚or“). The following are therefore permitted: 'This is a character string' or 'This is also a character string'.
  • Function names: PHP is not case-sensitive, i. H. no distinction is made between upper and lower case.
  • Variable names: Valid variable or function names begin with a letter or underscore, followed by any number of letters, numbers, or underscores; Variable names are case-sensitive, they start with a $, for example: $ amount and $ Amount are two different variables.
  • Data types: PHP supports the usual data types; an overview can be found in Table 2.

Table 2: Data types supported by PHP [4]

As in any language, there are a number of keywords in PHP (Table 3), which are then logically not available for other purposes.

Table 3: List of reserved keywords [5]

To assign a value to a variable in PHP, you use the equal sign, for example the syntax looks like this: $ Quantity = 3;

The typical arithmetic operators and comparison operators are in the Tables 4 and 5 summarized.

Table 4: The arithmetic operators and their short forms [3]

Table 5: The comparison operators [3]

We come to the most important statements and control structures of PHP [5]:
  • Conditional statement: This has the general form: condition? a: b. Is the condition true, becomes a returned, otherwise b.
  • if statement: This statement tests a Boolean value and leads to the result true the following code block. Any number of additional conditions can be added to the code block using the elseif- Follow instruction. An optional one to be given last else-Branch is executed if all the conditions of the if- and the elseif-Branches were wrong. Example:
if ($ x> 10) {//… instructions} elseif ($ x <10) {//… instructions} else {//… instructions}
  • switchStatement: This statement is equivalent to a series of consecutive if statements with the same parameter that is checked for different values. It has the form: switch ($ x) {case value0: //… statements break; //… case Values: //… instructions break; default: //… instructions}

    Note: In PHP, comparison values ​​are in the case statement (Value 0 ... value n) does not open Integer or Char limited, but can e.g. Belly String or Float be.

  • for-Loop: The consists of three parts separated by semicolons: for (initialization, termination condition; action) {//… instructions}

    An initialization can take place once at the start of the loop. Before each execution of the loop body, it is checked whether the termination condition has been met. After every execution of the loop body there is the possibility to carry out an additional action. This is often a matter of increasing or decreasing a loop counter. Example:

for ($ i = 0; $ i <10; $ i ++) {//… instructions}
  • foreach-Loop over arrays: With the foreach- The individual elements of an array can be traversed in a loop. It has the following form: foreach ($ array as $ key => $ value) {//… instructions}

    If the key is not of interest, the following short form can also be used:

    foreach ($ array as $ value) {// ... instructions}

    $ array is the array to be traversed and the variables $ key and $ value receive the key-value pair of the current element in each pass.

  • while statement: The while statement (condition) {//… statement}

    executes the following code block as long as the condition true is. The condition is also checked before the code block is entered for the first time.

  • Also by means of the whileStatement can be traversed through an array:
reset ($ array); while (list ($ key, $ value) = each ($ array)) {// ... instructions}
  • Do ... whileStatement: This statement is the while-Statement very similar, except that the truth of the expression is only checked at the end of each run.
  • Loop control: Through continue the loop is terminated at the current position and the next run is started. continue can optionally be given a numeric argument that specifies how many levels should be skipped by the received loops. break breaks the execution of the current loop or one switchInstruction off. Also break Optionally, a numeric argument can be appended that contains the number of levels of the command sequences to be aborted.

PHP has a large number of predefined functions from a wide variety of areas. One such function was the function used above echo "..." with the help of which a character string could be output. The most important function classes are: String functions, functions for arrays, mathematical functions, control functions, time and date functions, file functions as well as class and object functions. There are also a number of functions for working with a database (establishing a connection, querying data). These are comprehensively documented in the online help. If you come across a problem while programming, it is definitely worth checking whether there is already a ready-made function for the task in question.

Tools

A craftsman is only as good as his tools. There are also a number of development environments available for PHP programming, which differ considerably in terms of performance. The right or better development environment does not exist, it depends on the individual requirements. The desire for more comfort and support is known to grow with the size of the project. Important criteria for the selection are:

  • Syntax highlighting
  • Code completion
  • Real-time failure analysis
  • easy and quick navigation
  • Refactoring
  • Source code generation
  • Integration of versioning systems

A list of PHP development environments would most likely always be incomplete. Important representatives are PhpStorm, Sublime Text, NetBeans, Zend Studio, Eclipse with PHP Development Tools (PDT) [13] and Visual Studio Code has recently been added. The latter development environment is based on Visual Studio and could be particularly interesting for developers who come from the Microsoft universe and take their first steps with PHP. Some tools can also run on different operating systems. We recommend "to bake small rolls" to start with. H. a reasonably comfortable text editor such as TextPad is sufficient. There is already enough to learn with a new language so that the tool support can be expanded later. PHP is made for this kind of easy entry.

Conclusion

We have already come back to the end of the first part about the introduction to programming with PHP. The focus was initially on the basic procedure and establishing the technical requirements. To do this, we installed a local web server, created a typical "Hello World" program for testing and learned the first basic basics of the language.

If you already have programming experience in another language, you can actually start now. We will continue our introductory course in the upcoming developer magazine. We complete the overview of the language features, including we will explicitly go into the object-oriented possibilities of PHP, which have been significantly expanded from version 5 onwards.

For all those who do not have a concrete use of PHP at the moment, two tips: PHP is the language of many established content management systems. If you want to configure or expand these, knowledge of PHP is more than useful. Perhaps you will not choose a desktop application for the next application, but instead create a dynamic web application as an alternative.

literature

[1] Krypczyk, Veikko and Bochkor, Olena: "Introduction to programming", in: Developer magazine 3.2015 to 2.2016

[2] Thies, T .: "Introduction to PHP 5.6 and MySQL 5.6", Galileo Press, 2014

[3] Wenz, C., Hauser T .: “PHP 5.6 and MySQL. The Comprehensive Handbook ”, Rheinwerk Computing, 2015

[4] PHP, basics. Creation of dynamic websites, RRZN, Leibniz University Hannover, 2012

[5] Henning, P. and Vogelsang, H .: "Taschenbuch Programmiersprachen", Hanser-Verlag, 2007