2021
PHP Introduction

PHP Introduction

Translated from German using DeepL.

Date: October 2021
Reading time: 8 minutes


Now that I've been dealing with the language for exactly one month, I'll show you what PHP is.

History

PHP (Hypertext Preprocessor) is a scripting language used in web development. The syntax is based on C and Perl. Rasmus Lerdorf developed it in 1994 to enable the creation of dynamic web applications. Last month, the PHP Group released version 7.4.24 of the software.

Scripting language: A scripting language is a programming language that is not compiled but interpreted at runtime.

Rasmus Lerdorf: The Danish-Canadian developer has worked at IBM, Linuxcare, Yahoo and WePay. He has been working at Etsy, an e-commerce website, since 2012. He is also an open source activist. He developed the first two versions of PHP.

Usage

PHP is ideal for creating interactive websites. The server-side language can be easily integrated into HTML to add functionalities to the web application. The functionalities include

  • Display of dynamic content
  • Simple evaluation of forms
  • Database connections (MySQL, PostgreSQL, Oracle, Sybase, Informix and Microsoft SQL Server)
  • Session tracking

This enables the implementation of:

  • E-commerce systems
  • chats
  • forums
  • ...

Advantages

The advantages of PHP include:

  • Easy to learn and implement
  • Free of charge
  • Open source
  • Cross-platform compatibility (Windows, Linux, UNIX and macOS)
  • Large community (there are many developers and a lot of knowledge)

Distribution

According to W3Techs, PHP is used on 78.7% of all websites. This is also due to the fact that the language is used by content management systems such as Wordpress.

Projects

It is now clear why PHP is used. But which well-known projects take advantage of PHP?

Facebook

The Facebook platform was developed with PHP. In fact, the company has developed a new language based on PHP (Hack). This allows static and dynamic type-checking.

Static: The types of the variables are already known when compiling.
Dynamic: The types of the variables are only recognized at runtime.

Yahoo!

The Yahoo search engine, which generates more than 7 billion hits per month, also relies on PHP. PHP is therefore proving to be particularly reliable for complex applications.

WordPress

The best-known content management system was also written with PHP.

Popularity

Despite its many advantages and influential projects, PHP does not have an excellent reputation. The programming language is considered unsafe.

This is due to the fact that almost anyone can create a PHP application in just a short time. Very little knowledge is required. The disadvantage of this is that this can also result in bad code, as the language has few restrictions. This can lead to security problems. However, these dangers can be averted. So if you write good code, a PHP site is secure.

Problems and their prevention:


Content currently not available.


Setup

In order to use PHP, it must be installed or provided by a web server.
I use MAMP (opens in a new tab).
After the installation you can store the PHP files in the htdocs folder. This way you can access the website via the localhost.

Syntax

Hello World!

The syntax can be executed both in the browser and in the console.

Console

hello.php
<?php
echo "Hello World!";
?>
php hello.php

Browser

index.php
<html>
	<head>
		<title>PHP</title>
	</head>
	<body>
		<?php
			echo "Hello World!";
		?>
	</body>
</html>

Embedding

There are two ways to embed PHP. Normally you use the PHP extension as follows:

<?php
	foreach ($arr as &$value) {
		echo "<p>" . $value . "<p>";
	}
?>

Sometimes, however, it makes sense not to include the entire PHP block. You can therefore make use of the short echo tag. This is a shortened notation:

<?php foreach ($arr as $value): ?>
	<p><?= $value; ?></p>
<?php endforeach; ?>

Variable declaration

PHP allows the following data types:

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • Null
  • Resource

However, no data type can be explicitly assigned to a variable.

$name = "Kay";
echo $name;

Methods

Functions are created with the keyword function.

function volume(int $length, int $width=1, int $height=1): float {
	return $length * $width * $height;
}

Arguments

There are several ways to define the arguments of a function.

Default

If no value is specified when the function is called, the specified number is used.

function testFunc(int $num = 5) {};
Nullable

Assigns the method parameter null. This means that no attribute needs to be specified when the method is called.

function testFunc(int $num = null) {};
Recommended

You can recommend a value with a question mark. However, no attribute must be specified here either.

function testFunc(int ?$num) {};

Return types

The type of the return value can be defined for methods.

function testFunc(): int {};

GET & POST

There are two ways to send data from the client to the web server.

Topic$_GET$_POST
ExplanationThe method sends the information appended to the page request. Example: http://get.com/index.htm?name=wild&lastName=kay. To encrypt this, you would have to encrypt the query string with the encrypt() method.With this method, the data is sent via the HTTP header. They are not visible in the URL.
Maximum amount of data1024 charactersNo maximum limit (depending on server and client)
SecurityTrusted data must not be sent. Security depends on the HTTP protocol. The information is secure with HTTPS.The security also depends on the HTTP protocol. The information is secure with HTTPS.
Exampleget.php example (see code below)post.php example (see code below)
get.php
<?php
if( $_GET["name"] || $_GET["age"] ) {
    echo "Welcome ". $_GET['name']. "<br />";
    echo "You are ". $_GET['age']. " years old.";
    exit();
}
?>
<html>
	<body>
		<form action = "<?php $_PHP_SELF ?>" method = "GET">
			Name: <input type = "text" name = "name" />
			Age: <input type = "text" name = "age" />
			<input type = "submit" />
		</form>
	</body>
</html>
post.php
<?php
if( $_POST["name"] || $_POST["age"] ) {
    echo "Welcome ". $_POST['name']. "<br />";
    echo "You are ". $_POST['age']. " years old.";
    exit();
}
?>
<html>
	<body>
		<form action = "<?php $_PHP_SELF ?>" method = "POST">
			Name: <input type = "text" name = "name" />
			Age: <input type = "text" name = "age" />
			<input type = "submit" />
		</form>
	</body>
</html>

$_REQUEST

The $_REQUEST variable contains GET, POST and cookie data. It can therefore be used to obtain the result of both methods.

MySQL

As already mentioned, PHP enables close interaction with databases.

Connect DB

One line is enough to connect to the DB.

connectToDB.php
$mysqli = new mysqli("url.com", "username", "password", "database");

You can then edit, delete, add and fetch the data.

Add data

$sql = "
	INSERT INTO sneaker (name, brands, model, colour, quantity, size, price, retail, releaseDate, artists,
	designers, athletes, img) VALUES (
	'Jordan 1', 'Nike', 'Jordan', 'White/Red/Black', NULL, '11', '80', '180', '2021-08-02', NULL, NULL, 'Michael Jordan', 'imgs/jordan-one.png', NULL);
";
$this->mysqli->query($sql)

Load data

getData.php
$response = $this->mysqli->query("SELECT * FROM sneaker");
while ($row = $response->fetch_assoc()) {
	echo $row["name"] "<br>";
}

Close DB connection

connectToDB.php
$this->mysqli->close();

OOP

PHP also enables object-oriented programming.

Define class

A class is defined as follows:

<?php
class Vehicle {}
?>

Variables & methods

<?php
class Vehicle {
	/* Property */
	private $speed = 0;
 
	/* Method */
	function output() {
		echo "Speed: $this->speed<br>";
	}
}
?>

Variables and methods can have different visibilities.

Visibilityprivateprotectedpublic
AccessibilityOnly within the class definitionOnly accessible within the class in which they are created and in classes derived from itAccessible from anywhere

Instantiation

The syntax for instantiating objects is as follows.

$vespa = new vehicle();
$vespa->output();

This

To access a variable of your own class, you can use this.

$this->speed = $sp;

Constructor & deconstructor

The name of the constructor is not the same as the class name. In PHP it looks like this.

vehicle.php
function __construct($name, $speed) {
	$this->name = $name;
	$this->speed = $speed;
}
$tesla->__construct("Tesla", 10);

The deconstructor is executed when an object is destroyed.

function __destruct() {
	echo "Destruktor<br>";
}

Copy & reference

Objects can be copied in different ways. This is explained here.

Reference

The names of the objects with which they can be accessed are only a reference.
Assigning an object to a different name creates another reference to the same object.
The object can then be changed via both references.

Copy

A copy creates a second object. This has the same properties and values.
However, the objects are changed individually.

clone

This is a copying process that can be carried out with clone. The process can be customized using the __clone() method.
With predefined cloning, all property values are copied.

Serialization & deserialization

Serialization creates a representation of the current value of a variable or object. This representation can then be saved.

serial.php
include "Vehicle.php";
$vespa = new Vehicle("Vespa Piaggio", 25, "rot");
$s = serialize($vespa);
file_put_contents("serializedClass.dat", $s);
echo "Object serialized and saved in file";

Converting this representation again is called deserialization.

deserial.php
include "Vehicle.php";
if (!file_exists("serializedClass.dat")) {
	exit("File not found");
}
$s = file_get_contents("serializedClass.dat");
$vespa = unserialize($s);
echo "Object read from file and deserialized<br>";
echo $vespa;

Frameworks

A framework usually has the following advantages.

  • Facilitates development
  • Helps to remove redundant code
  • Leads to better structure
  • Makes an application more secure
  • Errors are prevented more often

There are several PHP frameworks. These are 5 well-known ones:

FrameworkDescriptionStrengths
SymfonySymfony is an MVC framework used by well-known CMS (Drupal, Joomla!, ...) and e-commerce systems (Magento, PrestaShop, ...).It is one of the best-known free open source frameworks for project development, installation and most components, flexibility, integration with large companies, configuration on the platforms, use of reusable projects such as Drupal
LaravelLaravel is one of the best-known free open source frameworks. It enables the secure handling of complex applications. The framework helps with the integration of authentication, caching, sessions or routing.Many features, security, development of applications with a complex backend, speed
CodeIgniterThe small and free framework helps with the development of dynamic websites. CodeIgniter can also be used to create components.Speed, setup, clear documentation, easy creation of websites and components
CakePHPCakePHP allows you to create a visually appealing website. It is relatively easy to learn.Security L Injection prevention, great documentation, easy installation, features like validation and XSS prevention
YiiYii is a component-based framework that is ideal for developing modern web applications.Easy installation, robust security features, speed and performance, data is used as objects, large community, extensibility, easy to learn

Conclusion

PHP is somewhat frowned upon because it is possible to write unclean and insecure code.

Nevertheless, PHP is extremely widespread on the web. It is precisely the many advantages that make the language interesting. Although PHP is one of the simpler languages, it enables the creation of large and popular websites.
And with version 8 (opens in a new tab) the language becomes even more appealing.