0% found this document useful (0 votes)
12 views

PHP_FormAndFileHandling

The document discusses PHP's variable functions, form handling, and file processing. It covers the use of superglobals like $_GET, $_POST, and $_REQUEST for managing user input, as well as the importance of data sanitation and validation. Additionally, it explains server-side includes and file handling techniques, including file modes and operations.

Uploaded by

Sharjeel Sajid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

PHP_FormAndFileHandling

The document discusses PHP's variable functions, form handling, and file processing. It covers the use of superglobals like $_GET, $_POST, and $_REQUEST for managing user input, as well as the importance of data sanitation and validation. Additionally, it explains server-side includes and file handling techniques, including file modes and operations.

Uploaded by

Sharjeel Sajid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

PHP – FORM AND FILE HANDLING

Dr. Ayesha Hakim

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

avoid unintended code execution.

• Readability: Overuse of variable functions can make code harder to follow, so

use them judiciously.


PHP Form Handling
• Form and file handling are essential components for creating interactive
applications that can accept and manage user input and handle files like
images, documents, or other media.
PHP - A Simple HTML Form

• The PHP superglobals $_GET and $_POST are used to collect form-data.

<html>
<body>

<form action="welcome.php" method="POST">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

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

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

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

• The most important thing to notice when dealing with HTML


forms and PHP is that any form element in an HTML page will
be automatically available to your PHP scripts.
• The PHP superglobals $_GET and $_POST are used to collect
form-data.
• When a user click on the submit button, the form data is sent
to a PHP file, specified in action attribute e.g., welcome.php
• The method for sending form data could be "post " or "get"
12

Form Handling - The $_POST Variable


• Collects values from HTTP POST requests
• POST request are?
o Not Visible in the URL
o Not limited in size
o However, there is an 8 Mb max size for the POST method, by default (can be changed by setting
the post_max_size in the php.ini file).
http://localhost/cs11/form.html
13

Form Handling - The $_POST Variable


http://localhost/cs11/form.html

<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 &lt; and &gt;
o This prevents attackers from exploiting the code by injecting HTML or Javascript code
(Cross-site Scripting attacks) in forms.

• The $_POST['name'] and $_POST[‘email'] variables are automatically set


for you by PHP.
15

Form Handling - The $_GET Variable


• Collects values from HTTP GET requests
• GET request are?
o Visible in URL
o Limited in size
o Bookmark-able
o not be used with values exceeding 2000 characters
• When the user clicks the "Submit" button, the URL sent to the server
could look something like:
http://localhost/cs11/welcome.php?name=%3CFahad%3E&email=fahad.satti%40seecs.edu.pk
16

Form Handling - The $_GET Variable


http://localhost/cs11/form.html

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

• It is also important to validate data. Unlike sanitization, validation does not


remove information from input data. Validation only confirms that input data
meets your expectations. If you expect an email address, make sure the input
data is an email address.
18
Form Handling
Data Sanitation - trim()
• Strip unnecessary characters (extra space, tab, newline) from the user
input data.

<?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
&lt; and &gt;. 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;

// Evaluates to true because $var is empty


if (empty($var)) {
echo '$var is either 0, empty, or not se
t at all';
}

// Evaluates as true because $var is set


if (isset($var)) {
echo '$var is set even though it is empt
y';
}
23
Form Handling
Form Validation - empty() "welcome.php”

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

<!DOCTYPE HTML> if (empty($_POST["email"])) {


$emailErr = "Email is required";
<html> } else {
<head> $email = test_input($_POST["email"]);
<style> } function test_input($data) {
.error {color: #FF0000;} $data = trim($data);
if (empty($_POST["website"])) { $data = stripslashes($data
</style> $website = "";
);
</head> } else {
$website = test_input($_POST["website"]); $data = htmlspecialchars($
<body> } data);
return $data;
<?php if (empty($_POST["comment"])) { }
$comment = "";
// define variables and set to empty v } else {
?>
alues $comment = test_input($_POST["comment"]);
$nameErr = $emailErr = $genderErr = $w }
ebsiteErr = ""; if (empty($_POST["gender"])) {
$name = $email = $gender = $comment = $genderErr = "Gender is required";
$website = ""; } else {
$gender = test_input($_POST["gender"]);
}
}

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

Server Side Includes


• You can insert the content of one PHP file into another PHP file before the server executes it.

• PHP has 2 functions for this purpose:


– include() : will only produce a warning (E_WARNING) and the script will continue

– 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.

$fp = fopen($_SERVER[‘DOCUMENT_ROOT’] . “/orders/orders.txt”, “w”);

• If no path is specified the current directory is used.


• If you are in a windows environment you must use double back
slashes.

$fp = fopen($_SERVER[‘DOCUMENT_ROOT’] . “\\orders\\orders.txt”, “w”);


34

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

Checking the file exists


• Lots of things can go wrong when you try and open a file.
o The file might not exist
o You might not have permission to view it

• The following code handles this situation:


$fp = fopen(“orders.txt”, “a”);
if (!fp)
{
print “There were problems opening the file”;
exit();
}
37

Writing and Closing


• In PHP, both fwrite() and fputs() are used to write data to a file.

<?php
// Open the file in write mode ("w")
$file = fopen("example.txt", "w");

// Check if the file was opened successfully


if ($file) {
$content = "Hello, this is a sample text to write to the file.\n";

// Write the content to the file


fwrite($file, $content);

// Close the file to save changes


fclose($file);

echo "Data written successfully!";


} else {
echo "Unable to open file.";
}
?>
38

Reading from a File


• fgets() is the most common function used - It is used to read one line at a time from a file.
• In this case below it will read until it encounters a newline character, an EOF or has read 99 bytes from the file.

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

• You can also use fread and fgetc.


39

Other useful file functions


• file_exists(path) – check whether file exists or not at the specified path
• filesize(path) – Returns the size of the specified file in bytes.
• Unlink(path) - Deletes a file from the specified path.
• Flock(path, option) – Controls access to a file by placing a lock on it.
• LOCK_SH: Reading lock
• LOCK_EX: Writing lock
• LOCK_UN: Release existing lock
40

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

// Get the current count from the file


$hits = fgets($fp, 100);
if ($hits === false) {
$hits = 0;
}

// Increment the count


$hits++; What is happening here?
// Move the pointer to the beginning of the file
rewind($fp);

// Write the updated count to the file


fwrite($fp, $hits);

// Close the file


fclose($fp);

return $hits;
}

// Call the function and display the count


$count = update_counter();
echo "Page read " . $count . " times";
?>
42

Problems using flat files


• There are a number of problems with working with
files:
o When a file gets large it can be very slow to work with.
o Searching through a file is difficult. You tend to have to read
everything in to memory.
o Concurrent access can become problematic.
o Hard to enforce levels of access to data

What is the Solution then ???


43

Safety First!
$str = strip_tags($str)

• This simply removes all HTML tags from the string supplied as the parameter
– including <SCRIPT> tags.

• crypt() will encrypt a string that you give it.


• This is especially useful for encrypting items such as passwords.
• This then cannot be reversed
• but you can encrypt another string that is entered and then compare it with the stored
encrypted string.
Terminating Execution
 There are two ways to stop the execution of a script. The first is using the exit() statement
which simply stops the script without returning anything.

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.

$connection = mysqli_connect("localhost", "username", "password", "database");


if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}

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

echo check_permission("guest"); // Outputs: Access denied


PHP DB HANDLING
Next!

47
48

USEFUL LINKS AND FURTHER


STUDY
W3 Schools - http://www.w3schools.com/php/
PHP web site - http://www.php.net/
THANK YOU

You might also like