An introduction to PHP 8.3

Nice that you are interested in PHP. Here you will find an introduction to PHP, which is mainly aimed at PHP beginners.

On the following pages, we want to explain to you how you can successfully program with PHP and what mistakes to avoid

Let's learn PHP!

What you can learn here:

Setting up the development environment (IDE)

Before you can start working on your first PHP project, you need to set up a development environment.

An integrated development environment (IDE) is a special program that helps developers write, test, and debug software. An IDE usually provides many useful features and tools that can make the development process easier and faster, such as:

  • Syntax highlighting - The different parts of the code are highlighted with different colors to make the code easier to read and clearer.
  • Auto-completion - The IDE suggests code snippets and functions that the developer may want to use to save typing and speed up the development process.
  • Troubleshooting - The IDE can help find syntactical errors in the code and alert the developer to potential problems.
  • ...

While it is not mandatory to use an IDE, we recommend that you use a text editor such as Notepad++, Sublime Text or Atom.

How do I run my PHP code?

To run your PHP code, you first need a server that can run PHP. This can either be a local server on your computer or a remote hosting account.

Once you have a server, you can run your PHP code in the following way:

Create a new file with the extension ".php". hallowelt.php would be a good start :)

Save the file in a directory that can be executed by the server. This is usually in the "htdocs" directory of the server.

Open a web browser and enter the URL that points to the PHP file. This URL should be in the form "http://localhost/hallowelt.php", where "localhost" can be replaced with the IP address or hostname (domain) of the server if the code is running on a remote server.

Introduction to PHP - my first PHP script

If you have done everything so far, we can start to write a first small PHP Script

Open your IDE and create a PHP file with the name "hallowelt.php". Often the IDE recognizes which file format it is and adds CODE automatically. Your file should have the following content:

<?php
// Your PHP-Code here
?>

As you can see here, the file consists of a <?php and a ?> part. These two tags indicate where the actual PHP code is located. No PHP code is executed outside of these PHP tags.

The simplest PHP command is "echo" and gives an output on the browser

<?php
    echo "Hello Welt!";
?>

Now try to execute your PHP file. You should be able to read "hello world" in the browser. If not, check your URL in the browser or the directory where you saved your PHP file.

Variables in PHP - a simple example

Almost no program is static or uses only static data. To make a program flexible, variables are used.

A variable is a memory location in which values can be stored. In programming, variables are used to store values that are needed in the program. Often variables are changed during the execution of the program.
Variables usually have names that are distinguished from other variables in the program, and can hold different types of data, such as numbers, strings, or Boolean values. They are used in almost all programming languages and are an important part of algorithms because they allow values to be stored and changed dynamically.

Variables start with a dollar sign ($) in PHP. Variable names must begin with a letter or underscore (_) and can only consist of letters, numbers, and underscores.

Here are some examples of valid variable names in PHP:

$name
$alter
$City
$_Tel

To define a variable in PHP, you use the equality operator (=). The value you want to assign to the variable is enclosed in quotes if it is text (a string), or without quotes if it is a number.
Here are some examples of defining variables in PHP:

$name = "Bernie";
$alter= 40
$City = "Frankfurt";
$_Tel = "069/6767676";

Once you have defined a variable in PHP, you can use it in your code.
For example:

<?php
echo "Mein Name is $name and I am $age years old and live in $City";
?>

This would output the text "My name is Bernie and I am 40 years old and live in Frankfurt".

It is important to note that PHP variables are case-sensitive, i.e. $name and $Name are two different variables.

Control structures - "if"-"else" statements in PHP

PHP supports various control structures such as "if"-"else" statements that allow you to execute code based on certain conditions.

Here is an example of an "if"--"else" statement:

<?php
$alter = 18;
if ($alter > 17) {
  echo "Du bist volljährig";
} else {
  echo "You are still a minor";
}
?>

Loops in PHP

Loops are used quite often in PHP, for example, to execute a statement or a group of statements repeatedly. This is especially useful when you need to process a large amount of data, such as querying a list of users in a database and then processing each user individually.

In PHP there are several types of loops

for Loop

This loop is used to execute an instruction or group of instructions for a predetermined number of iterations.

Here is an example of a for loop in PHP:

<?php
    for ($i = 1; $i <= 10; $i++) {
    echo $i;
}
?>

This loop will output the numbers from 1 to 10. The first statement $i = 1 initializes the loop counter to 1. The second statement $i <= 10 is the condition that will be checked to determine if the loop continues. The third statement $i++ increments the loop counter by 1 after each iteration. The statements inside the curly braces are repeated as long as the condition is met.

while Loop

This loop is used to execute a statement or a group of statements as long as a certain condition is met.

Example of a while loop in PHP:

<?php
    $i = 1;
    while ($i <= 10) {
    echo $i;
    $i++;
    }
?>

do...while Loop

This loop is similar to the while loop, but it executes the statements at least once before checking the condition.

Example of a do-while loop in PHP:

<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i <= 10);
?>

foreach Loop

This loop is used to pass through the elements of an array one by one.

Example of a foreach loop in PHP:

<?php
$colors = array('red', 'green', 'blue');
foreach ($colors as $color) {
echo $color;
}
?>

Arrays in PHP

In PHP, arrays are data structures that allow multiple values to be stored under a single name. So not like a variable that can have only one value. The values in an array are called elements and can be of different types, such as strings, integers, or even other arrays (nested arrays or multidimensional array).

Arrays are created in PHP with the keyword "array" and the elements are specified in parentheses, with each element separated by a comma.

<?php
// Numeric array with three elements
$autos = array('VW', 'TESLA', 'AUDI');

// Associative array with three elements and user-defined keys
$autos = array(
  'auto1' => 'VW',
  'auto2' => 'TESLA',
  'auto3' => 'AUDI'
);

// Multidimensional array with three elements, which in turn each contain an array
$autos = array(
  array('VW', 'DE', 'Benziner'),
  array('TESLA', 'US', 'eAuto'),
  array('AUDI', 'DE', 'hyprid')
);
?>

Access PHP arrays

To access the elements of an array, the array name is specified with a key in square brackets.

<?php
// Access to the first element of the array
$autos $fruits[0]; // output: "VW"

// Access to the element with the "autos2" key
echo $autos['autos2']; // output: "TESLA"

// Accessing the first element of the second array in a multidimensional array
echo $autos[1][2]; // output: "eAuto"
?>

There are many PHP functions that can be used to work with arrays. The functions "array_push" e.g. adds an element to the end of an array, "sort" to sort array elements or "count" to get the number of elements in an array.

Operators and expressions in PHP

Operators in PHP are symbols or characters that are used to perform certain operations. The most common operators in PHP include arithmetic operators such as "+" (plus), "-" (minus), "*" (multiplication) and "/" (division), but also comparison operators such as "==" (equal), "!=" (not equal) or "<" (less than) and logical operators such as "&&" (AND) and "||" (OR).

Outputs in PHP are any type of statement that returns a value. Outputs in PHP include arithmetic outputs that return calculated values, comparison outputs that return either true or false, and logical outputs that also return true or false.

<?php
// Arithmetic expression: Addition of two numbers
$result = 3 + 4; // $result has the value 7

// Comparison expression: comparison of two strings for equality
$result = 'abc' == 'abc'; // $result has the value true

// Logical expression: linking two comparison expressions with the AND operator
$result = (3 > 2) && (4 > 3); // $result has the value true
?>

It is important to note that expressions in PHP can be used in statements such as loops or branches to execute or skip certain blocks of code. For example, you could use a comparison expression in an "if" statement to decide whether or not to execute a particular block of code.

Security in PHP programs

As a PHP programmer, you have a responsibility to pay attention to security in your PHP programs because security vulnerabilities in a program can allow attacks from hackers. If security holes in a program are exploited, the attackers may be able to steal sensitive data such as passwords or credit card information, manipulate the program, or even cause damage.

In addition, security vulnerabilities in a program can also cause the program to stop working properly, resulting in unexpected errors and possible loss of data.

To avoid these risks, it is important to consider security-related aspects in programming and ensure that all inputs are validated and sanitized, secure passwords are used, and secure connections are used, to name just a few examples.

Here are some tips that can help you program more securely in PHP:

  • Always use the latest stable version of PHP. Security vulnerabilities are often fixed in newer versions of PHP, so it is important to always use the latest version.
  • Ensure that all input from users or other external sources is validated before it is used in your code. This can help avoid security threats such as SQL injection or cross-site scripting (XSS).
  • Prepared statements allow SQL queries (SQL injection) to be executed securely by preventing malicious code from being injected into the query.
  • Use strong, long passwords and never store them unencrypted. Also, use password hashing functions like "password_hash" to store passwords.
  • Always use secure connections (https) for all sensitive data transfers.
  • Make sure all configuration files and settings are secure and avoid insecure settings like "register_globals".
  • Avoid unsafe code practices such as directly outputting user input without validation or using functions that are considered unsafe, such as "eval".
  • Using outdated or incompatible libraries or frameworks. It is important to always use the latest and compatible version of libraries and frameworks to ensure that the program runs stably and safely.
  • Ignoring error messages. Error messages contain important information about what went wrong in the program and should definitely be heeded in order to fix errors quickly.
  • Overloading functions. Functions should be defined as clearly and precisely as possible and should not take on too many tasks. This way, the code remains clear and maintainable.
  • Using incomplete or inconsistent tests. It is important to use comprehensive and consistent tests to ensure that the program works correctly.
  • Ignoring performance optimizations. It is important to regularly check the performance of the program and make optimizations to ensure that the program runs quickly and efficiently.

These are just a few examples of how you can program securely in PHP. There are many more aspects that should be considered to avoid security threats. It is therefore advisable to regularly inform yourself about security vulnerabilities and best practices in PHP and to take appropriate measures.

Publish a tutorial

Share your knowledge with other developers worldwide

Share your knowledge with other developers worldwide

You are a professional in your field and want to share your knowledge, then sign up now and share it with our PHP community

learn more

Publish a tutorial

ASCII Datenbanken

ASCII Datenbanken sind eigentlich nur Textdateien, in denen man Daten speichert, die durch ein Trennzeichen voneinander getrennt sind. Dieses Tutorial zeigt wie es geht. Mit Übung und Lösung ...

deep_space_nine@

Autor : deep_space_nine@
Category: PHP-Tutorials

abhängige Listen

In einem Formular sollen neben mehreren anderen Eingabefeldern auch zwei Listen (Select-Felder) zum Einsatz kommen. Dabei soll der Inhalt der zweiten Liste vom gewählten Wert der ersten Liste abhängig verändert werden. ...

Patrick_PQ

Autor : Patrick_PQ
Category: mySQL-Tutorials

Variablen über mehrere Seiten hinweg verwenden - der Session-Befehl macht 's möglich!

Oberste Voraussetzung um Session-Befehle korrekt auszuführen ist, dass der Provider a) PHP und b) das speichern von Sessions auf dem Server überhaupt erlaubt. Wird der Session-Befehl unterstützt jedoch nicht das direkte speichern von Sessions bzw. Sess ...

ndo@

Autor : ndo@
Category: PHP-Tutorials