Introduction to PHP
PHP Basics
Functions in PHP
Working with Forms
Working with Files
Working with Databases
Advanced PHP Techniques

PHP Tutorial

Introduction PHP language

PHP (Hypertext Preprocessor) is a popular general-purpose scripting language that is especially suited to web development. It was originally created by Rasmus Lerdorf in 1994 and has since evolved into a robust and feature-rich language used on millions of websites worldwide.

History and Evolution

  1. PHP/FI (1994): The initial version, known as PHP/FI (Personal Home Page / Forms Interpreter), was a set of Common Gateway Interface (CGI) binaries written in the C programming language.

  2. PHP 3 (1997): This version was the first to gain widespread popularity. It introduced the ability to work with databases, support for more complex data structures, and was the first version to be used as a module within web servers.

  3. PHP 4 (2000): Introduced the Zend Engine, which improved performance and added many features, including session management and output buffering.

  4. PHP 5 (2004): Introduced significant improvements, such as enhanced object-oriented programming (OOP) capabilities, the PHP Data Objects (PDO) extension, and better XML support.

  5. PHP 7 (2015): Marked a significant performance improvement, introduced scalar type declarations, return type declarations, and null coalescing operator. PHP 6 was skipped due to development issues.

  6. PHP 8 (2020): Introduced the Just-In-Time (JIT) compilation, union types, attributes (annotations for metadata), and match expressions.

Features of PHP

  • Server-Side Scripting: PHP scripts are executed on the server, generating HTML which is then sent to the client.
  • Cross-Platform: PHP runs on various platforms, including Windows, Linux, Unix, and macOS.
  • Easy to Learn: PHP has a syntax that is easy for beginners to pick up, especially those with experience in other programming languages.
  • Open Source: PHP is free to use and distribute.
  • Database Integration: PHP has strong support for various databases, including MySQL, PostgreSQL, SQLite, and more.
  • Rich Ecosystem: PHP has a large number of libraries, frameworks (like Laravel and Symfony), and tools that enhance its functionality.
  • Community Support: PHP has a large and active community, offering extensive documentation, tutorials, and forums.
php Tutorial

PHP Syntax and Basics

PHP Tags: PHP code is embedded within HTML using special tags.

				
					<?php
// PHP code goes here
?>

				
			

Short tags can also be used but are less common:

				
					<?=
// Short echo tag
?>


				
			

Basic Syntax: PHP statements end with a semicolon ;.

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



				
			

Comments: Comments are lines in the code that are not executed

				
					<?php
// This is a single-line comment
# This is another single-line comment
/*
   This is a multi-line comment
*/
?>



				
			

Variables and Data Types

Variables: Declared using the $ sign..

				
					<?php
$variableName = "value";
?>

?>



				
			

Data Types:

String: Sequence of characters.

				
					$string = "Hello, World!";


				
			

Integer: Whole numbers.

				
					$integer = 123;



				
			

Float: Decimal numbers

				
					$float = 3.14;




				
			

Boolean: true or false.

				
					$boolean = true;




				
			

Array: Collection of values.

				
					$array = array("apple", "banana", "cherry");





				
			

Object: Instances of classes

				
					class Car {
    function Car() {
        $this->model = "VW";
    }
}
$herbie = new Car();




				
			

NULL: Variable with no value.

				
					$nullValue = NULL;




				
			

Conditional Statements:

if-else:

				
					<?php
$num = 10;
if ($num > 0) {
    echo "$num is positive";
} else {
    echo "$num is not positive";
}
?>

				
			

switch:

				
					<?php
$color = "red";
switch ($color) {
    case "red":
        echo "Color is red";
        break;
    case "blue":
        echo "Color is blue";
        break;
    default:
        echo "Color is not red or blue";
}
?>

				
			

Loops:

for:

				
					<?php
for ($i = 0; $i < 5; $i++) {
    echo "The number is $i <br>";
}
?>

				
			

while:

				
					<?php
$i = 0;
while ($i < 5) {
    echo "The number is $i <br>";
    $i++;
}
?>

				
			

do-while:

				
					<?php
$i = 0;
do {
    echo "The number is $i <br>";
    $i++;
} while ($i < 5);
?>

				
			

foreach (for arrays):

				
					<?php
$fruits = array("apple", "banana", "cherry");
foreach ($fruits as $fruit) {
    echo "The fruit is $fruit <br>";
}
?>

				
			

Functions

Defining Functions:

				
					<?php
function sayHello() {
    echo "Hello, World!";
}
sayHello();
?>

				
			

Function Arguments:

				
					<?php
function greet($name) {
    echo "Hello, $name!";
}
greet("Alice");
?>

				
			

Returning Values:

				
					<?php
function add($a, $b) {
    return $a + $b;
}
echo add(2, 3); // Outputs: 5
?>


				
			

Working with Forms

HTML Forms:

				
					<form action="process.php" method="post">
    Name: <input type="text" name="name"><br>
    Age: <input type="text" name="age"><br>
    <input type="submit">
</form>



				
			

Processing Form Data:

				
					<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo "Name: $name, Age: $age";
?>



				
			

Working with Databases (MySQL Example)

Connecting to a Database:

				
					<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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



				
			

Performing a Query

				
					<?php
$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();
?>

				
			

Advanced Concepts

Object-Oriented Programming (OOP):

Classes and Objects:
				
					<?php
class Car {
    public $color;
    public $model;
    public function __construct($color, $model) {
        $this->color = $color;
        $this->model = $model;
    }
    public function message() {
        return "My car is a " . $this->color . " " . $this->model . ".";
    }
}

$myCar = new Car("black", "Volvo");
echo $myCar->message();
?>

				
			

Error and Exception Handling:

				
					<?php
function divide($dividend, $divisor) {
    if ($divisor == 0) {
        throw new Exception("Division by zero");
    }
    return $dividend / $divisor;
}

try {
    echo divide(5, 0);
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage

				
			

PHP and Web Services

Working with APIs (cURL Example)

				
					<?php
$url = "https://api.example.com/data";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>

				
			

PHP and Web Services

Laravel Example:

Installation:

				
					composer create-project --prefer-dist laravel/laravel blog

				
			

Basic Routing:

				
					// routes/web.php
Route::get('/', function () {
    return view('welcome');
});

				
			

Controller Example:

				
					// app/Http/Controllers/HelloController.php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class HelloController extends Controller
{
    public function index() {
        return "Hello, World!";
    }
}

// routes/web.php
Route::get('/hello', [HelloController::class, 'index']);

				
			

PHP is a versatile and powerful scripting language that continues to be a dominant force in web development. Its ease of use, extensive documentation, and active community support make it an excellent choice for both beginners and experienced developers. Whether you’re building simple websites or complex web applications, PHP provides the tools and functionality needed to bring your projects to life

Scroll to Top