PHP Tutorial

Welcome to the PHP tutorial! PHP (Hypertext Preprocessor) is a popular server-side scripting language designed for web development but also used as a general-purpose programming language.

PHP Intro

PHP is widely used for creating dynamic web pages and can be embedded directly into HTML. It is known for its flexibility, simplicity, and wide support across various platforms.

PHP Install

To start using PHP, you need to install a server stack like XAMPP, WAMP, or MAMP, which includes PHP, Apache, and MySQL. Follow these steps to install:

  1. Download XAMPP from Apache Friends.
  2. Run the installer and follow the setup instructions.
  3. Start the Apache server from the XAMPP control panel.

PHP Syntax

PHP scripts are usually embedded within HTML using <?php ... ?> tags. Here’s a basic example:

php
<?php echo "Hello, World!"; ?>

PHP Comments

Comments are essential for code readability. PHP supports single-line and multi-line comments:

php
// This is a single-line comment /* This is a multi-line comment */

PHP Variables

Variables in PHP are declared with a $ sign followed by the variable name. PHP is a loosely typed language, meaning you don’t need to declare the data type.

php
$myVariable = "Hello, PHP!"; $myNumber = 42;

PHP Echo / Print

To output data to the screen, use echo or print. Both can display strings or variables.

php
echo "Hello, World!"; print $myVariable;

PHP Data Types

PHP supports several data types:

  • String
  • Integer
  • Float (double)
  • Boolean
  • Array
  • Object
  • NULL

Example:

php
$myString = "Hello"; $myInt = 5; $myFloat = 3.14; $myBool = true;

PHP Strings

Strings can be defined using single or double quotes. Double quotes allow variable parsing.

php
$name = "John"; echo "Hello, $name!"; // Outputs: Hello, John!

PHP Numbers

PHP supports both integer and floating-point numbers. You can perform mathematical operations directly.

php
$sum = 10 + 5; // 15 $product = 10 * 5; // 50

PHP Casting

You can cast variables to different types using the following methods:

php
$number = "10"; $castedNumber = (int)$number; // Cast to integer

PHP Math

PHP includes various math functions like abs(), round(), rand(), etc.

php
echo abs(-10); // Outputs: 10 echo round(3.6); // Outputs: 4 echo rand(1, 10); // Outputs a random number between 1 and 10

PHP Constants

Constants are defined using the define() function. Once set, they cannot be changed.

php
define("SITE_NAME", "My Website"); echo SITE_NAME; // Outputs: My Website

PHP Magic Constants

Magic constants provide useful information about the file, line number, etc. They are automatically populated.

php
echo __FILE__; // Outputs the current file path echo __LINE__; // Outputs the current line number

PHP Operators

PHP supports various operators including arithmetic, comparison, and logical operators.

php
$a = 5; $b = 10; echo $a + $b; // Addition echo $a == $b; // Comparison

PHP If…Else…Elseif

Conditional statements are used to execute different actions based on different conditions.

php
if ($a < $b) { echo "a is less than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is greater than b"; }

PHP Switch

The switch statement is an alternative to multiple if statements.

php
$color = "red"; switch ($color) { case "red": echo "Color is red"; break; case "blue": echo "Color is blue"; break; default: echo "Color is neither red nor blue"; }

PHP Loops

PHP supports different types of loops: for, while, and foreach.

For Loop

php
for ($i = 0; $i < 5; $i++) { echo $i; // Outputs: 01234 }

While Loop

php
$i = 0; while ($i < 5) { echo $i; $i++; }

Foreach Loop

php
$array = array(1, 2, 3); foreach ($array as $value) { echo $value; // Outputs: 123 }

PHP Functions

Functions are blocks of code that can be reused. Define a function using the function keyword.

php
function greet($name) { return "Hello, $name!"; } echo greet("Alice"); // Outputs: Hello, Alice!

PHP Arrays

Arrays can hold multiple values. They can be indexed or associative.

Indexed Array

php
$fruits = array("Apple", "Banana", "Cherry"); echo $fruits[1]; // Outputs: Banana

Associative Array

php
$person = array("name" => "John", "age" => 30); echo $person["name"]; // Outputs: John

PHP Superglobals

Superglobals are built-in variables that are always accessible, regardless of scope. Examples include $_POST, $_GET, $_SESSION, and $_COOKIE.

PHP RegEx

Regular expressions allow for pattern matching within strings. Use preg_match() for pattern matching.

php
$pattern = "/php/i"; $text = "PHP is great!"; if (preg_match($pattern, $text)) { echo "Match found!"; }

PHP Forms

Forms allow users to send data to the server. Use the <form> tag to create a form.

PHP Form Handling

Form data can be sent using GET or POST methods.

html
<form method="post" action="process.php"> Name: <input type="text" name="name"> <input type="submit" value="Submit"> </form>

PHP Form Validation

Validate form data before processing. Use empty() to check if fields are filled.

php
if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST['name']; if (empty($name)) { echo "Name is required!"; } }

PHP Form Required

Use HTML attributes like required to enforce input validation.

html
<input type="text" name="name" required>

PHP Form URL/E-mail

Use filters to validate URL and email.

php
$email = "[email protected]"; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid email!"; }

PHP Form Complete

After processing, redirect or display a confirmation message.

php
echo "Form submitted successfully!";

PHP Advanced

PHP Date and Time

Use date() to format the current date and time.

php
echo date("Y-m-d H:i:s"); // Outputs: Current date and time

PHP Include

Include external PHP files using include or require.

php
include 'header.php';

PHP File Handling

PHP provides functions to work with files, such as opening, reading, writing, and closing files.

PHP File Open/Read

Use fopen() to open a file and fread() to read its contents.

php
$file = fopen("example.txt", "r"); $content = fread($file, filesize("example.txt")); fclose($file);

PHP File Create/Write

Use fopen() with the write mode to create and write to a file.

php
$file = fopen("example.txt", "w"); fwrite($file, "Hello, World!"); fclose($file);

PHP File Upload

Use the <input type="file"> tag to create a file upload form.

html
<form action="upload.php" method="post" enctype="multipart/form-data"> Select file to upload: <input type="file" name="fileToUpload"> <input type="submit" value="Upload"> </form>

PHP Cookies

Set cookies using setcookie().

php
setcookie("user", "John Doe", time() + (86400 * 30)); // 86400 = 1 day

PHP Sessions

Use sessions to store user data across multiple pages.

php
session_start(); $_SESSION["username"] = "JohnDoe";

PHP Filters

Use filter_var() to sanitize input data.

php
$sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);

PHP Filters Advanced

Use filter functions to validate and sanitize various data types.

PHP Callback Functions

Define a callback function and pass it to another function.

php
function myFunction($callback) { $callback(); } myFunction(function() { echo "Hello, Callback!"; });

PHP JSON

Use json_encode() and json_decode() for JSON data manipulation.

php
$data = array("name" => "John", "age" => 30); $jsonData = json_encode($data);

PHP Exceptions

Use try...catch blocks to handle exceptions.

php
try { throw new Exception("An error occurred"); } catch (Exception $e) { echo $e->getMessage(); }

PHP OOP

PHP What is OOP

Object-Oriented Programming (OOP) allows you to structure your code in objects that can encapsulate data and behavior.

PHP Classes/Objects

Define a class and create objects.

php
class Car { public $color; public function __construct($color) { $this->color = $color; } } $myCar = new Car("red");

PHP Constructor

A constructor initializes objects when they are created.

php
class Person { public $name; public function __construct($name) { $this->name = $name; } }

PHP Destructor

A destructor is called when an object is destroyed.

php
class MyClass { function __destruct() { echo "Object destroyed."; } }

PHP Access Modifiers

Access modifiers define the visibility of properties and methods: public, private, and protected.

PHP Inheritance

Inheritance allows a class to use methods and properties from another class.

php
class Vehicle { public function drive() { echo "Driving"; } } class Car extends Vehicle { public function honk() { echo "Beep!"; } }

PHP Constants

Define class constants using the const keyword.

php
class MyClass { const MY_CONSTANT = "Constant Value"; }

PHP Abstract Classes

Abstract classes cannot be instantiated and must be extended by other classes.

php
abstract class Animal { abstract protected function makeSound(); }

PHP Interfaces

Interfaces define methods that must be implemented by classes that implement the interface.

php
interface Animal { public function makeSound(); } class Dog implements Animal { public function makeSound() { echo "Woof!"; } }

PHP Traits

Traits allow code reuse in single inheritance languages.

php
trait MyTrait { public function hello() { echo "Hello!"; } } class MyClass { use MyTrait; }

PHP Static Methods

Static methods can be called without creating an instance of the class.

php
class MyClass { public static function staticMethod() { echo "Static method called!"; } } MyClass::staticMethod();

PHP Static Properties

Static properties belong to the class rather than instances.

php
class MyClass { public static $staticVar = "Static Variable"; }

PHP Namespaces

Namespaces prevent name conflicts in larger applications.

php
namespace MyNamespace; class MyClass { public function display() { echo "Hello from MyNamespace!"; } }

PHP Iterables

An iterable is a special type that can be looped over with foreach.

php
function getIterable() { return [1, 2, 3]; } foreach (getIterable() as $value) { echo $value; }

MySQL Database

MySQL Connect

Connect to a MySQL database using mysqli_connect().

php
$conn = mysqli_connect("localhost", "username", "password", "database");

MySQL Create DB

Create a new database using CREATE DATABASE.

php
$sql = "CREATE DATABASE myDB"; mysqli_query($conn, $sql);

MySQL Create Table

Create a new table using CREATE TABLE.

php
$sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL )"; mysqli_query($conn, $sql);

MySQL Insert Data

Insert data into a table using INSERT INTO.

php
$sql = "INSERT INTO MyGuests (firstname, lastname) VALUES ('John', 'Doe')"; mysqli_query($conn, $sql);

MySQL Get Last ID

Get the last inserted ID using mysqli_insert_id().

php
$last_id = mysqli_insert_id($conn);

MySQL Insert Multiple

Insert multiple records at once.

php
$sql = "INSERT INTO MyGuests (firstname, lastname) VALUES ('Alice', 'Smith'), ('Bob', 'Brown')"; mysqli_query($conn, $sql);

MySQL Prepared

Use prepared statements for secure data handling.

php
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname) VALUES (?, ?)"); $stmt->bind_param("ss", $firstname, $lastname); $firstname = "John"; $lastname = "Doe"; $stmt->execute();

MySQL Select Data

Select data from a table using SELECT.

php
$sql = "SELECT * FROM MyGuests"; $result = mysqli_query($conn, $sql); while ($row = mysqli_fetch_assoc($result)) { echo $row['firstname']; }

MySQL Where

Filter results with the WHERE clause.

php
$sql = "SELECT * FROM MyGuests WHERE firstname='John'";

MySQL Order By

Order results using ORDER BY.

php
$sql = "SELECT * FROM MyGuests ORDER BY lastname ASC";

MySQL Delete Data

Delete records using DELETE.

php
$sql = "DELETE FROM MyGuests WHERE id=3"; mysqli_query($conn, $sql);

MySQL Update Data

Update existing records using UPDATE.

php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=1"; mysqli_query($conn, $sql);

MySQL Limit Data

Limit the number of results returned.

php
$sql = "SELECT * FROM MyGuests LIMIT 5";

PHP XML

PHP XML Parsers

PHP offers various ways to parse XML, including SimpleXML and DOM.

PHP SimpleXML Parser

SimpleXML is a simple way to work with XML data.

php
$xml = simplexml_load_file("data.xml"); echo $xml->name;

PHP SimpleXML – Get

Extract data from a SimpleXML object.

php
foreach ($xml->item as $item) { echo $item->title; }

PHP XML Expat

Use the XML Expat parser for event-driven parsing.

php
function startElement($parser, $name) { echo "Start: $name\n"; } $parser = xml_parser_create(); xml_set_element_handler($parser, "startElement", null); xml_parse($parser, $xmlData); xml_parser_free($parser);

PHP XML DOM

Use the DOM extension to manipulate XML documents.

php
$dom = new DOMDocument(); $dom->load("data.xml"); echo $dom->getElementsByTagName("name")->item(0)->nodeValue;

PHP – AJAX

AJAX Intro

AJAX (Asynchronous JavaScript and XML) allows you to update parts of a web page without reloading the whole page.

AJAX PHP

AJAX can send requests to PHP scripts.

javascript
$.ajax({ url: 'process.php', type: 'POST', data: { name: 'John' }, success: function(response) { $('#result').html(response); } });

AJAX Database

You can use AJAX to interact with a database via PHP.

AJAX XML

AJAX can also work with XML data.

AJAX Live Search

Create a live search feature using AJAX.

javascript
$('#search').keyup(function() { $.ajax({ url: 'search.php', type: 'GET', data: { query: $(this).val() }, success: function(data) { $('#results').html(data); } }); });

Reference

PHP