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

Unit 4 PHP

The document explains how to use PHP superglobals $_GET and $_POST to collect form data through HTML forms, including examples of both methods. It emphasizes the importance of form validation to protect against malicious input and discusses the differences between GET and POST methods. Additionally, it covers cookies and sessions in PHP, detailing how to create, modify, and delete cookies, as well as how to manage session variables across multiple pages.

Uploaded by

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

Unit 4 PHP

The document explains how to use PHP superglobals $_GET and $_POST to collect form data through HTML forms, including examples of both methods. It emphasizes the importance of form validation to protect against malicious input and discusses the differences between GET and POST methods. Additionally, it covers cookies and sessions in PHP, detailing how to create, modify, and delete cookies, as well as how to manage session variables across multiple pages.

Uploaded by

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

UNIT 4

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

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a
submit button:

<!DOCTYPE HTML>
<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>
</html>

Name:

E-mail:
Submit

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>

</html>

The output could be something like this:

Welcome John

Your email address is [email protected]

The same result could also be achieved using the HTTP GET method:

Example
Same example, but the method is set to GET instead of POST:

<html>

<body>

<form action="welcome_get.php" method="GET">

Name: <input type="text" name="name"><br>

E-mail: <input type="text" name="email"><br>

<input type="submit">

</form>

</body>

</html>

and "welcome_get.php" looks like this:

<html>

<body>

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

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


</body>

</html>

The code above is quite simple, and it does not include any validation.

You need to validate form data to protect your script from malicious code.

This page does not contain any form validation, it just shows how you can send
and retrieve form data.

Proper validation of form data is important to protect your form from


hackers and spammers!

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 =>
value2, key3 => value3, ...)). This array holds key/value pairs, where keys are
the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you
can access them from any function, class or file without having to do anything
special.

$_GET is an array of variables passed to the current script via the URL
parameters.

$_POST is an array of variables passed to the current script via the HTTP POST
method.

When to use GET?


Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL).

GET also has limits on the amount of information to send. The limitation is about
2000 characters.

However, because the variables are displayed in the URL, it is possible to


bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive
information!

When to use POST?


Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request) and has no
limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part


binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.

Developers prefer POST for sending form data.

PHP Form Validation


The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:

PHP Form Validation Example


* required field

Name: *

E-mail: *

Website:

Comment:
Gender: Female Male Other *

Submit

The validation rules for the form above are as follows:

Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @


and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one

First we will look at the plain HTML code for the form:

Text Fields
The name, email, and website fields are text input elements, and the comment
field is a textarea.

The HTML code looks like this:

Name: <input type="text" name="name">

E-mail: <input type="text" name="email">


Website: <input type="text" name="website">

Comment: <textarea name="comment" rows="5" cols="40"></textarea>

Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:

Gender:

<input type="radio" name="gender" value="female">Female

<input type="radio" name="gender" value="male">Male

<input type="radio" name="gender" value="other">Other

The Form Element


The HTML code of the form looks like this:

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]);?>">

When the form is submitted, the form data is sent with method="post".

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename


of the currently executing script.

So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.

What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters into 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.

Validate Form Data With PHP


The first thing we will do is to pass all variables through
PHP's htmlspecialchars() function.

When we use the htmlspecialchars() function; then if a user tries to submit


the following in a text field:

<script>location.href('http://www.hacked.com')</script>

- this would not be executed, because it would be saved as HTML escaped code,
like this:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:

1. Strip unnecessary characters (extra space, tab, newline) from the user
input data (with the PHP trim() function)
2. Remove backslashes \ from the user input data (with the
PHP stripslashes() function)

3. The next step is to create a function that will do all the checking for us
(which is much more convenient than writing the same code over and
over again).
4. We will name the function test_input().
5. Now, we can check each $_POST variable with
the test_input() function, and the script looks like this:

1. // define variables and set to empty values


2. $name = $email = $gender = $comment = $website = "";
3.
4. if ($_SERVER["REQUEST_METHOD"] == "POST") {
5. $name = test_input($_POST["name"]);
6. $email = test_input($_POST["email"]);
7. $website = test_input($_POST["website"]);
8. $comment = test_input($_POST["comment"]);
9. $gender = test_input($_POST["gender"]);
10. }
11.
12. function test_input($data) {
13. $data = trim($data);
14. $data = stripslashes($data);
15. $data = htmlspecialchars($data);
16. return $data;
17. }
Notice that at the start of the script, we check whether the form has been
submitted using $_SERVER["REQUEST_METHOD"]. If
the REQUEST_METHOD is POST, then the form has been submitted - and it should
be validated. If it has not been submitted, skip the validation and display a blank
form.

PHP - Required Fields


From the validation rules table on the previous page, we see that the "Name",
"E-mail", and "Gender" fields are required. These fields cannot be empty and
must be filled out in the HTML form.

In the following code we have added some new


variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error
variables will hold error messages for the required fields. We have also added
an if else statement for each $_POST variable. This checks if
the $_POST variable is empty (with the PHP empty() function). If it is empty, an
error message is stored in the different error variables, and if it is not empty, it
sends the user input data through the test_input() function:

// define variables and set to empty values

$nameErr = $emailErr = $genderErr = $websiteErr = "";

$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["name"])) {

$nameErr = "Name is required";

} else {

$name = test_input($_POST["name"]);

if (empty($_POST["email"])) {

$emailErr = "Email is required";


} else {

$email = test_input($_POST["email"]);

if (empty($_POST["website"])) {

$website = "";

} else {

$website = test_input($_POST["website"]);

if (empty($_POST["comment"])) {

$comment = "";

} else {

$comment = test_input($_POST["comment"]);

if (empty($_POST["gender"])) {

$genderErr = "Gender is required";

} else {

$gender = test_input($_POST["gender"]);

PHP - Display The Error Messages


Then in the HTML form, we add a little script after each required field, which
generates the correct error message if needed (that is if the user tries to submit
the form without filling out the required fields):
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">

<span class="error">* <?php echo $nameErr;?></span>

<br><br>

E-mail:

<input type="text" name="email">

<span class="error">* <?php echo $emailErr;?></span>

<br><br>

Website:

<input type="text" name="website">

<span class="error"><?php echo $websiteErr;?></span>

<br><br>

Comment: <textarea name="comment" rows="5" cols="40"></textarea>

<br><br>

Gender:

<input type="radio" name="gender" value="female">Female

<input type="radio" name="gender" value="male">Male

<input type="radio" name="gender" value="other">Other

<span class="error">* <?php echo $genderErr;?></span>

<br><br>

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

</form>
The next step is to validate the input data, that is "Does the Name field contain
only letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid URL?".

PHP - Validate Name


The code below shows a simple way to check if the name field only contains
letters, dashes, apostrophes and whitespaces. If the value of the name field is
not valid, then store an error message:

$name = test_input($_POST["name"]);

if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {

$nameErr = "Only letters and white space allowed";

The preg_match() function searches a string for pattern, returning true


if the pattern exists, and false otherwise.

PHP - Validate E-mail


The easiest and safest way to check whether an email address is well-formed is
to use PHP's filter_var() function.

In the code below, if the e-mail address is not well-formed, then store an error
message:

$email = test_input($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$emailErr = "Invalid email format";

Unit 4

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page
with a browser, it will send the cookie too. With PHP, you can both create and
retrieve cookie values.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe".
The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie
is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:

Example

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Note: The setcookie() function must appear BEFORE the <html> tag.

Note: The value of the cookie is automatically URLencoded when sending the
cookie, and automatically decoded when received (to prevent URLencoding,
use setrawcookie() instead).

Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie() function:

Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the
past:

Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

PHP Sessions
A session is a way to store information (in variables) to be used across
multiple pages.

Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?


When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session. The computer knows who you are. It knows
when you start the application and when you end. But on the internet there is
one problem: the web server does not know who you are or what you do,
because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used


across multiple pages (e.g. username, favorite color, etc). By default, session
variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available
to all pages in one application.

Tip: If you need a permanent storage, you may want to store the data in
a database.

Start a PHP Session


A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start
a new PHP session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we
will access the session information we set on the first page
("demo_session1.php").

Notice that session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning of each
page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION
variable:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Another way to show all the session variable values for a user session is to run
the following code:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

Modify a PHP Session Variable


To change a session variable, just overwrite it:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>

Destroy a PHP Session


To remove all global session variables and destroy the session,
use session_unset() and session_destroy():

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

SENDING EMAILS:

Why use PHP to send emails


PHP is a fast, reliable and flexible way to send emails from a web
server, making it the ideal solution for transactional email.

Additionally, using PHP to send emails allows you to take advantage


of the many email libraries and integrations built around it. These
libraries usually provide advanced solutions such as email
validation, spam protection and email tracking, making it easier to
manage your transactional email

PHP mail() Function


Example
Send a simple email:

<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters


$msg = wordwrap($msg,70);

// send email
mail("[email protected]","My subject",$msg);
?>

Definition and Usage


The mail() function allows you to send emails directly from a script.

Syntax
mail(to,subject,message,headers,parameters);

Parameter Values

Parameter Description

to Required. Specifies the receiver / receivers of the email

subject Required. Specifies the subject of the email. Note: This


parameter cannot contain any newline characters

message Required. Defines the message to be sent. Each line should be


separated with a LF (\n). Lines should not exceed 70
characters.
Windows note: If a full stop is found on the beginning of a
line in the message, it might be removed. To solve this
problem, replace the full stop with a double dot:
<?php
$txt = str_replace("\n.", "\n..", $txt);
?>

headers Optional. Specifies additional headers, like From, Cc, and Bcc.
The additional headers should be separated with a CRLF (\r\n).

Note: When sending an email, it must contain a From header.


This can be set with this parameter or in the php.ini file.

parameters Optional. Specifies an additional parameter to the sendmail


program (the one defined in the sendmail_path configuration
setting). (i.e. this can be used to set the envelope sender
address when using sendmail with the -f sendmail option)

Return Returns the hash value of the address parameter, or FALSE on


Value: failure. Note: Keep in mind that even if the email was accepted
for delivery, it does NOT mean the email is actually sent and
received!

You might also like