PHP_FormAndFileHandling
PHP_FormAndFileHandling
1
Variable Functions
• Variable functions allow you to call a function by using a variable that holds
the function’s name.
• This is a powerful feature for creating dynamic, flexible, and clean code.
Code:
<?php
function greet() {
echo "Hello, World!";
}
$functionName = 'greet'; // Store function name in a variable
$functionName(); // Call function using the variable
?>
Use Cases for Variable Functions
1. Dynamic Callbacks: Useful when the function to be executed varies based
on conditions or user input.
2. Reducing Repetition: Allows you to reuse code without manually calling
each function.
Important Considerations
• Security: Validate function names when they are derived from user input to
• The PHP superglobals $_GET and $_POST are used to collect form-data.
<html>
<body>
</body>
6
</html>
PHP - A Simple HTML Form
• When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.
• To display the submitted data, you could simply echo all the variables.
• The "welcome.php" looks like this:
<html>
<body>
</body>
7
</html>
Super-Globals: $GLOBALS
• $GLOBALS is a PHP super global variable which is used to access global variables
from anywhere in the PHP script (also from within functions or methods).
• PHP stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable.
<?php
$x = 75;
$y = 25;
function add() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; // Access $x and $y using
$GLOBALS
}
add();
echo $z . "<br>"; // Outputs: 100
print_r($GLOBALS);
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>
PHP $_SERVER Superglobals
• $_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
<?php
echo "PHP: " . $_SERVER['PHP_SELF'] . "<br>";
echo "Server Name: " . $_SERVER['SERVER_NAME'] . "<br>";
echo "HTTP Host: " . $_SERVER['HTTP_HOST'] . "<br>";
echo "Browser: " . $_SERVER['HTTP_USER_AGENT'] . "<br>";
echo "Script Name: " . $_SERVER['SCRIPT_NAME'] . "<br>";
?>
PHP FORM HANDLING
10
11
Form Handling
<html>
<body>
<form action="welcome.php" method="POST">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" placeholder="Enter your <html>
full name here"><br> <body>
<label for="email">Email:</label><br> Welcome <?php echo htmlspecialchars($_POST["name"]); ?>
<input type="text" id="email" name="email" <br>
placeholder="[email protected]"><br><br> Your email address is: <?php echo $_POST["email"]; ?>
<input type="submit" value="Submit"> </body>
</form>
</html>
</form>
</body>
</html>
PHP Forms - $_POST Function
• htmlspecialchars() makes sure any characters that are special in html are
properly encoded so people can't inject HTML tags or Javascript into your
page.
o This means that it will replace HTML characters like < and > with < and >
o This prevents attackers from exploiting the code by injecting HTML or Javascript code
(Cross-site Scripting attacks) in forms.
<html>
<body>
<form action="welcome.php" method=“GET">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" placeholder="Enter your <html>
full name here"><br> <body>
<label for="email">Email:</label><br> Welcome <?php echo htmlspecialchars($_GET["name"]); ?>
<input type="text" id="email" name="email" <br>
placeholder="[email protected]"><br><br> Your email address is: <?php echo $_GET["email"]; ?>
<input type="submit" value="Submit"> </body>
</form>
</html>
</form>
</body>
</html>
PHP $_REQUEST Superglobals
• PHP $_REQUEST is used to collect data after submitting an HTML form.
Form Handling
Sanitize, Validate, and Escape
• Never trust any data that originates from a source not under your direct
control.
• When you sanitize input, you escape or remove unsafe characters. It’s
important to sanitize input data before it reaches your application’s storage
layer (e.g., MySQL). This is your first line of defense.
<?php
$sanitizeddata = trim($data);
?>
19
Form Handling
Data Sanitation - stripslashes()
•Remove backslashes (\) from the user input data.
<?php
$sanitizeddata = stripslashes($data);
?>
20
Form Handling
Data Sanitation - htmlspecialchars()
• The htmlspecialchars() function converts special characters to HTML
entities. This means that it will replace HTML characters like < and > with
< and >. This prevents attackers from exploiting the code by injecting
HTML or Javascript code (Cross‐site Scripting attacks) in forms.
<?php
$sanitizeddata = htmlspecialchars($data);
?>
21
Form Handling
Data Sanitation - Example
<?php
function sanitizeInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data); return $data;
}
?>
22
Form Handling
Form Validation - empty()
• Determine whether a variable is empty.
• Other Situations: Use isset() to determine if a variable is set and is not NULL, and use is_null() to
finds whether a variable is NULL
<?php
$var = 0;
<?php
<html> // define variables and set to empty values
<body> $nameErr = $emailErr = "";
<form action="welcome.php" method="post"> $name = $email = "";
Name: <input type="text" name="name"><b
r> if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
E-
$nameErr = "Name is required";
mail: <input type="text" name="email">< } else {
br> $name = test_input($_POST["name"]);
<input type="submit"> }
</form>
</body> if (empty($_POST["email"])) {
</html> $emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
24
Form Handling
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
Form Validation - empty() }
25
<br><br>
Form Handling
Comment: <textarea name="comment" rows="5"
cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="fe
Form Validation - empty() male">Female
<input type="radio" name="gender" value="ma
le">Male
<h2>PHP Form Validation Example</h2> <input type="radio" name="gender" value="ot
<p><span class="error">* required field</ her">Other
span></p> <span class="error">* <?
<form method="post" action="<? php echo $genderErr;?></span>
php echo htmlspecialchars($_SERVER["PHP_SELF" <br><br>
]);?>"> <input type="submit" name="submit" value="S
Name: <input type="text" name="name"> ubmit">
<span class="error">* <?php echo $nameErr;? </form>
></span>
<br><br> <?php
E-mail: <input type="text" name="email"> echo "<h2>Your Input:</h2>";
<span class="error">* <? echo $name;
php echo $emailErr;?></span> echo "<br>";
<br><br> echo $email;
Website: <input type="text" name="website"> echo "<br>";
<span class="error"><? echo $website;
php echo $websiteErr;?></span> echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
26
27
PHP
SERVER SIDE INCLUDES
28
– require() : will produce a fatal error (E_COMPILE_ERROR) and stop the script
• These two functions are used to include PHP files that can be reused on multiple pages.
include 'filename’;
or
require 'filename';
Server Side Includes
include() Function
• The include() function takes all the content in a specified file and includes it in the current file.
• If an error occurs, the include() function generates a warning, but the script will continue
execution.
<!DOCTYPE html>
<html>
<head>
<title>PHP: Include Function</title>
</head>
<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
29
Server Side Includes
require() Function
• The require() function is identical to include(), except that it handles errors
differently.
• If an error occurs, the require() generates a fatal error, and the script will stop.
<!DOCTYPE html>
<html>
<head>
<title>PHP: Include Function</title>
</head>
<body>
<?php require("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
30
PHP FILE HANDLING
31
32
File Processing
• There are 3 steps to using data in a file:
1. Open the file. If the file doesn’t already exist create it or catch the error gracefully.
2. Write/Read data from the file.
3. Close the file.
• To open a file in PHP use the fopen() function.
• We supply it with a filename, but we also need to set the file mode
that tells how we intend to use it.
33
fopen()
• fopen expects 2 parameters – the location of the file and the file
mode.
File Modes
r Read mode, does not create file if it does not exist
r+ Reading and writing, does not create file if it does not exist
w OverWrite mode – if the file already exists delete it and create a new one
w+ Overwrite and reading mode– if the file already exists delete it and create a new
one
a Append mode
a+ Appending and reading
x Creates a new file for writing only
x+ Creates a new file for reading and writing only
b Binary mode (e.g., "rb" or "wb+"); prevents character translation.
c Opens a file for write-only access, does not truncate (clear) the file content, create file if it
does not exist
c+ Opens a file for read and write access, does not truncate (clear) the file content, create file if
it does not exist
35
File Modes
(Summary)
36
<?php
// Open the file in write mode ("w")
$file = fopen("example.txt", "w");
<?php
// Open the file in read mode
$file = fopen("example.txt", "r");
if ($file) {
// Loop until the end of the file
while (!feof($file)) {
// Read each line
$line = fgets($file);
echo $line . "<br>";
} feof is a really useful
function when dealing with
// Close the file after reading
fclose($file);
files – here we check we
} else { are not at the end of the file
echo "Unable to open file.";
}
?>
Simplified readfile()
• Read a file and write its content to the output buffer
<!DOCTYPE html>
<html>
<body>
<?php
echo readfile("dictionary_mini.txt");
?>
</body>
</html>
41
Example
<?php
function update_counter()
{
// Attempt to open the file in create/read/write mode without truncation
$fp = fopen("orders.txt", ”r+");
return $hits;
}
Safety First!
$str = strip_tags($str)
• This simply removes all HTML tags from the string supplied as the parameter
– including <SCRIPT> tags.
if ($user_is_not_logged_in) {
exit("Access denied: You must be logged in to view this page.");
}
// The rest of the code will not execute if the exit condition is met
Terminating Execution
More useful – especially for bug checking – is the die() command.
// If connection fails, it will output the error message and stop the script
Terminating Execution
The return statement is used to end the execution of a function and return
control to the calling context. It is not technically for terminating the entire script,
but it can be used to stop the execution within functions.
function check_permission($user_role) {
if ($user_role != "admin") {
return "Access denied"; // End function and return message
}
// Code for admin access only
return "Access granted";
}
47
48