0% found this document useful (0 votes)
4 views9 pages

PHP Functions and State Management Guide

This document provides an overview of functions in PHP, including defining, calling, and returning values, as well as passing by value versus passing by reference. It also covers variable scope, the mail function, PHP error levels, and state management techniques such as GET and POST methods, cookies, and sessions. Additionally, it includes examples and best practices for handling forms and managing application state in PHP.

Uploaded by

KANAK THUKRAL
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)
4 views9 pages

PHP Functions and State Management Guide

This document provides an overview of functions in PHP, including defining, calling, and returning values, as well as passing by value versus passing by reference. It also covers variable scope, the mail function, PHP error levels, and state management techniques such as GET and POST methods, cookies, and sessions. Additionally, it includes examples and best practices for handling forms and managing application state in PHP.

Uploaded by

KANAK THUKRAL
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

UNIT -2

Functions in PHP 🛠️
Functions are fundamental to structured programming, allowing developers to encapsulate
specific tasks into reusable blocks of code.

1. Defining, Calling, and Returning Values

Concept Syntax & Explanation Detailed Example

Basic Definition Functions are defined using php function


the function keyword. calculateArea($width,
Parameters are listed inside $height) { $area = $width *
the parentheses (). $height; return $area; }

Calling Executing the function by php $result =


name, passing the required calculateArea(10, 5); //
arguments. $result holds 50 echo "The
area is: " . $result;

Type Hinting (PHP 7+) Modern PHP allows you to php function add(int $a, int
specify the expected data $b): int { return $a + $b; } //
type for arguments and PHP ensures $a and $b are
the function's return value treated as integers, and the
for better code reliability. result is an integer.

2. Passing by Value vs. Passing by Reference

This concept determines whether a function operates on a copy of a variable or the original
variable itself.

Method Mechanism PHP Implementation &


Example

Pass by Value (Default) The function creates a php function


separate, local copy of the applyDiscount($price) {
variable. The original $price = $price - 10; // Only
variable in the global scope the copy is changed echo
remains untouched. "Inside function:
$price<br>"; } $cost = 100;
applyDiscount($cost); echo
"Outside function: $cost";
// Output: 100

Pass by Reference The argument is preceded php function


by an ampersand (&amp;) applyTax(&$amount) {
in the function definition. $amount = $amount * 1.05;
The function operates // The original variable is
directly on the memory changed } $bill = 200;
address of the original applyTax($bill); echo "Final
variable. Bill: " . round($bill, 2); //
Output: 210.00

3. Variable Scope

Scope Definition Access Rule Example

Local Declared within a Only exists and is php function


function. accessible inside logMessage() {
that function. $message =
"Function ran."; } //
echo $message; //
Undefined variable
error

Global Declared outside To be accessed or php $counter = 0;


any function. modified inside a function
function, it must be increment() { global
declared using the $counter;
global keyword. $counter++; }
increment(); //
$counter is now 1

Static Declared within a The variable retains php function


function using the its last value trackCalls() { static
static keyword. between multiple $count = 0;
calls to the same $count++; echo
function. $count . " "; }
trackCalls(); // 1
trackCalls(); // 2

4. Mail Function

The mail() function sends email from the server. It requires a correctly configured MTA (Mail
Transfer Agent) like Sendmail on the host system to work. It's often replaced by libraries (like
PHPMailer) in modern development for reliability.

Example (Simplified):

PHP

<?php​
$recipient = "support@[Link]";​
$subject_line = "New Inquiry from Website";​
$user_message = "I need assistance with my account.";​
$from_header = "From: user_email@[Link]" . "\r\n" .​
"Reply-To: user_email@[Link]";​

$success = mail($recipient, $subject_line, $user_message, $from_header);​

if ($success) {​
echo "Message sent.";​
} else {​
// Note: Failure often indicates a server configuration issue.​
echo "Message failed to send.";​
}​
?>​

PHP Errors 🚨
Understanding PHP error levels is crucial for development and securing production
environments.

Error Level Description Impact Handling Strategy


(Constant)

E_ERROR (Fatal) A critical runtime Stops the script Must be resolved;


error that is execution cannot be
unrecoverable (e.g., immediately. gracefully handled
trying to instantiate within the script
a non-existent (except via
class). shutdown
functions).

E_WARNING A non-fatal runtime Script continues Should be


(Warning) error (e.g., trying to to run, but a addressed, but
include a file that warning message is won't crash the
doesn't exist). displayed/logged. application.

E_NOTICE (Notice) A minor warning Script continues Best practice is to


(e.g., accessing an to run. Indicates eliminate all notices
undefined variable). potential issues or for clean code.
poor coding
practice.

E_PARSE A syntax error Script never The code must be


(Compile-time) detected by the starts execution. fixed before the
parser (e.g., a interpreter can run
missing semicolon it.
or curly brace).

Error Control Strategy:


1.​ Development: Set error_reporting(E_ALL); and ini_set('display_errors', 1); to see all errors
and notices.
2.​ Production: Set ini_set('display_errors', 0); to hide errors from users (security) and
ini_set('log_errors', 1); to write errors to a secure log file.

Working with Forms and State Management 🌐


1. GET and POST Methods

Feature GET Method POST Method

Data Transfer Data is sent in the URL's Data is sent in the body of
Query String. the HTTP request.

Visibility Data is visible in the Data is not visible in the


browser history and logs. URL.

Limits Limited by URL length No practical limits;


(typically 2048 characters). supports large data and file
uploads.

PHP Superglobal \$_GET \$_POST

Idempotency Idempotent (safe to Non-Idempotent


repeat/bookmark). (repeating a request might
have side effects, e.g.,
double purchase).
HTML/PHP Example:

PHP

<?php​
// Check for submission method​
if ($_SERVER["REQUEST_METHOD"] == "POST") {​
$username = htmlspecialchars($_POST['username']);​
echo "POST data received for user: " . $username;​
}​
// ... or use $_GET for URL parameters​
?>​
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">​
<input type="text" name="username">​
<input type="submit" value="Login">​
</form>​

2. State Management Overview

Since HTTP is stateless, managing the application state (information about the current user
or application context) requires specific techniques.

Method Storage Location PHP Access Array Primary Use Case

Cookies Client Browser \$_COOKIE Storing user


(Text File) preferences,
tracking, or
"Remember Me"
features.

Sessions Server (Temporary \$_SESSION Maintaining user


File) login status,
shopping carts, or
sensitive data.
Query String URL \$_GET Passing minimal,
non-sensitive data
between pages
(e.g., product IDs).

Hidden Field HTML Form \$_POST or \$_GET Passing


(Submitted via non-user-editable
POST/GET) data from one form
to the next step.

3. Cookies in Detail

Cookies are set via the Set-Cookie header sent by the server.

Setting and Unsetting:

PHP

<?php​
// Set a cookie: Name, Value, Expiry Time (seconds from now), Path, Domain, Security​
$expiry = time() + (86400 * 30); // 30 days​
setcookie("theme", "dark", $expiry, "/");​

// To unset/delete a cookie, set its expiration time to the past​
setcookie("theme", "", time() - 3600); ​
?>​

Accessing:

PHP

<?php​
// Always check if the cookie is set before accessing it​
if (isset($_COOKIE['theme'])) {​
echo "User theme preference: " . $_COOKIE['theme'];​
}​
?>​

4. Sessions in Detail

Sessions are the preferred method for managing sensitive user data. PHP automatically
handles the Session ID (PHPSESSID) creation and transmission (usually via a cookie).

Process Flow:
1.​ session_start(); is called.
2.​ PHP checks for an existing Session ID.
3.​ If no ID is found, PHP generates a new ID and sends it to the client (browser).
4.​ PHP loads the corresponding session data file from the server.
5.​ All data is stored and retrieved using the \$_SESSION superglobal array.

Example (Login State):

PHP

<?php​
session_start(); // Start the session at the top of the script​

// Setting a session variable upon successful login​
$_SESSION['user_id'] = 123;​
$_SESSION['role'] = 'Admin';​
$_SESSION['last_activity'] = time();​

// Retrieving and checking​
if (isset($_SESSION['user_id'])) {​
echo "Logged in as User ID: " . $_SESSION['user_id'];​
}​
?>​
5. Query String and Hidden Fields for State Transfer

These methods transfer data directly between pages without reliance on the server or client
storage.

Query String Example:


When a user clicks a link: <a href="[Link]?product_id=52&source=home">View
Product</a>
●​ On [Link], you access: \$productID = \$_GET['product_id'];

Hidden Field Example:


Used within multi-page forms to carry data from step 1 to step 2.

HTML

<form method="post" action="[Link]">​


<input type="text" name="name" value="User Name">​
<input type="hidden" name="name" value="User Name"> ​
<input type="submit" value="Next Step">​
</form>​

●​ On [Link], you access the forwarded data via \$_POST['name'].

You might also like