PHP pentru începători

PHP for Beginners

Ce este PHP?

PHP (Hypertext Preprocessor) este un limbaj de scripting pe server, ideal pentru aplicații web dinamice. Rulează pe server (Apache, Nginx), poate fi integrat în HTML și are o comunitate uriașă.

Caracteristici

  • Ușor de integrat cu HTML și șabloane
  • Conectivitate largă cu baze de date (MySQL, MariaDB, PostgreSQL)
  • Portabil (Linux, Windows, macOS)
  • Ecosistem bogat (Composer, framework-uri, CMS)

Unde este folosit?

CMS API E-commerce Site-uri corporate Prototipare rapidă

What is PHP?

PHP (Hypertext Preprocessor) is a server-side scripting language designed for dynamic web apps. It runs on the server, embeds into HTML, and has a huge ecosystem.

Highlights

  • HTML templating made easy
  • Broad database support (MySQL, MariaDB, PostgreSQL)
  • Portable across Linux, Windows, macOS
  • Rich ecosystem (Composer, frameworks, CMS)

Common uses

CMS API E-commerce Corporate sites Rapid prototyping

Sintaxă de bază

Blocurile PHP sunt delimitate de <?php și ?>. Statement-urile se termină cu ;.

<!DOCTYPE html>
<html>
<body>
<?php
  echo "Salut, lume!";
?>
</body>
</html>
Evitați scurta notare <?= în proiecte fără configurare clară; preferați <?php echo.

Basic Syntax

PHP blocks are delimited by <?php and ?>. Statements end with ;.

<!DOCTYPE html>
<html>
<body>
<?php
  echo "Hello, world!";
?>
</body>
</html>
Avoid short open tags unless guaranteed; prefer <?php echo.

Variabile & Tipuri

Variabilele încep cu $ și sunt dinamice. Tipuri comune: string, int, float, bool, array, object, null.

$nume   = "Ana";
$varsta = 21;
$gpa    = 9.75;
$activ  = true;
$nimic  = null;

Funcții utile: var_dump(), print_r(), gettype().

Variables & Types

Variables start with $ and are dynamically typed. Common types: string, int, float, bool, array, object, null.

$name   = "Ana";
$age    = 21;
$gpa    = 9.75;
$active = true;
$none   = null;

Handy: var_dump(), print_r(), gettype().

Tablouri (Arrays)

$fructe = ["mar","pere","banane"];
$pers   = ["nume" => "Ana", "varsta" => 21];
$lista  = array_map('strtoupper', $fructe);

Iterare: foreach; manipulare: array_map, array_filter, array_reduce.

Arrays

$fruits = ["apple","pear","banana"];
$user   = ["name" => "Ana", "age" => 21];
$upper  = array_map('strtoupper', $fruits);

Iterate with foreach; transform with array_map, array_filter, array_reduce.

Structuri de control

if ($varsta >= 18) echo "adult";
else echo "minor";

for ($i=0;$i<3;$i++) echo $i;

foreach ($fructe as $f) echo $f;

switch($role){
  case 'admin': echo "Salut, admin!"; break;
  default: echo "Salut, vizitator!";
}

Control structures

if ($age >= 18) echo "adult";
else echo "minor";

for ($i=0;$i<3;$i++) echo $i;

foreach ($fruits as $f) echo $f;

switch($role){
  case 'admin': echo "Hello, admin!"; break;
  default: echo "Hello, visitor!";
}

Funcții

function salut(string $nume): string {
  return "Salut, $nume";
}

Folosiți type hints și return types pentru claritate.

Functions

function greet(string $name): string {
  return "Hello, $name";
}

Prefer type hints & return types for clarity.

Formulare & Sesiuni

session_start();
$nume = trim($_POST['nume'] ?? '');
$_SESSION['nume'] = htmlspecialchars($nume, ENT_QUOTES, 'UTF-8');
Validați inputul, folosiți htmlspecialchars, și token CSRF pentru acțiuni sensibile.

Forms & Sessions

session_start();
$name = trim($_POST['name'] ?? '');
$_SESSION['name'] = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
Always validate input, escape output, and protect sensitive forms with CSRF tokens.

Baze de date (PDO)

$pdo = new PDO("mysql:host=localhost;dbname=ex","user","pass",[
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :e");
$stmt->execute([':e' => $email]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Preferă PDO + parametri pentru a evita SQL Injection.

Database (PDO)

$pdo = new PDO("mysql:host=localhost;dbname=app","user","pass",[
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :e");
$stmt->execute([':e' => $email]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Prefer PDO with bound params to mitigate SQL Injection.

Securitate – bune practici

  • Escapare ieșire: htmlspecialchars pentru HTML
  • Parole cu password_hash / password_verify
  • Declarații pregătite (PDO)
  • Token CSRF pentru formulare
  • Configurări display_errors=0 în producție

Security – best practices

  • Escape output with htmlspecialchars
  • Store passwords using password_hash / password_verify
  • Use prepared statements (PDO)
  • CSRF tokens on forms
  • display_errors=0 in production

Test de evaluare (9 întrebări)

Regulă bonus: La afișarea punctajului se adaugă automat +1 punct (bonus de participare).

1) Cum începe o variabilă în PHP?

2) Ce funcție afișează un text?

3) Care este metoda sigură de interogare DB?

4) Ce face htmlspecialchars?

5) Cum definești o funcție?

6) Ce funcție hash se folosește pentru parole?

7) Ce declarație iterează peste un array?

8) Cum se pornește o sesiune?

9) Ce tip returnează PDO::fetchAll(PDO::FETCH_ASSOC)?

Evaluation Quiz (9 questions)

Bonus rule: When showing the score, we automatically add +1 bonus point.

1) How does a PHP variable start?

2) Which outputs text?

3) Safe way to query DB?

4) What does htmlspecialchars do?

5) How do you define a function?

6) Which function to hash passwords?

7) Which iterates over an array?

8) How to start a session?

9) What does PDO::fetchAll(PDO::FETCH_ASSOC) return?