DEV Community

HugoDemont62
HugoDemont62

Posted on

PHP Base for MMI

PHP and HTML Course (Beginner)

Table of Contents

Introduction

PHP is a server-side programming language used for creating dynamic web pages. PHP stands for "PHP: Hypertext Preprocessor."

Language Basics

Variables

A variable is a container for storing data values. It has a name and a value. Variables are created with a dollar sign followed by the variable name:

<?php
$variable_name = "value";
// Always remember the semicolon at the end of the line! (in other languages, it may not be required)
?>
Enter fullscreen mode Exit fullscreen mode

(Note that in PHP, you need to open and close PHP tags for the code to be interpreted.)

Variable Types

Variables can store different types of data, and different data types can perform different tasks. PHP supports the following data types:

  • String
  • Integer
  • Float (Decimal number)
  • Boolean
  • Array
  • Object
  • NULL

Example:

<?php
$name = "John";
$age = 25;
$height = 1.85;
$is_adult = true;
$fruits = array("apple", "banana", "orange"); 
// or
$fruits = ["apple", "banana", "orange"];
$object = new stdClass();
$nothing = null;
?>
Enter fullscreen mode Exit fullscreen mode

Constants

Constants are similar to variables, but once defined, they cannot be changed or deleted later.

Example:

<?php
const NAME = "John"; 
?>
Enter fullscreen mode Exit fullscreen mode

Operators

Operators are used to perform operations on variables and values. Like in mathematics, PHP operators are used for arithmetic operations such as addition, subtraction, multiplication, division, etc.

Example:

<?php
$x = 10;
$y = 6;
$z = $x + $y;
echo $z; // Outputs 16
?>
Enter fullscreen mode Exit fullscreen mode

(There are, of course, other operators like increment, decrement, addition, subtraction, multiplication, division, modulus, etc.)

Example of increment and decrement:

<?php
$x = 10;
echo $x++; // Outputs 11
echo ++$x; // Outputs 12
echo $x--; // Outputs 11
echo --$x; // Outputs 10
?>
Enter fullscreen mode Exit fullscreen mode

Conditions

Conditional statements are used to perform different actions based on different conditions. There are three types of conditional statements in PHP:

  • if
  • else
  • elseif (There are others available, but these are the most commonly used.) The others include switch, ternary, etc.
  • The ternary is a condition that allows you to perform an if/else on a single line.

    • Example:
    <?php
    $age = 18;
    echo ($age >= 18) ? "Adult" : "Minor";
    ?>
    
    • The switch is a condition that allows you to perform an if/else over multiple lines.
    • Example:
      <?php
      $age = 18;
      switch ($age) {
        case 18:
          echo "You are 18 years old";
          break;
        case 19:
          echo "You are 19 years old";
          break;
        default:
          echo "You are a different age";
      }
      ?>
    

For if/else/elseif, here's an example:

<?php
$age = 18;
if ($age >= 18) {
  echo "Adult";
} elseif ($age == 17) {
  echo "Almost an adult";
} else {
  echo "Minor";
}
?>
Enter fullscreen mode Exit fullscreen mode

Loops

Loops are used to repeatedly execute the same block of code as long as a specific condition is met. There are four types of loops in PHP:

  • for
  • foreach
  • while
  • do...while

Example of a for loop:

<?php
for ($x = 0; $x <= 10; $x++) { // (initialization; condition; increment)
  echo "The number is: $x <br>";
}
?>
Enter fullscreen mode Exit fullscreen mode

Example of a foreach loop:

<?php
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) { // (array as variable), here $fruit is the variable that iterates through the $fruits array
  echo "$fruit <br>";
}
?>
Enter fullscreen mode Exit fullscreen mode

Example of a while loop:

<?php
$x = 1;
while ($x <= 5) { // (condition), here, as long as $x is less than or equal to 5, we display the number
  echo "The number is: $x <br>";
  $x++;
}
?>
Enter fullscreen mode Exit fullscreen mode

Example of a do...while loop:

<?php
$x = 1;
do { // (condition), here, as long as $x is less than or equal to 5,
// we display the number (similar to while, but the condition is checked at the end of the loop)
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>
Enter fullscreen mode Exit fullscreen mode

Functions

A function is a block of statements that can be used multiple times in a script. A function is not executed immediately when a page is loaded; it is executed by calling the function.

Example of a function:

<?php
function sayHello() {
  echo "Hello!"; // Outputs Hello!
  // You can also use return "Hello!"; to return a value
}

sayHello(); // Calling the function
?>
Enter fullscreen mode Exit fullscreen mode

Arrays

An array stores multiple values in a single variable. Each value has an identifier (key) associated with it. Arrays can contain strings, numbers, objects, functions, and even other arrays.

Example of an array:

<?php
$fruits = array("apple", "banana", "orange"); // Indexed array
$people = ["John", "Doe", "Jane"]; // Indexed array (alternative syntax)
$person = array("name" => "John", "age" => 25); // Associative array
// Multi-dimensional array (array within an array)
$hobbies = [
  ["name" => "John", "age" => 25],
  ["name" => "Doe", "age" => 30],
  ["name" => "Jane", "age" => 28]
];
?>
Enter fullscreen mode Exit fullscreen mode

To iterate through an array, you can use a loop:

<?php
$fruits = ["apple", "banana", "orange"];
for ($i = 0; $i < count($fruits); $i++) {
  echo $fruits[$i] . "<br>";
}
?>
Enter fullscreen mode Exit fullscreen mode

To traverse an associative array, you can use a foreach loop:

<?php
$person = array("nom" => "John", "age" => 25);
foreach ($person as $key => $value) {
  echo "$key : $value <br>";
}
?>
Enter fullscreen mode Exit fullscreen mode

To traverse a multi-dimensional array, you can also use a foreach loop:

<?php
$people = [
  ["nom" => "John", "age" => 25],
  ["nom" => "Doe", "age" => 30],
  ["nom" => "Jane", "age" => 28]
];
foreach ($people as $person) {
  echo $person["nom"] . " a " . $person["age"] . " ans <br>";
}
?>
Enter fullscreen mode Exit fullscreen mode

Forms

Forms are used to collect information from users. An HTML form typically contains various types of form inputs, such as text, checkboxes, radio buttons, option buttons, drop-down menus, etc.

Example of a form:

<form action="traitement.php" method="post">
  <label for="nom">Nom :</label>
  <input type="text" id="nom" name="nom">
  <label for="prenom">Prénom :</label>
  <input type="text" id="prenom" name="prenom">
  <input type="submit" value="Envoyer">
</form>
Enter fullscreen mode Exit fullscreen mode

This is a form that will send data to the "traitement.php" file using the POST method. GET and POST are the two most common methods for sending data to a PHP page.

GET: Data is sent in the URL (data is visible in the URL).
POST: Data is sent in the HTTP header (data is not visible in the URL).

To retrieve data from a form, you can use the superglobal $_POST:

<?php
$nom = $_POST["nom"]; // "nom" corresponds to the "name" attribute of the form input (in this case, it's "nom") (name="nom")
$prenom = $_POST["prenom"];
echo "Bonjour $prenom $nom!";
?>
Enter fullscreen mode Exit fullscreen mode

To retrieve data from a form using the GET method, you can use the superglobal $_GET:

<?php
$nom = $_GET["nom"];
$prenom = $_GET["prenom"];
echo "Bonjour $prenom $nom!";
// Be sure to change the form method to GET
?>
Enter fullscreen mode Exit fullscreen mode

Superglobals are built-in variables that are always available in all contexts. They are predefined in PHP. There are many superglobals, but the most commonly used ones are $_POST and $_GET. Here are some others that might be useful:

  • $_SERVER
  • $_REQUEST
  • $_SESSION
  • $_COOKIE
  • $_FILES

You can also add a condition to check if the form has been submitted:

<?php
if (isset($_POST["nom"]) && isset($_POST["prenom"]) && !empty($_POST["nom"]) && !empty($_POST["prenom"])) {
  $nom = $_POST["nom"];
  $prenom = $_POST["prenom"];
  echo "Bonjour $prenom $nom!";
}
?>
Enter fullscreen mode Exit fullscreen mode

Sessions

A session is a way to store information (in variables) for use across multiple pages. Unlike cookies, session data is not stored on the user's computer.

To start a session, you use the session_start() function:

<?php
session_start();
?>
Enter fullscreen mode Exit fullscreen mode

To store information in a session, you use the $_SESSION superglobal:

<?php
session_start();
$_SESSION["nom"] = "John";
$_SESSION["prenom"] = "Doe";
?>
Enter fullscreen mode Exit fullscreen mode

To retrieve information from a session, you also use the $_SESSION superglobal:

<?php
session_start();
echo $_SESSION["nom"]; // Outputs John
echo $_SESSION["prenom"]; // Outputs Doe
?>
Enter fullscreen mode Exit fullscreen mode

Cookies

A cookie is often used to identify a user. A cookie is a small text file stored on the user's computer. When the user accesses a web page, their name can be retrieved from the cookie.

To create a cookie, you use the setcookie() function:

<?php
setcookie("nom", "John", time() + 3600); // name, value, duration (here, 1 hour)
?>
Enter fullscreen mode Exit fullscreen mode

To retrieve a cookie, you use the $_COOKIE superglobal:

<?php
echo $_COOKIE["nom"]; // Outputs John
?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)