PHP Overview
Understanding server-side scripting with PHP
🐘 What is PHP?
PHP (Hypertext Preprocessor) is a popular server-side scripting language designed for web development. It runs on the server and generates dynamic HTML content for browsers.
<?php
// This is a simple PHP example
echo "Hello, World!";
?>
Output:
Hello, World!
Key PHP Features
Server-Side
PHP runs on the web server
<?php
echo "Processed on server";
?>
Free & Open
PHP is completely free to use
<?php
// No license fees!
phpinfo();
?>
Database Support
Works with MySQL, PostgreSQL, etc.
<?php
$conn = mysqli_connect();
?>
Cross-Platform
Runs on Windows, Linux, Mac
<?php
echo PHP_OS;
?>
🔹 PHP Syntax Basics
PHP code is embedded in HTML and starts with <?php and ends with ?>. The server processes PHP code and sends HTML to the browser.
<!DOCTYPE html>
<html>
<body>
<h1>My First PHP Page</h1>
<?php
echo "Hello, PHP!";
?>
</body>
</html>
Output:
My First PHP Page
Hello, PHP!
🔹 Variables in PHP
Variables in PHP start with the $ symbol. PHP is loosely typed, meaning you don't need to declare variable types explicitly.
<?php
// Variables start with $
$name = "John";
$age = 25;
$price = 19.99;
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Price: $" . $price;
?>
Output:
Name: John
Age: 25
Price: $19.99
🔹 PHP Comments
Comments help document your code and are ignored by the PHP interpreter. Use single-line or multi-line comments to explain your logic.
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multi-line comment
It can span multiple lines
*/
echo "Comments are ignored!";
?>
Output:
Comments are ignored!
🔹 PHP Data Types
PHP supports various data types including strings, integers, floats, booleans, arrays, and objects. The var_dump() function shows variable type and value.
<?php
$text = "Hello"; // String
$number = 42; // Integer
$decimal = 3.14; // Float
$isTrue = true; // Boolean
$colors = array("red"); // Array
var_dump($text);
var_dump($number);
var_dump($isTrue);
?>
Output:
string(5) "Hello"
int(42)
bool(true)
🔹 PHP Functions
Functions are reusable blocks of code that perform specific tasks. Define functions with the function keyword and call them by name.
<?php
// Define a function
function greet($name) {
return "Hello, " . $name . "!";
}
// Call the function
echo greet("Alice");
echo "<br>";
echo greet("Bob");
?>
Output:
Hello, Alice!
Hello, Bob!