Master PHP - the most popular server-side scripting language for web development
PHP (Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
To start programming in PHP, you need a web server with PHP installed. Here are the common options:
Option | Description |
---|---|
XAMPP | Apache + MySQL + PHP + Perl (Windows, Linux, macOS) |
WAMP | Windows Apache MySQL PHP |
MAMP | Mac Apache MySQL PHP |
LAMP | Linux Apache MySQL PHP |
Docker | Containerized PHP environment |
htdocs
folder with .php
extensionhttp://localhost/yourfile.php
For quick testing without installation:
<?php
phpinfo();
?>
Save this as info.php
in your web server's root directory and access it via browser.
A PHP script starts with <?php
and ends with ?>
. PHP statements end with a semicolon (;).
<!DOCTYPE html>
<html>
<body>
<?php
// PHP code goes here
echo "Hello World!";
?>
</body>
</html>
Component | Description | Example |
---|---|---|
PHP Tags | Delimit PHP code | <?php ... ?> |
Comments | Explanatory notes | // Single-line |
echo/print | Output data | echo "Hello"; |
Variables | Store data | $name = "John"; |
Functions | Reusable code blocks | function greet() { ... } |
<?php
echo "Welcome to PHP programming!<br>";
print "This is your first program.";
?>
PHP supports several primitive data types:
Data Type | Description | Example |
---|---|---|
String |
Sequence of characters | $name = "John"; |
Integer |
Whole numbers | $age = 25; |
Float |
Decimal numbers | $price = 9.99; |
Boolean |
True/False | $is_active = true; |
Array |
Collection of values | $colors = array("red", "green"); |
Object |
Instance of a class | $user = new User(); |
NULL |
No value | $var = NULL; |
Use var_dump()
or gettype()
to check variable types:
<?php
$name = "John";
$age = 25;
$price = 9.99;
$is_active = true;
var_dump($name); // string(4) "John"
echo gettype($age); // integer
?>
Variables in PHP are declared with a dollar sign $
followed by the variable name.
$variable_name = value;
<?php
$name = "John Doe"; // String
$age = 30; // Integer
$price = 19.99; // Float
$is_admin = true; // Boolean
$colors = array("red", "green", "blue"); // Array
?>
$
followed by name$name
and $Name
are different)Scope | Description | Example |
---|---|---|
Local | Only accessible within function | function test() { $x = 5; } |
Global | Accessible anywhere | $x = 5; function test() { global $x; } |
Static | Persists between function calls | function test() { static $x = 0; } |
PHP has various operators for different operations:
Operator | Description | Example |
---|---|---|
+ |
Addition | $x + $y |
- |
Subtraction | $x - $y |
* |
Multiplication | $x * $y |
/ |
Division | $x / $y |
% |
Modulus | $x % $y |
** |
Exponentiation | $x ** $y |
Operator | Description | Example |
---|---|---|
== |
Equal | $x == $y |
=== |
Identical | $x === $y |
!= |
Not equal | $x != $y |
<> |
Not equal | $x <> $y |
!== |
Not identical | $x !== $y |
> |
Greater than | $x > $y |
< |
Less than | $x < $y |
Operator | Description | Example |
---|---|---|
and |
And | $x and $y |
or |
Or | $x or $y |
xor |
Xor | $x xor $y |
&& |
And | $x && $y |
|| |
Or | $x || $y |
! |
Not | !$x |
<?php
$a = 10;
$b = 20;
echo "a + b = " . ($a + $b) . "<br>";
echo "a < b: " . ($a < $b) . "<br>";
echo "a == 10 && b == 20: " . ($a == 10 && $b == 20);
?>
Conditional statements are used to perform different actions based on different conditions.
if (condition) {
// code to execute if condition is true
}
if (condition) {
// code if true
} else {
// code if false
}
if (condition1) {
// code if condition1 true
} elseif (condition2) {
// code if condition2 true
} else {
// code if all false
}
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
<?php
$grade = "B";
if ($grade == "A") {
echo "Excellent!";
} elseif ($grade == "B") {
echo "Good!";
} else {
echo "Keep trying!";
}
// Switch example
$day = "Mon";
switch ($day) {
case "Mon":
echo "Monday";
break;
case "Tue":
echo "Tuesday";
break;
default:
echo "Other day";
}
?>
Loops are used to execute the same block of code repeatedly.
while (condition) {
// code to execute
}
do {
// code to execute
} while (condition);
for (init; condition; increment) {
// code to execute
}
foreach ($array as $value) {
// code to execute
}
// With keys
foreach ($array as $key => $value) {
// code to execute
}
<?php
// while loop
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
echo "<br>";
// for loop
for ($j = 1; $j <= 5; $j++) {
if ($j == 3) continue;
echo $j . " ";
}
echo "<br>";
// foreach loop
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color . " ";
}
?>
Functions are blocks of code that perform a specific task and can be reused.
function functionName($param1, $param2) {
// code to execute
return $value; // optional
}
functionName($arg1, $arg2);
<?php
// Function definition
function greet($name) {
return "Hello, $name!";
}
// Function call
echo greet("John");
?>
function setHeight($minheight = 50) {
// code
}
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
<?php
function sayHello() {
echo "Hello!";
}
$func = "sayHello";
$func(); // Calls sayHello()
?>
Arrays store multiple values in a single variable.
// Indexed array
$cars = array("Volvo", "BMW", "Toyota");
// Associative array
$age = array("Peter"=>"35", "Ben"=>"37");
// Short array syntax (PHP 5.4+)
$colors = ["red", "green", "blue"];
echo $cars[0]; // Volvo
echo $age["Peter"]; // 35
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[1]; // Banana
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
echo $person["name"]; // John
// Multidimensional array
$cars = [
["Volvo", 22, 18],
["BMW", 15, 13]
];
echo $cars[0][0]; // Volvo
?>
Function | Description | Example |
---|---|---|
count() |
Count elements | count($array) |
sort() |
Sort array | sort($array) |
array_push() |
Add element | array_push($array, $item) |
array_pop() |
Remove last element | array_pop($array) |
array_merge() |
Merge arrays | array_merge($arr1, $arr2) |
PHP provides many functions to manipulate strings.
$str1 = 'Hello world!'; // Single quotes
$str2 = "Hello world!"; // Double quotes
$name = "John";
echo "Hello " . $name . "!"; // Hello John!
Function | Description | Example |
---|---|---|
strlen() |
String length | strlen("Hello") |
str_word_count() |
Count words | str_word_count($str) |
strrev() |
Reverse string | strrev($str) |
strpos() |
Find substring | strpos($str, "world") |
str_replace() |
Replace text | str_replace("old", "new", $str) |
substr() |
Return part of string | substr($str, 0, 5) |
trim() |
Remove whitespace | trim($str) |
<?php
$text = " Hello World! ";
echo strlen($text) . "<br>"; // 17
echo str_word_count($text) . "<br>"; // 2
echo strrev($text) . "<br>"; // " !dlroW olleH "
echo strpos($text, "World") . "<br>"; // 9
echo trim($text) . "<br>"; // "Hello World!"
echo strtoupper($text) . "<br>"; // " HELLO WORLD! "
?>
PHP can collect form data sent with both GET and POST methods.
Method | Description |
---|---|
GET |
Data visible in URL, limited length, not secure |
POST |
Data not shown in URL, no size limit, more secure |
<!-- HTML Form -->
<form method="post" action="welcome.php">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
<?php
// welcome.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
echo "Welcome $name!<br>";
echo "Your email is $email";
}
?>
Always validate form data before processing:
<?php
$name = $email = "";
$nameErr = $emailErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
PHP has several functions for creating, reading, uploading, and editing files.
Function | Description |
---|---|
fopen() |
Opens a file |
fread() |
Reads from a file |
fwrite() |
Writes to a file |
fclose() |
Closes a file |
file_get_contents() |
Reads entire file into string |
file_put_contents() |
Writes string to file |
<?php
// Write to file
$file = fopen("test.txt", "w");
fwrite($file, "Hello World!\n");
fclose($file);
// Read from file
$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);
// Simple way to read
echo file_get_contents("test.txt");
// Simple way to write
file_put_contents("test.txt", "New content");
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file: <input type="file" name="fileToUpload">
<input type="submit" value="Upload" name="submit">
</form>
<?php
if (isset($_POST["submit"])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "File uploaded successfully";
} else {
echo "Error uploading file";
}
}
?>
PHP works well with MySQL databases using MySQLi or PDO extensions.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create table
$sql = "CREATE TABLE Users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";
if (mysqli_query($conn, $sql)) {
echo "Table created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Insert data
$sql = "INSERT INTO Users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Select data
$sql = "SELECT id, firstname, lastname FROM Users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Insert data
$stmt = $conn->prepare("INSERT INTO Users (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
echo "New records created successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
PHP supports object-oriented programming with classes and objects.
class ClassName {
// Properties
public $property;
private $privateProperty;
// Constructor
public function __construct($param) {
$this->property = $param;
}
// Methods
public function method() {
// code
}
}
$object = new ClassName("value");
<?php
class Car {
// Properties
public $brand;
public $model;
private $price;
// Constructor
public function __construct($brand, $model, $price) {
$this->brand = $brand;
$this->model = $model;
$this->price = $price;
}
// Method
public function getInfo() {
return "{$this->brand} {$this->model}";
}
// Getter
public function getPrice() {
return $this->price;
}
}
// Create object
$myCar = new Car("Toyota", "Corolla", 20000);
echo $myCar->getInfo(); // Toyota Corolla
echo $myCar->getPrice(); // 20000
?>
class ChildClass extends ParentClass {
// Additional properties and methods
}
interface InterfaceName {
public function method();
}
class ClassName implements InterfaceName {
public function method() {
// implementation
}
}
PHP provides several ways to handle errors and exceptions.
if (!file_exists("file.txt")) {
die("File not found");
} else {
$file = fopen("file.txt", "r");
}
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
set_error_handler("customError");
echo $undefinedVar; // Triggers custom error
try {
if ($value > 1) {
throw new Exception("Value must be 1 or below");
}
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage();
}
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=myDB", "user", "pass");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM Users WHERE id=?");
$stmt->execute([$_GET['id']]);
$user = $stmt->fetch();
if (!$user) {
throw new Exception("User not found");
}
} catch(PDOException $e) {
echo "Database Error: " . $e->getMessage();
} catch(Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
PHP applications should implement security best practices.
password_hash()
htmlspecialchars()
// Hashing a password
$hash = password_hash("mypassword", PASSWORD_DEFAULT);
// Verifying a password
if (password_verify("mypassword", $hash)) {
// Password correct
}
// UNSAFE
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
// SAFE with prepared statements (MySQLi)
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
// SAFE with PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->execute(['username' => $username, 'password' => $password]);
// UNSAFE
echo $_GET['user_input'];
// SAFE
echo htmlspecialchars($_GET['user_input'], ENT_QUOTES, 'UTF-8');
Follow these best practices to write clean, efficient, and maintainable PHP code.
<?php
declare(strict_types=1);
namespace App\Services;
use App\Exceptions\UserNotFoundException;
use PDO;
class UserService {
public function __construct(private PDO $db) {}
public function getUserById(int $id): array {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch();
if (!$user) {
throw new UserNotFoundException("User with ID $id not found");
}
return $user;
}
}
// Usage
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$userService = new UserService($pdo);
try {
$user = $userService->getUserById(123);
echo "User: " . htmlspecialchars($user['name']);
} catch (UserNotFoundException $e) {
echo "Error: " . $e->getMessage();
}
?>
You've completed the comprehensive PHP programming tutorial. Practice these concepts by building small projects and web applications to reinforce your learning.
Ready to take the next step? Check out our Laravel Framework tutorial to continue your PHP journey.