Master PHP
From Newbie to Professional
Build Your Web Development Career
Authored by William H. Simmons
Founder of A Few Bad Newbies LLC.
PHP Professional Development Course
Module 1: PHP Fundamentals
Chapter 1: Introduction to PHP
PHP (Hypertext Preprocessor) is a server-side scripting language for web development, embedded in HTML.
echo "Hello, World!";
?>
Common Mistakes
- Forgetting to close PHP tags
?>. - Missing semicolons after statements.
Practice outputting a message:
echo "Welcome to PHP!";
?>
Chapter 2: Basic Syntax and Variables
Variables in PHP start with a dollar sign ($), and code runs within tags.
$name = "Alice";
echo "Hello, $name!";
?>
Pro Tip
Use double quotes for string interpolation, single quotes for literal strings.
Practice a variable:
$greeting = "Hi!";
echo $greeting;
?>
Chapter 3: Data Types
PHP supports multiple data types without explicit declaration.
$string = "Text";
$number = 42;
$array = ["item"];
var_dump($string);
?>
Common Mistakes
- Relying on implicit type conversion.
- Not checking
nullvalues.
Practice a data type:
$num = 10;
echo $num;
?>
Module 2: Control Structures
Chapter 1: Conditional Statements
Conditionals control program flow.
$age = 20;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
?>
Pro Tip
Use === for strict equality checks.
Practice a conditional:
$score = 85;
if ($score > 80) {
echo "Pass";
}
?>
Chapter 2: Loops
Loops repeat code execution.
for ($i = 1; $i <= 3; $i++) {
echo $i;
}
?>
Common Mistakes
- Infinite loops from incorrect conditions.
- Uninitialized loop variables.
Practice a loop:
$count = 0;
while ($count < 2) {
echo "Loop";
$count++;
}
?>
Chapter 3: Functions
Functions encapsulate reusable logic.
function greet($name) {
return "Hello, $name!";
}
echo greet("Bob");
?>
Pro Tip
Use default parameters for optional arguments.
Practice a function:
function sayHi() {
echo "Hi!";
}
sayHi();
?>
Module 3: Arrays and Strings
Chapter 1: Working with Arrays
Arrays store multiple values, indexed or associative.
$colors = ["red", "blue"];
echo $colors[0];
?>
Pro Tip
Use [] for concise array creation.
Practice an array:
$items = ["item1"];
echo $items[0];
?>
Chapter 2: Array Functions
PHP provides functions for array manipulation.
$nums = [3, 1];
sort($nums);
print_r($nums);
?>
Common Mistakes
- Modifying arrays during
foreach. - Not checking key existence.
Practice an array function:
$arr = [1, 2];
array_push($arr, 3);
echo count($arr);
?>
Chapter 3: String Manipulation
Manipulate strings with built-in functions.
$str = "Hello";
echo strlen($str);
?>
Pro Tip
Use trim() for cleaning user input.
Practice string manipulation:
$text = "Hi";
echo strtoupper($text);
?>
Module 4: Forms and User Input
Chapter 1: Handling Form Data
Use $_POST or $_GET to process form data.
if (isset($_POST["name"])) {
echo $_POST["name"];
}
?>
Common Mistakes
- Not validating form inputs.
- Using
$_GETfor sensitive data.
Practice form handling:
$input = $_POST["input"] ?? "";
echo $input;
?>
Chapter 2: Form Validation
Validate inputs to ensure data integrity.
$email = $_POST["email"] ?? "";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid";
}
?>
Pro Tip
Use htmlspecialchars() to prevent XSS.
Practice validation:
$data = $_POST["data"] ?? "";
echo htmlspecialchars($data);
?>
Chapter 3: File Uploads
Handle file uploads with $_FILES.
if ($_FILES["file"]["size"] < 10000) {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload.txt");
}
?>
Common Mistakes
- Missing
enctype="multipart/form-data". - Not validating file types.
Practice file uploads:
if (isset($_FILES["file"])) {
echo "File received";
}
?>
Module 5: Database Integration
Chapter 1: MySQL Basics
Connect to MySQL using MySQLi or PDO.
$conn = new mysqli("localhost", "user", "pass", "db");
$result = $conn->query("SELECT * FROM users");
?>
Pro Tip
Prefer PDO for database portability.
Practice a query:
$conn = new mysqli("localhost", "user", "pass", "db");
$conn->query("SELECT 1");
?>
Chapter 2: CRUD Operations
Perform Create, Read, Update, Delete operations.
$pdo = new PDO("mysql:host=localhost;dbname=db", "user", "pass");
$stmt = $pdo->prepare("INSERT INTO users (name) VALUES (?)");
$stmt->execute(["Alice"]);
?>
Common Mistakes
- Not using prepared statements.
- Not closing connections.
Practice a CRUD operation:
$pdo = new PDO("mysql:host=localhost;dbname=db", "user", "pass");
$pdo->query("SELECT * FROM users");
?>
Chapter 3: Prepared Statements
Prepared statements secure queries.
$pdo = new PDO("mysql:host=localhost;dbname=db", "user", "pass");
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([1]);
?>
Pro Tip
Bind parameters for type safety.
Practice a prepared statement:
$pdo = new PDO("mysql:host=localhost;dbname=db", "user", "pass");
$stmt = $pdo->prepare("SELECT * FROM test WHERE id = ?");
$stmt->execute([1]);
?>
Module 6: Object-Oriented PHP
Chapter 1: Classes and Objects
Create classes for object-oriented programming.
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$user = new User("Bob");
?>
Pro Tip
Use private properties with getters/setters.
Practice a class:
class Test {
public $val = 1;
}
$obj = new Test();
echo $obj->val;
?>
Chapter 2: Inheritance and Interfaces
Use inheritance and interfaces for code reuse.
class Person {
public $name;
}
class Student extends Person {}
?>
Common Mistakes
- Not implementing interface methods.
- Overriding without
parent::.
Practice inheritance:
class Base {}
class Derived extends Base {}
$obj = new Derived();
?>
Chapter 3: Traits and Abstract Classes
Traits and abstract classes enhance flexibility.
trait Log {
public function log() {
echo "Log";
}
}
class App {
use Log;
}
?>
Pro Tip
Use traits for shared functionality across classes.
Practice a trait:
trait Test {
public function test() {
echo "Test";
}
}
class MyClass {
use Test;
}
$obj = new MyClass();
$obj->test();
?>
Module 7: Error Handling and Security
Chapter 1: Error Handling
Handle errors with try-catch blocks.
try {
throw new Exception("Error");
} catch (Exception $e) {
echo $e->getMessage();
}
?>
Pro Tip
Use finally for cleanup tasks.
Practice error handling:
try {
echo 1 / 0;
} catch (Exception $e) {
echo "Caught";
}
?>
Chapter 2: Security Best Practices
Secure applications against vulnerabilities.
$input = htmlspecialchars($_POST["data"] ?? "");
echo $input;
?>
Common Mistakes
- Not sanitizing user input.
- Using weak hashing methods.
Practice security:
$pass = password_hash("test", PASSWORD_DEFAULT);
echo $pass;
?>
Chapter 3: Session Management
Manage user sessions with $_SESSION.
session_start();
$_SESSION["user"] = "Alice";
echo $_SESSION["user"];
?>
Pro Tip
Use session_regenerate_id() for security.
Practice sessions:
session_start();
$_SESSION["id"] = 1;
echo $_SESSION["id"];
?>
Module 8: Working with APIs
Chapter 1: Consuming APIs
Use cURL or HTTP functions to consume APIs.
$data = file_get_contents("https://api.example.com");
echo $data;
?>
Pro Tip
Use GuzzleHTTP for robust HTTP requests.
Practice API consumption:
$json = json_decode('{"key":"value"}', true);
echo $json["key"];
?>
Chapter 2: Building REST APIs
Create RESTful APIs with PHP.
header("Content-Type: application/json");
echo json_encode(["data" => "test"]);
?>
Common Mistakes
- Not setting HTTP status codes.
- Ignoring CORS headers.
Practice building an API:
header("Content-Type: application/json");
http_response_code(200);
echo json_encode(["ok" => true]);
?>
Chapter 3: API Authentication
Secure APIs with JWT or other methods.
$token = $_SERVER["HTTP_AUTHORIZATION"] ?? "";
if ($token) {
echo "Authenticated";
}
?>
Pro Tip
Use firebase/php-jwt for JWT handling.
Practice authentication:
http_response_code(401);
echo "Unauthorized";
?>
Module 9: Modern PHP Frameworks
Chapter 1: Introduction to Frameworks
Frameworks like Laravel simplify development.
// Laravel route example
Route::get("/", function() {
return "Hello, Laravel!";
});
?>
Pro Tip
Start with Laravel for its ecosystem.
Practice a framework concept:
echo "Framework test";
?>
Chapter 2: Building with Laravel
Use Laravel’s MVC architecture.
Route::get("/users", function() {
return view("users");
});
?>
Common Mistakes
- Not configuring
.env. - Ignoring CSRF protection.
Practice a route:
Route::get("/test", function() {
return "Test";
});
?>
Chapter 3: Composer and Dependency Management
Composer manages dependencies.
require "vendor/autoload.php";
use Monolog\Logger;
$log = new Logger("app");
?>
Pro Tip
Use composer require for easy package installation.
Practice Composer:
require "vendor/autoload.php";
?>
Module 10: Testing and Deployment
Chapter 1: Unit Testing with PHPUnit
Test code with PHPUnit.
use PHPUnit\Framework\TestCase;
class Test extends TestCase {
public function testAdd() {
$this->assertEquals(2, 1 + 1);
}
}
?>
Pro Tip
Test edge cases for robust code.
Practice a test:
use PHPUnit\Framework\TestCase;
class MyTest extends TestCase {
public function testTrue() {
$this->assertTrue(true);
}
}
?>
Chapter 2: Deployment Strategies
Automate deployments with CI/CD.
name: CI
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run tests
run: vendor/bin/phpunit
Common Mistakes
- Incorrect file permissions.
- Skipping staging environments.
Practice a deployment config:
name: Test
on: [push]
jobs:
build:
runs-on: ubuntu-latest
Chapter 3: PHP Career Paths
Explore PHP career opportunities.
echo "Backend, Full-Stack, WordPress";
?>
Pro Tip
Contribute to open-source to build your portfolio.
Practice a career-related output:
echo "PHP Developer";
?>
PHP Career Paths
Complete all modules and pass the final test!