0% found this document useful (0 votes)
48 views22 pages

Unit - Iii PHP (DS & Stat)

This document outlines the syllabus for Unit III, focusing on working with forms, cookies, and user sessions in PHP. It covers creating and handling forms, combining HTML and PHP, using hidden fields, redirecting users, sending emails, file uploads, and managing cookies and sessions. Each section includes code examples and explanations for practical implementation.

Uploaded by

Divya Gurram
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)
48 views22 pages

Unit - Iii PHP (DS & Stat)

This document outlines the syllabus for Unit III, focusing on working with forms, cookies, and user sessions in PHP. It covers creating and handling forms, combining HTML and PHP, using hidden fields, redirecting users, sending emails, file uploads, and managing cookies and sessions. Each section includes code examples and explanations for practical implementation.

Uploaded by

Divya Gurram
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/ 22

UNIT – III

SYLLABUS
Working with Forms: Creating Forms, Accessing Form Input with User defined Arrays,
Combining HTML and PHP code on a single page, Using Hidden Fields to save state,
Redirecting the user, Sending Mail on Form Submission, and Working with File Uploads.

Working with Cookies and User Sessions: Introducing Cookies, setting a Cookie
with PHP, Session Function Overview, starting a Session, Working with Session Variables,
Passing Session IDs in the Query String, Destroying Sessions and Unsetting Variables, Using
Sessions in an Environment with Registered Users.

…………………………………………………………………………………………………..

Working with forms:


Creating Forms
• We can create and use forms in PHP. To get form data, we need to use PHP superglobals
$_GET and $_POST.
• The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.

Form Syntax:

<form action="server url" method="get|post">


//input controls e.g. text field, textarea, radiobutton, button
</form>

PHP POST Form


• Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc.
• The data passed through post request is not visible on the URL browser so it is secured.
You can send large amount of data through post request.

Form.html
The example below displays a simple HTML form with two input fields and a
submit button:
Source Code:

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

Output:

welcome.php

• 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:
Source code:

<html>

<body>

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

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

</body>

</html>

Output:

PHP GET Form

• Get request is the default form request. The data passed through get request is visible
on the URL browser so it is not secured. You can send limited amount of data through
get request.
• The same result could also be achieved using the HTTP GET method:

Form.html
The example below displays a simple HTML form with two input fields and a
submit button:
Source Code:

<html>

<body>

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

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

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

<input type="submit">

</form>

</body>

</html>

Output:

welcome.php

Source Code:

<html>

<body>

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

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

</body>

</html>
Output:

…………………………………………………………………………………………………..

Combining HTML and PHP Code on a Single Page


• Combining HTML and PHP code on a single page allows you to create dynamic web
pages. Here's an example of how you can integrate PHP within HTML to create a
simple web page:

Source Code:

<!DOCTYPE html>

<html>

<head>

<title>PHP and HTML Example</title>

</head>

<body>

<h1>Welcome to my website!</h1>

<?php

// PHP code starts here

$name = "John";

$age = 25;

// Displaying dynamic content using PHP within HTML


echo "<p>Hello, my name is $name and I am $age years old.</p>";

?>

<p>This is a static paragraph.</p>

</body>

</html>

Output:

…………………………………………………………………………
Using Hidden Fields to save state
• A hidden field let web developers include data that cannot be seen or modified by users
when a form is submitted.
• A hidden field often stores what database record that needs to be updated when the form
is submitted.
• The <input type = “hidden”> defines a hidden input field.
Source Code:

Hidden.html

<html>

<body>

click button<br>

<form method="post" action="phphid.php">

<input type="hidden" name=customer_type" value="good">

<br>

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

</form>

</body>

</html>

Output:

• Clicking the “send” button.


• The hidden field is not shown to the user, but the data is sent when the form is submitted.
Phphid.php

<html>

<body>

We are

<?php

echo $_request["customer_type"];

?>

customers

</body>

</html>

Output:

We are

customers

…………………………………………………………………………………………………..

Redirecting the user page


• The header function in PHP can be used to redirect the user from one page to another.
It is an in – built function that sends raw HTTP header to the destination( client ).

Syntax ( header()):

header( $header_value, $replace_value, $http_response_code);

Following are the Parameters –

➢ header_value - in the function is used to store the header string.


➢ replace_value – Parameter stores the value that needs to be replace.
➢ response_code – is used to store the HTTP response code.
Source Code:

<?php

// This will redirect the user to the new location

header("Location: http://www.javatpoint.com");

//The below code will not execute after header

exit;

?>

Output:
➢ The website to which the page needs to be redirected is specified in the header function.

Source Code:

<html>

<body>

<?php

function redirect($url)

header('location:'.$url);

exit();

redirect("http://w3schools.com");

?>

</body>

</html>

Output:
…………………………………………………………………………………………………..

Sending Mail on Form Submission


• PHP mail() function is used to send email in PHP. You can send text message, html
message and attachment with message using PHP mail() function.
• The mail() function allows you to send emails directly from a script.

Requirements
For the mail() functions to be available, PHP requires an installed and working email system.
The program to be used is defined by the configuration settings in the php.ini file.

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.
$message Required. Defines the message to be sent.
$headers Optional. Specifies additional headers, like
From, Cc, and Bcc.
$parameters Optional. Specifies an additional parameter
to the sendmail program.
Source Code:

<?php

$to = "[email protected]"; //change receiver address

$subject = "This is subject";

$message = "<h1>This is HTML heading</h1>";

$header = "From:[email protected] \r\n";

$result = mail ($to,$subject,$message,$header);

if( $result == true ){

echo "Message sent successfully...";

}else{

echo "Sorry, unable to send mail...";

?>

…………………………………………………………………………………………………

PHP File Upload


• PHP allows you to upload single and multiple files through few lines of code only.
• PHP file upload features allows you to upload binary and text files both. Moreover, you
can have the full control over the file to be uploaded through PHP authentication and
file operation functions.
• With PHP, it is easy to upload files to the server.
• Configure the “php.ini” File.
• First, ensure that PHP is configured to allow file uploads.
• In your “php.ini” file, search for the file_uploads directive, and set it to On:
File_uploads = On

Create The HTML Form:


Next, create an HTML form that allow users to choose the image file they want to upload:
Form.html:

Source Code:

<!DOCTYPE html>

<html>

<body>

<form action="uploader.php" method="post" enctype="multipart/form-data">

Select File:

<input type="file" name="fileToUpload"/>

<input type="submit" value="Upload Image" name="submit"/>

</form>

</body>

</html>

Output:
Uploader.php
<?php

$target_path = "e:/";

$target_path=$target_path.basename( $_FILES['fileToUpload']['name']);

if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {

echo "File uploaded successfully!";

} else{

echo "Sorry, file not uploaded, please try again!";

?>

Output:

Sorry, file not uploaded, please try again!

…………………………………………………………………………………………………..

Working with Cookies and User Sessions


Working with Cookies:
• PHP cookie is a small piece of information which is stored at client browser. It is used
to recognize the user.
• Cookie is created at server side and saved to client browser. Each time when client
sends request to the server, cookie is embedded with request. Such way, cookie can be
received at the server side.
Create Cookies with PHP:

• A cookie is created with the setcookie() function.

Syntax:

setcookie(name, value, expire, path, domain, secure, http only );

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

Create/Retrieve a Cookie in PHP:


• 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:

Source Code:

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

Output:

Modify a Cookie Value

• To modify a cookie, just set (again) the cookie using


the setcookie() function:

Source Code:

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

Output:

Delete a cookie:

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

Source Code:

<?php

// set the expiration date to one hour ago

setcookie("user", "", time() - 3600);

?>

<html>

<body>

<?php

echo "Cookie 'user' is deleted.";

?>

</body>

</html>
Output:

……………………………………………………………………………………

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

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:
Source Code:

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

Output:

Session variables are set.

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:
Source Code:

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

Output:

Favorite color is green.

Favorite animal is cat.

Modify a PHP Session Variable:


To change a session variable, just overwrite it:

Source Code:

<?php

session_start();

?>

<!DOCTYPE html>

<html>

<body>
<?php

// to change a session variable, just overwrite it

$_SESSION["favcolor"] = "yellow";

print_r($_SESSION);

?>

</body>

</html>

Output:

Array ( [favcolor] => yellow [favanimal] => cat )

Destroy a PHP Session:


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

Source Code:

<?php

session_start();

?>

<!DOCTYPE html>

<html>

<body>

<?php

session_unset(); // remove all session variables

session_destroy(); // destroy the session

?>

</body>

</html>

Output:

No output here, because the session variables are removed & delete ( destroy ) the session.

You might also like