0% found this document useful (0 votes)
6 views23 pages

Unit 3 Shot Notes

The document provides a comprehensive guide to server-side development using PHP, covering its definition, functions, and advantages. It includes detailed sections on PHP syntax, data types, decision making, loops, and integration with HTML, as well as advanced topics like form processing, file operations, and cookies/sessions. Each section is supplemented with code examples to illustrate key concepts and functionalities.

Uploaded by

geekyone23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views23 pages

Unit 3 Shot Notes

The document provides a comprehensive guide to server-side development using PHP, covering its definition, functions, and advantages. It includes detailed sections on PHP syntax, data types, decision making, loops, and integration with HTML, as well as advanced topics like form processing, file operations, and cookies/sessions. Each section is supplemented with code examples to illustrate key concepts and functionalities.

Uploaded by

geekyone23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Complete Guide to Server-Side Development with PHP

1. Introduction to Server-Side Development


What is Server-Side Development?
Server-side development refers to programming that happens on the web server (the computer that
hosts websites) rather than in the user's web browser. When you visit a website:
1. Client-Side: Your browser (Chrome, Firefox, etc.) handles HTML, CSS, and JavaScript
2. Server-Side: The web server processes requests, accesses databases, and generates dynamic
content
Example: When you log into Facebook:
Client-side: The login form you see
Server-side: Checking your username/password against the database
Why Server-Side Development?
Security: Sensitive operations (like database access) happen on the server
Dynamic Content: Generate different content for different users
Data Processing: Handle form submissions, file uploads, etc.
Database Integration: Store and retrieve information
2. A Web Server's Responsibilities
Primary Functions:
1. Request Handling: Receive HTTP requests from browsers
2. File Serving: Send HTML, CSS, images, and other files
3. Script Execution: Run server-side scripts (PHP, Python, etc.)
4. Database Communication: Connect to databases for data operations
5. Response Generation: Create and send responses back to browsers
How It Works:
User types URL → Browser sends request → Server processes → Server sends response →
Browser displays page

3. Quick Tour of PHP


What is PHP?
PHP: PHP: Hypertext Preprocessor (recursive acronym)
Purpose: Server-side scripting language
Features: Easy to learn, widely used, great for web development
Famous Sites: Facebook, Wikipedia, WordPress
Why Choose PHP?
Free and open-source
Easy syntax
Large community support
Works well with databases (especially MySQL)
Cross-platform (Windows, Linux, Mac)
4. Introduction and Basic Syntax of PHP
Basic Structure:
php

<?php
// PHP code goes here
echo "Hello, World!";
?>

Key Syntax Rules:


All PHP code starts with <?php and ends with ?>
Every statement ends with a semicolon ( ; )
Variables start with $ symbol
Comments use // for single line or /* */ for multiple lines
Variables:
php

<?php
$name = "John"; // String
$age = 25; // Integer
$height = 5.8; // Float
$isStudent = true; // Boolean

echo "Name: " . $name; // Concatenation with dot (.)


?>
Data Types:
String: Text data ( "Hello" )
Integer: Whole numbers ( 42 )
Float: Decimal numbers ( 3.14 )
Boolean: True/False values
Array: Collection of values
Object: Complex data structures
5. Decision Making and Looping
Decision Making (if-else):
php

<?php
$score = 85;

if ($score >= 90) {


echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
?>

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");

foreach ($fruits as $fruit) {


echo "I like " . $fruit . "<br>";
}
?>

6. PHP and HTML Integration


Embedding PHP in HTML:
php

<!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>

Dynamic Content Example:


php

<?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"
);

echo $student["name"]; // Output: John Doe


echo $student["age"]; // Output: 20
?>

Multidimensional Arrays:
php

<?php
$students = array(
array("name" => "Alice", "grade" => "A"),
array("name" => "Bob", "grade" => "B"),
array("name" => "Charlie", "grade" => "A")
);

echo $students[0]["name"]; // Output: Alice


echo $students[1]["grade"]; // Output: B
?>

Array Functions:
php

<?php
$fruits = array("Apple", "Banana", "Orange");

// Add element
array_push($fruits, "Grape");

// Remove last element


array_pop($fruits);

// Count elements
echo count($fruits);

// Check if value exists


if (in_array("Apple", $fruits)) {
echo "Apple found!";
}
?>

8. Functions in PHP
Creating Functions:
php

<?php
// Basic function
function greet() {
echo "Hello, World!";
}

// Call the function


greet();

// Function with parameters


function greetUser($name) {
echo "Hello, " . $name . "!";
}

greetUser("Alice"); // Output: Hello, Alice!

// Function with return value


function addNumbers($a, $b) {
return $a + $b;
}

$result = addNumbers(5, 3);


echo $result; // Output: 8
?>

Function with Default Parameters:


php

<?php
function createProfile($name, $age = 18, $city = "Unknown") {
return "Name: $name, Age: $age, City: $city";
}

echo createProfile("John"); // Uses default age and city


echo createProfile("Alice", 25); // Uses default city
echo createProfile("Bob", 30, "NYC"); // Uses all provided values
?>

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
?>

9. Browser Control and Detection


Detecting Browser Information:
php

<?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;

// Get current page URL


$currentURL = $_SERVER['REQUEST_URI'];
echo "Current page: " . $currentURL;
?>

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

10. String Manipulation


Basic String Operations:
php

<?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
?>

Advanced String Functions:


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]

// Join array into string


$newSentence = implode("-", $words);
echo $newSentence; // PHP-is-awesome

// Check if string contains substring


if (strpos($sentence, "PHP") !== false) {
echo "Contains PHP";
}
?>

11. Form Processing


HTML Form:
html

<!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>

<input type="submit" value="Submit">


</form>
</body>
</html>

PHP Form Processing:


php

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

// Check required fields


if (empty($data['username'])) {
$errors[] = "Username is required";
}

// 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>";
}
}
}
?>

12. File Operations


Reading Files:
php

<?php
// Read entire file
$content = file_get_contents("data.txt");
echo $content;

// Read file line by line


$file = fopen("data.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
}

// Check if file exists


if (file_exists("data.txt")) {
echo "File exists";
} else {
echo "File not found";
}
?>

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);

// Write using fopen


$file = fopen("log.txt", "a"); // 'a' for append
if ($file) {
fwrite($file, date("Y-m-d H:i:s") . " - User logged in\n");
fclose($file);
}
?>

File Upload:
html

<!-- HTML Form for file upload -->


<form method="POST" enctype="multipart/form-data">
<input type="file" name="uploaded_file">
<input type="submit" value="Upload">
</form>

php

<?php
// Handle file upload
if (isset($_FILES['uploaded_file'])) {
$file = $_FILES['uploaded_file'];

// Check for errors


if ($file['error'] === 0) {
$fileName = $file['name'];
$fileSize = $file['size'];
$fileTmp = $file['tmp_name'];

// Set upload directory


$uploadDir = "uploads/";
$uploadPath = $uploadDir . $fileName;

// Move uploaded file


if (move_uploaded_file($fileTmp, $uploadPath)) {
echo "File uploaded successfully!";
} else {
echo "Upload failed!";
}
} else {
echo "Error uploading file!";
}
}
?>

13. Advanced Features: Cookies and Sessions


Cookies
What are Cookies?
Cookies are small pieces of data stored in the user's browser. They remember information about the
user between visits.
Setting Cookies:
php

<?php
// Set a cookie (expires in 1 hour)
setcookie("username", "john_doe", time() + 3600);

// Set cookie with path and domain


setcookie("user_pref", "dark_mode", time() + (30 * 24 * 3600), "/", "example.com");

// Cookie must be set before any HTML output


?>
<!DOCTYPE html>
<html>
<body>
<h1>Cookie has been set!</h1>
</body>
</html>

Reading Cookies:
php

<?php
// Check if cookie exists
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'];
} else {
echo "Welcome, new visitor!";
}

// Display all cookies


echo "<h3>All Cookies:</h3>";
foreach ($_COOKIE as $name => $value) {
echo "$name: $value<br>";
}
?>

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();

// Set session variables


$_SESSION['username'] = 'alice';
$_SESSION['user_id'] = 123;
$_SESSION['login_time'] = date('Y-m-d H:i:s');

echo "Session started and variables set!";


?>

Accessing Session Data:


php

<?php
session_start();

// Check if user is logged in


if (isset($_SESSION['username'])) {
echo "Welcome, " . $_SESSION['username'];
echo "<br>User ID: " . $_SESSION['user_id'];
echo "<br>Login Time: " . $_SESSION['login_time'];
} else {
echo "Please log in first!";
}
?>

Complete Login System Example:


php

<?php
// login.php
session_start();

if ($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];

// Simple authentication (in real app, check database)


if ($username == 'admin' && $password == 'password123') {
$_SESSION['username'] = $username;
$_SESSION['login_time'] = date('Y-m-d H:i:s');
header("Location: dashboard.php");
exit();
} else {
$error = "Invalid login credentials!";
}
}
?>

<!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>

<input type="submit" value="Login">


</form>
</body>
</html>
php

<?php
// dashboard.php
session_start();

// Check if user is logged in


if (!isset($_SESSION['username'])) {
header("Location: login.php");
exit();
}
?>

<!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();

// Destroy all session data


session_destroy();

// Redirect to login
header("Location: login.php");
exit();
?>

Session Security Best Practices:


php

<?php
session_start();

// Regenerate session ID for security


session_regenerate_id(true);

// Set session timeout (30 minutes)


if (isset($_SESSION['last_activity']) &&
(time() - $_SESSION['last_activity'] > 1800)) {
session_destroy();
header("Location: login.php");
exit();
}

$_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!

You might also like