What is PHP? How does it work on the server?
PHP is a server-side programming language, which means it runs on the server and generates content that will be
sent to the user's browser. For example, when you access a .php page, the server executes the PHP
code, and the result (usually HTML, JSON, or text) is sent back to the browser.
PHP is mainly used to build dynamic websites and web applications. Unlike HTML, which is static, PHP can fetch data from a database, process forms, authenticate users, and much more.
In short, the flow is:
- The browser sends a request to the server (e.g.,
index.php). - The server interprets the PHP code.
- The result is sent as HTML to the browser.
Installing XAMPP / Laragon / MAMP
To run PHP on your computer, you need a local server. The most popular options are:
XAMPP
XAMPP includes Apache (web server), MySQL (database), and PHP. It is available for Windows, Linux, and Mac. After installation, start the Apache and MySQL modules from the control panel.
Laragon
Laragon is highly appreciated for its simplicity and fast startup. It is available only for Windows and provides an easy-to-use environment for PHP and MySQL.
MAMP
MAMP is a popular option for MacOS and Windows, offering the same combination of Apache, MySQL, and PHP.
After installation, place your PHP files in a special folder (e.g., htdocs for XAMPP) and access
http://localhost/ in your browser to see the results.
First Script: Hello, world!
Your first PHP file can be very simple. Create a file named index.php in the htdocs
folder and add the following code:
<?php
echo "Hello, world!";
?>
When you access http://localhost/index.php in the browser, the server will execute the script and
display the text "Hello, world!".
Comments (//, #, /* ... */)
Comments are pieces of text that are not executed by the server but help programmers understand the code. PHP allows three styles of comments:
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multi-line comment
*/
?>
Comments are very useful when you want to explain the logic of your program or remember why you wrote a certain piece of code.
Debugging: var_dump(), print_r()
During learning and development, you will want to see the values of your variables. For this, PHP provides debugging functions.
var_dump()
Displays the type and value of a variable, including its internal structure (for example, for arrays and objects).
<?php
$number = 42;
var_dump($number);
$array = ["apple", "pear", "plum"];
var_dump($array);
?>
print_r()
Displays the content of a variable in a simpler way (especially useful for arrays).
<?php
$fruits = ["apple", "pear", "plum"];
print_r($fruits);
?>
☞Important to know:
These functions are useful only for debugging and should not be left in the final application code.