Back-End with PHP Overview
PHP (Hypertext Preprocessor) is a powerful server-side scripting language that enables you to create dynamic web applications. Unlike HTML, CSS, and JavaScript that run in the browser, PHP runs on the server and can interact with databases, handle form submissions, manage user sessions, and generate dynamic content.
Learning Objectives
By the end of this part, you will be able to:
- Understand PHP syntax and basic programming concepts
- Process HTML forms and handle user input securely
- Work with sessions and cookies for user state management
- Connect to databases and perform CRUD operations
- Build dynamic web pages that respond to user actions
- Implement security best practices in PHP applications
PHP Basics
What is PHP?
PHP is a server-side scripting language designed for web development. It's embedded in HTML and executed on the server before the page is sent to the browser. PHP can generate dynamic content, interact with databases, handle file uploads, send emails, and much more.
PHP Syntax Basics
PHP code is enclosed in special tags and can be embedded within HTML:
Basic PHP Structure
<?php// PHP code goes here
echo "Hello, World!";
?>
Variables in PHP
<?php$name = "John";
$age = 25;
$isStudent = true;
echo "My name is " . $name;
?>
Key Points
- Variables start with $: All PHP variables must begin with a dollar sign
- Case-sensitive: Variable names are case-sensitive ($name ≠ $Name)
- String concatenation: Use the dot (.) operator to join strings
- No type declaration: PHP automatically determines variable types
Data Types
PHP supports several data types:
PHP Data Types
<?php// String
$text = "Hello";
// Integer
$number = 42;
// Float
$price = 19.99;
// Boolean
$isActive = true;
// Array
$colors = ["red", "green", "blue"];
?>
Control Structures
PHP supports common control structures like conditionals and loops:
If-Else Statement
<?php$age = 18;
if ($age >= 18) {
echo "You are an adult";
} else {
echo "You are a minor";
}
?>
For Loop
<?phpfor ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
?>
Working with Forms
Processing Form Data
PHP can receive and process data from HTML forms using the $_GET and $_POST superglobals:
HTML Form
<form method="POST" action="process.php"><input type="text" name="username" required>
<input type="email" name="email" required>
<button type="submit">Submit</button>
</form>
Processing Form (process.php)
<?phpif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = htmlspecialchars($_POST['username']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
echo "Welcome, " . $username . "!";
echo "Your email: " . $email;
}
?>
Security Best Practices
- Always validate input: Check that data exists and is in the correct format
- Sanitize data: Use functions like
htmlspecialchars()to prevent XSS attacks - Use prepared statements: When working with databases to prevent SQL injection
- Validate on server-side: Never rely solely on client-side validation
Form Validation
Always validate form data on the server side:
Form Validation Example
<?php$errors = [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'] ?? '';
// Validate email
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
// If no errors, process form
if (empty($errors)) {
// Process the form
}
}
?>
Sessions & Cookies
Working with Sessions
Sessions allow you to store user data across multiple page requests. Sessions are stored on the server and are more secure than cookies for sensitive data.
Starting and Using Sessions
<?php// Start session (must be called before any output)
session_start();
// Set session variables
$_SESSION['username'] = 'john_doe';
$_SESSION['user_id'] = 123;
// Access session variables
echo "Welcome, " . $_SESSION['username'];
// Destroy session (logout)
session_destroy();
?>
Working with Cookies
Cookies are small pieces of data stored in the user's browser. They're useful for remembering user preferences or tracking user activity.
Setting and Reading Cookies
<?php// Set a cookie (expires in 30 days)
setcookie('username', 'john_doe', time() + (86400 * 30));
// Read a cookie
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'];
}
// Delete a cookie
setcookie('username', '', time() - 3600);
?>
Database Integration
Connecting to MySQL Database
PHP can connect to MySQL databases using PDO (PHP Data Objects) or MySQLi. PDO is recommended for its security features and database abstraction.
Database Connection with PDO
<?phptry {
$pdo = new PDO(
"mysql:host=localhost;dbname=mydatabase",
"username",
"password"
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful!";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
CRUD Operations
CRUD stands for Create, Read, Update, Delete - the four basic operations for database management:
Prepared Statements (Safe Database Queries)
<?php// INSERT (Create)
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(['John Doe', 'john@example.com']);
// SELECT (Read)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// UPDATE
$stmt = $pdo->prepare("UPDATE users SET email = ? WHERE id = ?");
$stmt->execute(['newemail@example.com', 1]);
// DELETE
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute([1]);
?>
Security: Always Use Prepared Statements
- Prevent SQL Injection: Prepared statements automatically escape user input
- Better Performance: Queries are compiled once and executed multiple times
- Cleaner Code: Separates SQL logic from data
- Never use: Direct string concatenation in SQL queries with user input