1. PHP Basics
PHP is embedded within HTML using <?php … ?> tags, making it very flexible for mixing PHP with other web technologies like HTML, CSS, and JavaScript.
Basic PHP Script
<?php
echo "Hello, World!";
?>
Key Points:
- PHP Code Blocks: PHP code is wrapped within <?php ?> or <?php echo ?>.
- Echo Statement: echo is used to output text or variables to the browser.
- Case Sensitivity: PHP keywords are case-insensitive (echo, ECHO both work), but variables are case-sensitive.
Basic Syntax and Structure:
- Statements End with Semicolons: Every PHP statement must end with a semicolon (;).
- PHP Comments: You can add comments with // (single line) or /* … */ (multi-line).
// This is a single-line comment
/* This is a
multi-line comment */
2. PHP Data Types
PHP supports a wide range of data types, including primitive and complex types.
Primitive Data Types:
Data Type |
Description |
Example |
int |
Integer numbers |
$age = 25; |
float |
Floating point numbers |
$price = 19.99; |
string |
Sequence of characters |
$name = “PHP”; |
bool |
Boolean (True/False) |
$is_valid = true; |
null |
Represents a variable with no value |
$var = null; |
Complex Data Types:
Data Type |
Description |
Example |
array |
A collection of values |
$arr = [1, 2, 3]; |
object |
An instance of a class |
$obj = new MyClass(); |
resource |
Special type representing external resources |
e.g., database connections |
3.Variables and Constants
Variables in PHP are dynamic, meaning you don’t need to declare their type explicitly. Variables are prefixed with $ and can store any data type.
Variable Declaration:
$name = "John"; // String variable
$age = 30; // Integer variable
$price = 19.99; // Float variable
$is_valid = true; // Boolean variable
Variable Scope:
Variables can have different scopes:
- Local Variables: Declared inside a function and used only within that function.
- Global Variables: Declared outside a function and can be accessed from anywhere in the script using the global keyword.
- Static Variables: Retain their value even after the function execution ends.
Constants:
Constants in PHP are defined using the define() function or using const.
define("PI", 3.14159); // Using define()
const MAX_VALUE = 100; // Using const
- Constants are case-sensitive by default, but you can make them case-insensitive: define(“MAX_SPEED”, 120, true);.
4. Operators in PHP
PHP offers a wide range of operators, including arithmetic, comparison, logical, assignment, and more.
Arithmetic Operators:
Operator |
Description |
Example |
+ |
Addition |
$a + $b |
– |
Subtraction |
$a – $b |
* |
Multiplication |
$a * $b |
/ |
Division |
$a / $b |
% |
Modulus |
$a % $b |
Comparison Operators:
Operator |
Description |
Example |
== |
Equal to |
$a == $b |
!= |
Not equal to |
$a != $b |
=== |
Identical (same value and type) |
$a === $b |
!== |
Not identical |
$a !== $b |
> |
Greater than |
$a > $b |
< |
Less than |
$a < $b |
Logical Operators:
Operator |
Description |
Example |
&& |
Logical AND |
$a && $b |
` |
|
` |
! |
Logical NOT |
!$a |
Assignment Operators:
Operator |
Description |
Example |
= |
Assign value |
$a = $b; |
+= |
Add and assign |
$a += $b; |
-= |
Subtract and assign |
$a -= $b; |
*= |
Multiply and assign |
$a *= $b; |
/= |
Divide and assign |
$a /= $b; |
Increment/Decrement Operators:
Operator |
Description |
Example |
++$a |
Pre-increment (increment before use) |
++$a |
$a++ |
Post-increment (increment after use) |
$a++ |
–$a |
Pre-decrement (decrement before use) |
–$a |
$a– |
Post-decrement (decrement after use) |
$a– |
5. PHP Strings
PHP has a rich set of functions for manipulating strings.
String Declaration:
$greeting = "Hello, World!";
Common String Functions:
Function |
Description |
Example Usage |
strlen() |
Returns the length of the string |
strlen($greeting) |
strtoupper() |
Converts string to uppercase |
strtoupper($greeting) |
strtolower() |
Converts string to lowercase |
strtolower($greeting) |
strpos() |
Finds the position of a substring |
strpos($greeting, “World”) |
str_replace() |
Replaces all occurrences of a substring |
str_replace(“World”, “PHP”, $greeting) |
substr() |
Returns a substring |
substr($greeting, 0, 5) |
trim() |
Removes whitespace from both ends |
trim(” Hello “) |
String Concatenation:
PHP uses the dot (.) operator for concatenation.
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: John Doe
6. Arrays
Arrays in PHP are used to store multiple values in a single variable. PHP supports both indexed and associative arrays.
Indexed Arrays:
$fruits = array("Apple", "Banana", "Orange");
Associative Arrays:
$ages = array("John" => 25, "Jane" => 30, "Mark" => 35);
Multidimensional Arrays:
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
Array Functions:
Function |
Description |
Example Usage |
count() |
Returns the number of elements in an array |
count($fruits) |
array_merge() |
Merges two or more arrays |
array_merge($arr1, $arr2) |
array_push() |
Adds elements to the end of an array |
array_push($fruits, “Grape”) |
array_pop() |
Removes the last element from an array |
array_pop($fruits) |
in_array() |
Checks if a value exists in an array |
in_array(“Banana”, $fruits) |
array_keys() |
Returns all keys of an array |
array_keys($ages) |
array_values() |
Returns all values of an array |
array_values($ages) |
Accessing Array Elements:
echo $fruits[0]; // Outputs: Apple
echo $ages['John']; // Outputs: 25
7. Control Structures
PHP supports the standard control structures found in most programming languages, such as conditional statements and loops.
If-Else Statement:
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
Switch Case:
$day = "Monday";
switch ($day) {
case "Monday":
echo "It's Monday!";
break;
case "Friday":
echo "It's Friday!";
break;
default:
echo "Another day!";
}
Ternary Operator:
$is_valid = ($age >= 18) ? true : false;
8. Loops
Loops in PHP allow repetitive execution of code blocks.
For Loop:
for ($i = 0; $i < 5; $i++) {
echo $i;
}
While Loop:
$i = 0;
while ($i < 5) {
echo $i;
$i++;
}
Do-While Loop:
$i = 0;
do {
echo $i;
$i++;
} while ($i < 5);
Foreach Loop:
The foreach loop is specifically designed for iterating over arrays.
$fruits = array("Apple", "Banana", "Orange");
foreach ($fruits as $fruit) {
echo $fruit;
}
9. Functions in PHP
Functions allow code reuse and modularity.
Defining and Calling Functions:
function greet($name) {
echo "Hello, $name!";
}
greet("John"); // Outputs: Hello, John!
Return Statement:
function add($a, $b) {
return $a + $b;
}
$sum = add(5, 3); // $sum is 8
Default Parameters:
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Outputs: Hello, Guest!
Variable-Length Argument Lists:
You can pass an arbitrary number of arguments to a function using the … operator.
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // Outputs: 10
10. Object-Oriented Programming (OOP)
PHP supports OOP concepts like classes, objects, inheritance, and polymorphism.
Classes and Objects:
A class is a blueprint for creating objects.
class Dog {
public $name;
public function bark() {
echo "Woof!";
}
}
// Creating an object
$myDog = new Dog();
$myDog->name = "Buddy";
$myDog->bark(); // Outputs: Woof!
Constructors:
A constructor is a special method that is automatically called when an object is created.
class Car {
public $make;
public function __construct($make) {
$this->make = $make;
}
}
$myCar = new Car("Toyota");
echo $myCar->make; // Outputs: Toyota
Inheritance:
Inheritance allows a class to inherit properties and methods from another class.
class Animal {
public function makeSound() {
echo "Some generic sound";
}
}
class Cat extends Animal {
public function makeSound() {
echo "Meow!";
}
}
$cat = new Cat();
$cat->makeSound(); // Outputs: Meow!
Access Modifiers:
- Public: Can be accessed from anywhere.
- Protected: Can be accessed within the class and by classes derived from that class.
- Private: Can be accessed only within the class that declares them.
class Person {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
class Shape {
public function draw() {
echo "Drawing a shape";
}
}
class Circle extends Shape {
public function draw() {
echo "Drawing a circle";
}
}
$shape = new Circle();
$shape->draw(); // Outputs: Drawing a circle
Static Methods and Properties:
Static properties and methods belong to the class, not objects. They are accessed using the class name.
class MathHelper {
public static $pi = 3.14159;
public static function add($a, $b) {
return $a + $b;
}
}
echo MathHelper::$pi; // Outputs: 3.14159
echo MathHelper::add(2, 3); // Outputs: 5
11. Superglobals
PHP provides several built-in
superglobal arrays that are always accessible.
Superglobal |
Description |
$_GET |
Contains data from the query string of a URL |
$_POST |
Contains data from an HTML form submitted via POST |
$_REQUEST |
Contains data from both GET and POST methods |
$_SESSION |
Contains session variables |
$_COOKIE |
Contains cookie values |
$_SERVER |
Contains server and execution environment information |
$_FILES |
Contains file upload information |
$_ENV |
Contains environment variables |
Using $_GET:
// URL: example.com/page.php?name=John
$name = $_GET['name'];
echo $name; // Outputs: John
Using $_POST:
// HTML Form:
<form method="post" action="submit.php">
<input type="text" name="username">
<input type="submit">
</form>
<?php
// In submit.php
$username = $_POST['username'];
echo $username;
?>
Using $_SESSION:
Sessions store user data across multiple page requests.
session_start();
$_SESSION['user'] = "John Doe";
echo $_SESSION['user']; // Outputs: John Doe
Using $_COOKIE:
Cookies store small amounts of data on the user’s machine.
setcookie("username", "John", time() + 3600); // Cookie expires in 1 hour
echo $_COOKIE['username']; // Outputs: John
12. File Handling
PHP provides functions for reading, writing, and manipulating files.
Reading a File:
$filename = "file.txt";
$content = file_get_contents($filename);
echo $content;
Writing to a File:
$file = fopen("file.txt", "w");
fwrite($file, "Hello, File!");
fclose($file);
Checking if a File Exists:
if (file_exists("file.txt")) {
echo "File exists!";
}
File Uploading:
PHP makes file uploading simple using the $_FILES superglobal.
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit">
</form>
<?php
if ($_FILES["myfile"]["error"] == 0) {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["myfile"]["name"]);
move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetFile);
echo "File uploaded successfully!";
}
?>
13. Error Handling
Error handling in PHP is done using the try-catch block.
Try-Catch Block:
try {
if ($age < 18) {
throw new Exception("Age must be 18 or older.");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Custom Error Handler:
You can define a custom error handler using set_error_handler().
function customError($errno, $errstr) {
echo "Error: [$errno] $errstr";
}
set_error_handler("customError");
echo 10 / 0; // Triggers an error
14. Working with Databases
PHP provides extensions like
PDO and
MySQLi to work with databases.
Connecting to MySQL (MySQLi):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Querying the Database:
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["id"] . " - " . $row["name"];
}
} else {
echo "0 results";
}
Prepared Statements (PDO):
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$stmt = $conn->prepare("SELECT name FROM users WHERE id = ?");
$stmt->execute([1]);
$user = $stmt->fetch();
echo $user['name'];
15. PHP Sessions and Cookies
Session Management:
session_start(); // Start the session
$_SESSION['username'] = "John"; // Store session data
echo $_SESSION['username']; // Access session data
Cookies Management:
setcookie("username", "John", time() + (86400 * 30), "/"); // Set a cookie
echo $_COOKIE['username']; // Access the cookie
16. Regular Expressions in PHP
Regular expressions are patterns used for string matching.
Functions for Regular Expressions:
- preg_match(): Searches a string for a pattern.
- preg_replace(): Replaces occurrences of a pattern in a string.
$pattern = "/^hello/i";
$string = "Hello, World!";
if (preg_match($pattern, $string)) {
echo "Pattern found!";
}
17. PHP Date and Time
PHP provides a robust set of functions for handling dates and times.
Getting Current Date/Time:
echo date("Y-m-d H:i:s"); // Outputs current date and time
Formatting Dates:
echo date("l, F j, Y"); // Outputs: Monday, October 10, 2024
Timestamp Functions:
$timestamp = strtotime("next Monday");
echo date("Y-m-d", $timestamp); // Outputs the date of next Monday
18. PHP Best Practices
Follow Naming Conventions:
- Use meaningful variable and function names.
- Use camelCase for variables and functions, PascalCase for class names, and ALL_CAPS for constants.
Secure Input Validation:
- Sanitize and validate user input using functions like filter_var() to prevent security risks such as SQL injection and XSS attacks.
Error Reporting:
- Use error_reporting(E_ALL) during development to display all types of errors.
- In production, log errors instead of displaying them using ini_set(“log_errors”, 1) and error_log().
Use Prepared Statements:
- Always use prepared statements to avoid SQL injection attacks.
Avoid Global Variables:
- Avoid using global variables as they can lead to unmanageable code. Use functions, classes, or namespaces instead.
Use Composer:
- Use Composer for managing dependencies in your PHP projects.
Optimize Performance:
- Cache expensive operations such as database queries.
- Use object-oriented programming for better code reusability and maintenance.
19. Conclusion
PHP is a powerful and flexible server-side language that is widely used in web development due to its ease of integration with HTML, support for databases, and the ability to handle dynamic content efficiently. This comprehensive has covered the fundamental and advanced aspects of PHP, including syntax, data types, variables, control structures, functions, object-oriented programming, file handling, error handling, sessions, and more.
As PHP continues to evolve, adopting new features and best practices will ensure your PHP applications remain secure, maintainable, and high-performing. Whether you’re building a small website or a large-scale web application, PHP provides the tools you need to succeed. Happy coding!