Unit 3 Shot Notes
Unit 3 Shot Notes
<?php
// PHP code goes here
echo "Hello, World!";
?>
<?php
$name = "John"; // String
$age = 25; // Integer
$height = 5.8; // Float
$isStudent = true; // Boolean
<?php
$score = 85;
Switch Statement:
php
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of work week";
break;
case "Friday":
echo "TGIF!";
break;
case "Saturday":
case "Sunday":
echo "Weekend!";
break;
default:
echo "Regular day";
}
?>
Looping:
For Loop:
php
<?php
// Print numbers 1 to 5
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
?>
While Loop:
php
<?php
$count = 1;
while ($count <= 3) {
echo "Count: " . $count . "<br>";
$count++;
}
?>
Foreach Loop (for arrays):
php
<?php
$fruits = array("Apple", "Banana", "Orange");
<!DOCTYPE html>
<html>
<head>
<title>PHP and HTML</title>
</head>
<body>
<h1><?php echo "Welcome to My Website"; ?></h1>
<?php
$currentTime = date("Y-m-d H:i:s");
echo "<p>Current time: " . $currentTime . "</p>";
?>
<ul>
<?php
$items = array("Home", "About", "Contact");
foreach ($items as $item) {
echo "<li>" . $item . "</li>";
}
?>
</ul>
</body>
</html>
<?php
$username = "Alice";
$loginStatus = true;
?>
<div class="header">
<?php if ($loginStatus): ?>
<p>Welcome back, <?php echo $username; ?>!</p>
<a href="logout.php">Logout</a>
<?php else: ?>
<a href="login.php">Login</a>
<?php endif; ?>
</div>
7. Arrays in PHP
Types of Arrays:
Indexed Arrays:
php
<?php
// Method 1
$colors = array("Red", "Green", "Blue");
// Method 2
$numbers = [1, 2, 3, 4, 5];
// Accessing elements
echo $colors[0]; // Output: Red
echo $numbers[2]; // Output: 3
?>
Associative Arrays:
php
<?php
$student = array(
"name" => "John Doe",
"age" => 20,
"grade" => "A",
"city" => "New York"
);
Multidimensional Arrays:
php
<?php
$students = array(
array("name" => "Alice", "grade" => "A"),
array("name" => "Bob", "grade" => "B"),
array("name" => "Charlie", "grade" => "A")
);
Array Functions:
php
<?php
$fruits = array("Apple", "Banana", "Orange");
// Add element
array_push($fruits, "Grape");
// Count elements
echo count($fruits);
8. Functions in PHP
Creating Functions:
php
<?php
// Basic function
function greet() {
echo "Hello, World!";
}
<?php
function createProfile($name, $age = 18, $city = "Unknown") {
return "Name: $name, Age: $age, City: $city";
}
Built-in Functions:
php
<?php
// String functions
$text = "Hello World";
echo strlen($text); // Length: 11
echo strtoupper($text); // HELLO WORLD
echo strtolower($text); // hello world
// Math functions
echo rand(1, 100); // Random number between 1-100
echo round(3.7); // Rounds to 4
echo max(10, 20, 5); // Returns 20
// Date functions
echo date("Y-m-d"); // Current date: 2024-01-15
echo date("H:i:s"); // Current time: 14:30:25
?>
<?php
// Get user agent string
$userAgent = $_SERVER['HTTP_USER_AGENT'];
// Detect browser
if (strpos($userAgent, 'Chrome') !== false) {
echo "You're using Chrome";
} elseif (strpos($userAgent, 'Firefox') !== false) {
echo "You're using Firefox";
} elseif (strpos($userAgent, 'Safari') !== false) {
echo "You're using Safari";
} else {
echo "Unknown browser";
}
// Get IP address
$ipAddress = $_SERVER['REMOTE_ADDR'];
echo "Your IP: " . $ipAddress;
Redirecting Users:
php
<?php
// Redirect to another page
header("Location: https://www.example.com");
exit(); // Important: stop script execution
// Conditional redirect
$userRole = "admin";
if ($userRole == "admin") {
header("Location: admin_dashboard.php");
} else {
header("Location: user_dashboard.php");
}
exit();
?>
<?php
$firstName = "John";
$lastName = "Doe";
// Concatenation
$fullName = $firstName . " " . $lastName;
echo $fullName; // John Doe
// String length
echo strlen($fullName); // 8
// Substring
echo substr($fullName, 0, 4); // John
// Replace
$message = "Hello World";
$newMessage = str_replace("World", "PHP", $message);
echo $newMessage; // Hello PHP
?>
<?php
$email = " [email protected] ";
// Clean up email
$cleanEmail = trim(strtolower($email));
echo $cleanEmail; // [email protected]
// Split string
$sentence = "PHP is awesome";
$words = explode(" ", $sentence);
print_r($words); // Array: [PHP, is, awesome]
<!DOCTYPE html>
<html>
<body>
<form method="POST" action="process_form.php">
<label>Name:</label>
<input type="text" name="username" required><br><br>
<label>Email:</label>
<input type="email" name="email" required><br><br>
<label>Age:</label>
<input type="number" name="age"><br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br><br>
<label>Hobbies:</label>
<input type="checkbox" name="hobbies[]" value="reading"> Reading
<input type="checkbox" name="hobbies[]" value="sports"> Sports
<input type="checkbox" name="hobbies[]" value="music"> Music<br><br>
<?php
// process_form.php
if ($_POST) {
// Get form data
$username = $_POST['username'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$hobbies = $_POST['hobbies']; // Array
// Validate data
if (empty($username)) {
echo "Name is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Process valid data
echo "<h2>Registration Successful!</h2>";
echo "Name: " . htmlspecialchars($username) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
echo "Age: " . $age . "<br>";
echo "Gender: " . $gender . "<br>";
if (!empty($hobbies)) {
echo "Hobbies: " . implode(", ", $hobbies);
}
}
}
?>
Form Validation:
php
<?php
function validateForm($data) {
$errors = array();
// Validate email
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
// Validate age
if ($data['age'] < 18) {
$errors[] = "Must be 18 or older";
}
return $errors;
}
if ($_POST) {
$errors = validateForm($_POST);
if (empty($errors)) {
// Process form
echo "Form submitted successfully!";
} else {
// Display errors
foreach ($errors as $error) {
echo "<p style='color: red;'>$error</p>";
}
}
}
?>
<?php
// Read entire file
$content = file_get_contents("data.txt");
echo $content;
Writing Files:
php
<?php
// Write to file (overwrites existing content)
$data = "Hello, this is new content!";
file_put_contents("output.txt", $data);
// Append to file
$newData = "\nThis is additional content.";
file_put_contents("output.txt", $newData, FILE_APPEND);
File Upload:
html
php
<?php
// Handle file upload
if (isset($_FILES['uploaded_file'])) {
$file = $_FILES['uploaded_file'];
<?php
// Set a cookie (expires in 1 hour)
setcookie("username", "john_doe", time() + 3600);
Reading Cookies:
php
<?php
// Check if cookie exists
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'];
} else {
echo "Welcome, new visitor!";
}
Deleting Cookies:
php
<?php
// Delete cookie by setting expiration to past time
setcookie("username", "", time() - 3600);
echo "Cookie deleted!";
?>
Sessions
What are Sessions?
Sessions store user data on the server. More secure than cookies because data isn't stored in the
browser.
Starting and Using Sessions:
php
<?php
// Start session (must be first line)
session_start();
<?php
session_start();
<?php
// login.php
session_start();
if ($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
<!DOCTYPE html>
<html>
<body>
<h2>Login</h2>
<?php if (isset($error)) echo "<p style='color: red;'>$error</p>"; ?>
<form method="POST">
<label>Username:</label>
<input type="text" name="username" required><br><br>
<label>Password:</label>
<input type="password" name="password" required><br><br>
<?php
// dashboard.php
session_start();
<!DOCTYPE html>
<html>
<body>
<h2>Dashboard</h2>
<p>Welcome, <?php echo $_SESSION['username']; ?>!</p>
<p>Login Time: <?php echo $_SESSION['login_time']; ?></p>
<a href="logout.php">Logout</a>
</body>
</html>
php
<?php
// logout.php
session_start();
// Redirect to login
header("Location: login.php");
exit();
?>
<?php
session_start();
$_SESSION['last_activity'] = time();
?>
Summary
This comprehensive guide covers all essential aspects of server-side development with PHP:
1. Basics: Understanding server-side vs client-side development
2. PHP Fundamentals: Syntax, variables, data types
3. Control Structures: Decision making and loops
4. Integration: Combining PHP with HTML
5. Data Handling: Arrays, functions, strings
6. User Interaction: Form processing, browser detection
7. File Operations: Reading, writing, uploading files
8. Advanced Features: Cookies and sessions for user management
Each topic includes practical examples you can try and modify. Start with the basics and gradually
work through more complex topics. Practice by building small projects like a contact form, user
registration system, or simple content management system.
Remember: PHP is a powerful language that becomes easier with practice. Don't try to memorize
everything at once—focus on understanding concepts and refer back to examples as needed!