PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development. It can be embedded into HTML to create dynamic web pages.
PHP was created by Rasmus Lerdorf in 1994. It has gone through several major versions:
You can install PHP using XAMPP or WAMP which bundles Apache, MySQL, and PHP.
Steps for Windows: 1. Download XAMPP from Apache Friends website. 2. Install and launch XAMPP Control Panel. 3. Start Apache and MySQL. 4. Place PHP files in the htdocs folder.
PHP is embedded in HTML using <?php ?>
tags.
<!DOCTYPE html> <html> <body> <h1>PHP Test</h1> <?php echo "Hello World!"; ?> </body> </html>
$name = "John"; // String $age = 25; // Integer $price = 19.99; // Float $is_admin = true; // Boolean
Variables are declared with a $
sign. Constants use define()
. Variable scope
can be local, global, or static.
define("SITE_NAME", "MySite"); $x = 5; // Global variable function testScope() { global $x; echo $x; }
Arrays are used to store multiple values in one variable.
$fruits = array("Apple", "Banana", "Orange"); echo $fruits[1]; // Outputs: Banana
PHP provides several functions for working with strings like strlen()
,
str_replace()
, and strpos()
.
$msg = "Welcome"; echo strlen($msg); // Outputs: 7 echo str_replace("Wel", "Hel", $msg); // Outputs: Helcome
PHP supports arithmetic, comparison, logical, and assignment operators.
$a = 10; $b = 5; $sum = $a + $b; echo $sum; // 15
// save as hello.php in htdocs <?php echo "PHP is working!"; ?>
To run: Open http://localhost/hello.php
in your browser.
Conditional statements in PHP allow decision-making in code based on conditions.
Executes code if the condition is true.
if (condition) { // code to execute }
Executes one block if true, another if false.
if (condition) { // true block } else { // false block }
Multiple conditions can be checked in sequence.
if (condition1) { // block 1 } elseif (condition2) { // block 2 } else { // default block }
Used to perform different actions based on different conditions.
switch (variable) { case value1: // code break; case value2: // code break; default: // default code }
Loops are used to execute the same block of code repeatedly.
while (condition) { // code to be executed }
This loop runs the block once before checking the condition.
do { // code to be executed } while (condition);
for (initialization; condition; increment) { // code to be executed }
Functions are blocks of code that perform specific tasks.
strlen(), str_replace(), strpos()
abs(), round(), pow(), sqrt()
date(), time(), strtotime()
These functions are created by the user.
function greet() { echo "Hello, World!"; } greet();
function increment($num) { $num++; }
function increment(&$num) { $num++; }
strlen($str)
– Returns the length of a string.strtoupper($str)
– Converts to uppercase.strtolower($str)
– Converts to lowercase.str_replace("old", "new", $str)
– Replaces text.abs(-5)
– Returns 5pow(2, 3)
– Returns 8sqrt(16)
– Returns 4round(4.6)
– Returns 5date("Y-m-d")
– Current date in format.time()
– Returns current Unix timestamp.strtotime("tomorrow")
– Parses English textual datetime.A web form allows users to input data and submit it to a server. Forms are created using the <form> tag.
Form data can be processed using PHP with the $_GET
or $_POST
superglobals
depending on the method used.
<?php $name = $_POST['username']; echo "Hello, " . $name; ?>
Data entered in the form fields can be captured using:
$_GET
- Retrieves data from URL parameters$_POST
- Retrieves data from the form bodyYou can pass data between pages using:
$_GET
$_POST
Click Here <?php echo $_GET['name']; ?>
Checkboxes or multiple selects allow sending multiple values.
<?php if (isset($_POST['fruits'])) { foreach ($_POST['fruits'] as $fruit) { echo $fruit . "<br>"; } } ?>
Validation ensures correct and expected input from users before processing.
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = trim($_POST["name"]); if (empty($name)) { echo "Name is required."; } else { echo "Welcome, " . htmlspecialchars($name); } } ?>
PHP supports try-catch blocks for handling exceptions gracefully.
<?php try { if (!file_exists("data.txt")) { throw new Exception("File not found!"); } } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?>
Cookies store small amounts of data on the client-side browser.
<?php setcookie("user", "John", time() + 3600); echo $_COOKIE["user"]; ?>
Sessions store user data on the server for use across multiple pages.
<?php session_start(); $_SESSION["username"] = "John"; echo $_SESSION["username"]; ?>
PHP supports a wide range of databases, including:
MySQL is the most commonly used database with PHP.
<?php phpinfo(); // Displays PHP configuration including MySQL support ?>
<?php $conn = mysqli_connect("localhost", "root", "", "mydatabase"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>
Already done during connection using "mydatabase"
. You can also use:
mysqli_select_db($conn, "mydatabase");
$sql = "CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), age INT )"; mysqli_query($conn, $sql);
$sql = "ALTER TABLE students ADD email VARCHAR(100)"; mysqli_query($conn, $sql);
$sql = "INSERT INTO students (name, age) VALUES ('John', 20)"; mysqli_query($conn, $sql);
$sql = "DELETE FROM students WHERE id=1"; mysqli_query($conn, $sql);
$sql = "UPDATE students SET age=21 WHERE name='John'"; mysqli_query($conn, $sql);
$sql = "SELECT * FROM students"; $result = mysqli_query($conn, $sql); while ($row = mysqli_fetch_assoc($result)) { echo $row["name"] . " - " . $row["age"] . "<br>"; }
Use mysqli_query()
to perform queries and mysqli_fetch_assoc()
to process
results.
$result = mysqli_query($conn, "SELECT * FROM students"); if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "Name: " . $row["name"] . ", Age: " . $row["age"] . "<br>"; } } else { echo "No records found."; }
PHP allows reusing code using require()
and include()
functions. This helps
keep your code modular and maintainable.
// file: header.php <h1>Welcome to My Site</h1> // file: index.php <?php include("header.php"); ?>
include()
gives a warning if file not found, but script continues.require()
gives a fatal error and halts the script.include("config.php"); require("database.php");
include_path: It's a directive that tells PHP where to look for included files. You can
set it in php.ini
or at runtime.
chmod
in Linux to change file permissions.$file = fopen("data.txt", "r"); fclose($file);
$file = fopen("data.txt", "r"); while (!feof($file)) { echo fgets($file); } fclose($file);
$file = fopen("data.txt", "w"); fwrite($file, "Hello World!"); fclose($file);
fopen(), fread(), fwrite(), fclose()
– Basic file operationsfile_exists(), unlink(), filesize(), is_file()
if (file_exists("data.txt")) { echo "File size: " . filesize("data.txt"); }
mkdir("mydir"); rmdir("mydir");
chdir("mydir"); echo getcwd(); // Get current working directory
To upload files in PHP:
enctype="multipart/form-data"
.$_FILES
.// HTML form <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="submit" value="Upload"> </form> // PHP handler <?php move_uploaded_file($_FILES["myfile"]["tmp_name"], "uploads/" . $_FILES["myfile"]["name"]); ?>
PHP supports OOP with the following concepts:
class Car { public $color; function setColor($c) { $this->color = $c; } function getColor() { return $this->color; } } $myCar = new Car(); $myCar->setColor("Red"); echo $myCar->getColor();