- Introduction to PHP
- Setting Up PHP
- Basic Syntax
- Variables & Echo
- Data Types In-Depth
- Working with Forms
- Basic Error Handling
- Including Files
PHP (Hypertext Preprocessor) is a server-side scripting language designed specifically for web development. It runs on the web server, generating HTML that is then sent to the client.
- Easy to learn and use
- Large community support
- Extensive framework ecosystem
- Free and open source
- Works on various platforms
- Supports multiple databases
- Built-in security features
- Browser sends request to server
- Server runs PHP interpreter
- PHP code executes and generates HTML
- Server sends HTML back to browser
- Browser displays the page
-
XAMPP Installation
- Download XAMPP from Apache Friends website
- Includes PHP, Apache, MySQL, and more
- Easy to set up and configure
-
Directory Structure
xampp/ └── htdocs/ └── your-project/ └── index.php
-
Testing PHP Installation Create a file named
info.php
:<?php phpinfo(); ?>
Access via:
http://localhost/info.php
-
php.ini Settings
- Error reporting
- Memory limits
- Upload sizes
- Time zones
-
Apache Configuration
- Document root
- Virtual hosts
- URL rewriting
- Visual Studio Code with PHP extensions
- PHP Debug tools
- Code formatters
- Composer (Package Manager)
// PHP code must be enclosed within PHP tags
<?php
// Your PHP code here
?>
// Short echo tag (if enabled)
<?= "Hello World" ?>
// Single line comment
# Alternative single line comment
/*
Multi-line
comment block
*/
$name = "John"; // Statements end with semicolon
echo $name; // Each statement on new line
if (condition) {
// Code block enclosed in curly braces
statement1;
statement2;
}
- Keywords (if, else, null, true) are NOT case-sensitive
- Variables ARE case-sensitive
- Functions are NOT case-sensitive (but use consistent casing)
$color = "red"; // Different from $Color
$COLOR = "blue"; // Different from $color
echo strtoupper("hello"); // Same as STRTOUPPER()
// Variable naming rules
$validName = "Starts with $, then letters/numbers/_";
$valid_name = "Underscores are fine";
$validName2 = "Numbers okay, but not at start";
$this_is_long = "Descriptive names are good";
// Invalid names (don't do these)
$2invalid = "Can't start with number";
$my-var = "No hyphens allowed";
$my var = "No spaces allowed";
// Different ways to output text
echo "Hello World"; // Basic output
echo "Hello", " ", "World"; // Multiple parameters
print "Hello World"; // Alternative (single parameter)
// String concatenation
$first = "Hello";
$second = "World";
echo $first . " " . $second; // Using dot operator
// Variable interpolation
$name = "John";
echo "Hello $name"; // Variables in double quotes
echo 'Hello $name'; // Single quotes don't interpolate
// Global scope
$globalVar = "I'm global";
function testScope() {
global $globalVar; // Access global variable
$localVar = "I'm local"; // Local scope
echo $globalVar; // Works with 'global'
echo $GLOBALS['globalVar']; // Alternative way
}
// String Creation
$single = 'Single quoted';
$double = "Double quoted";
$heredoc = <<<EOD
Multiple lines
of text can go
here
EOD;
// String Functions
$str = "Hello World";
strlen($str); // Length: 11
strtoupper($str); // HELLO WORLD
strtolower($str); // hello world
substr($str, 0, 5); // Hello
str_replace("World", "PHP", $str); // Hello PHP
// Integers
$int = 42;
$negative = -42;
$octal = 0755; // Octal (starts with 0)
$hex = 0xFF; // Hexadecimal
$binary = 0b1010; // Binary
// Floats
$float = 3.14;
$scientific = 2.5e3; // 2500
$scientific2 = 1E-10; // 0.0000000001
// Number Functions
is_int($int); // Check if integer
is_float($float); // Check if float
round($float); // Round number
ceil($float); // Round up
floor($float); // Round down
$isTrue = true;
$isFalse = false;
// Type Casting to Boolean
$zero = 0; // false
$one = 1; // true
$emptyString = ""; // false
$nullValue = null; // false
<!-- Basic Form Structure -->
<form action="process.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
// POST Method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
// Form validation
if (empty($username)) {
echo "Username is required";
}
}
// GET Method
if (isset($_GET['search'])) {
$searchTerm = $_GET['search'];
// Process search
}
// Sanitizing Input
$username = htmlspecialchars($_POST['username']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Validating Input
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
}
// Preventing XSS
$safeData = strip_tags($_POST['userInput']);
// Common PHP Errors
Parse Error // Syntax error in code
Fatal Error // Serious error like undefined function
Warning // Non-fatal error, script continues
Notice // Runtime notice, script continues
try {
// Code that might throw an exception
$result = divide(10, 0);
} catch (Exception $e) {
// Handle the error
echo "Error: " . $e->getMessage();
} finally {
// Always executes
echo "Process completed";
}
// Set custom error handler
function customErrorHandler($errno, $errstr, $errfile, $errline) {
echo "Error [$errno]: $errstr\n";
echo "Line $errline in $errfile\n";
}
set_error_handler("customErrorHandler");
// Error logging
error_log("Database connection failed", 0);
// Include - Warning on failure
include 'header.php'; // Warning if file not found
include_once 'config.php'; // Checks if already included
// Require - Fatal error on failure
require 'database.php'; // Fatal error if file not found
require_once 'functions.php'; // Checks if already required
// Common file structure
project/
├── includes/
│ ├── header.php
│ ├── footer.php
│ └── nav.php
├── config/
│ └── database.php
└── index.php
// Config file (config.php)
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'password');
// Using included files
<?php
require_once 'config/database.php';
include 'includes/header.php';
// Main content here
include 'includes/footer.php';