PHP

PHP (Hypertext Preprocessor) is a widely-used server-side scripting language designed specifically for web development. PHP powers a significant portion of the web, offering compatibility with various web servers, databases, and operating systems. It provides extensive support for handling HTTP requests, interacting with databases, and generating dynamic HTML content. PHP's simplicity and ease of use make it accessible to beginners while offering advanced features for experienced developers. It has a vast ecosystem of frameworks like Laravel, Symfony, and CodeIgniter that streamline web development tasks and promote best practices. PHP's widespread adoption, extensive documentation, and large community support make it a popular choice for building dynamic and database-driven web applications.

Module 1: PHP Basics

Introduction to PHP

PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

<?php

echo 'Hello, world!';

?>

PHP Syntax

A PHP script can be placed anywhere in the document. A PHP file normally contains HTML tags, and some PHP scripting code.

<?php

$color = 'red';
echo 'My car is ' . $color . '<br>';
echo 'My house is ' . $COLOR . '<br>';
echo 'My boat is ' . $coLOR . '<br>';

?>

Variables

All variables in PHP start with a $ sign, followed by the name of the variable.

<?php

$txt = 'Hello, world!';
x = 5;
$y = 10.5;

echo $txt;
echo $x + $y;

?>

Data Types

PHP supports the following data types: String, Integer, Float, Boolean, Array, Object, NULL.

<?php

$string = 'Hello, world!';
$integer = 5;
$float = 10.5;
$array = array('apple', 'banana', 'cherry');

?>

Operators

PHP divides the operators in the following groups: Arithmetic operators, Assignment operators, Comparison operators, Increment/Decrement operators, Logical operators, String operators, Array operators.

<?php

$x = 10;
$y = 6;

echo $x + $y;

?>

Module 2: PHP Functions and Control Structures

Functions

A function is a block of statements that can be used repeatedly in a program. A function will not execute immediately when a page loads. It will be executed by a call to the function.

<?php

function writeMsg() {
	echo 'Hello, world!';
}

writeMsg(); // call the function

?>

Control Structures: If Else Statements

The if statement executes some code if a condition is true. The if...else statement executes some code if a condition is true and another code if that condition is false.

<?php

$t = date('H');

if ($t < '20') {
	echo 'Have a good day!';
} else {
	echo 'Have a good night!';
}

?>

Control Structures: Switch Statements

The switch statement is used to perform different actions based on different conditions.

<?php

$favcolor = 'red';

switch ($favcolor) {
	case 'red':
		echo 'Your favorite color is red!';
		break;
	case 'blue':
		echo 'Your favorite color is blue!';
		break;
	default:
		echo 'Your favorite color is neither red, blue, nor green!';
}

?>

Control Structures: Loops

PHP supports four types of loops: for, while, do-while, and foreach.

<?php

for ($x = 0; $x <= 10; $x++) {
	echo 'The number is: $x <br>';
}

?>

Module 3: PHP Files and Exception Handling

File Handling

PHP has several functions for creating, reading, uploading, and editing files.

<?php

$file = fopen('test.txt', 'w');
fwrite($file, 'Hello, world!');
fclose($file);

?>

File Upload

With PHP, it is easy to upload files to the server.

<?php

$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES['fileToUpload']['name']);

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
	echo 'The file '. htmlspecialchars(basename($_FILES['fileToUpload']['name'])). ' has been uploaded.';
} else {
	echo 'Sorry, there was an error uploading your file.';
}

?>

Exception Handling

Exception handling is used to change the normal flow of the code execution if a specified error occurs.

<?php

function checkNum($number) {
	if($number>1) {
		throw new Exception('Value must be 1 or below');
	}
	return true;
}

try {
	checkNum(2);
	//If the exception is thrown, this text will not be shown
	echo 'If you see this, the number is 1 or below';
}

catch(Exception $e) {
	echo 'Message: ' .$e->getMessage();
}

?>

Module 4: Database Interactions in PHP

Connecting to MySQL

PHP 5 and later can work with a MySQL database using MySQLi extension.

<?php
$servername = 'localhost';
$username = 'username';
$password = 'password';

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
	die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected successfully';
$conn->close();
?>

Performing MySQL Queries

You can execute MySQL commands in PHP using the `query` method of the `mysqli` class.

<?php
$servername = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'myDB';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Perform query
$sql = 'SELECT id, firstname, lastname FROM MyGuests';
$result = $conn->query($sql);

if ($result->num_rows > 0) {
	while($row = $result->fetch_assoc()) {
		echo 'id: ' . $row['id']. ' - Name: ' . $row['firstname']. ' ' . $row['lastname']. '<br>';
	}
} else {
	echo '0 results';
}
$conn->close();

?>

Preventing SQL Injection

SQL injection is a code injection technique, used to attack data-driven applications. Prepared statements and parameterized queries can help prevent SQL injection attacks.

<?php
$servername = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'myDB';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Prepare statement
$stmt = $conn->prepare('INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)');
$stmt->bind_param('sss', $firstname, $lastname, $email);

// Set parameters and execute
$firstname = 'John';
$lastname = 'Doe';
$email = 'john@example.com';
$stmt->execute();

$stmt->close();
$conn->close();

?>

Module 5: HTTP Methods and REST API with PHP

HTTP Methods

HTTP methods like GET, POST, PUT, DELETE are fundamental concepts in web development, and PHP supports all these methods.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// The request is using the POST method
}
?>

Building a Simple REST API

A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data.

<?php
header('Content-Type: application/json');
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));

switch ($request[0]) {
	case 'users' :
		if (sizeof($request) == 1) {
			echo json_encode(getUsers());
		} else {
			echo json_encode(getUser($request[1]));
		}
		break;
	default:
		http_response_code(404);
}

function getUsers() {
	// Function to return all users
}

function getUser($id) {
	// Function to return a user by id
}
?>

Module 6: Working with Databases and Files in PHP

Connecting to a Database

PHP provides several ways to connect to a database. One of the most common ways is using MySQLi or PDO (PHP Data Objects).

<?php
$servername = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'myDB';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
	 die('Connection failed: ' . $conn->connect_error);
}
 echo 'Connected successfully';
?>

Executing SQL queries

Once a connection is established, SQL queries can be executed to interact with the database.

<?php
$sql = 'SELECT id, firstname, lastname FROM MyGuests';
$result = $conn->query($sql);

if ($result->num_rows > 0) {
	// output data of each row
	while($row = $result->fetch_assoc()) {
		echo 'id: ' . $row['id']. ' - Name: ' . $row['firstname']. ' ' . $row['lastname']. '<br>';
	}
} else {
	echo '0 results';
}
$conn->close();
?>

Handling Files

PHP has several functions for creating, reading, uploading, and editing files.

<?php
$file = fopen('test.txt', 'w');
fwrite($file, 'Hello World. Testing!');
fclose($file);

// read the file
$read = file_get_contents('test.txt');
echo $read;
?>