0% found this document useful (0 votes)
17 views12 pages

PHP Unit3

aknu syllabus

Uploaded by

Pavani akumarthi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views12 pages

PHP Unit3

aknu syllabus

Uploaded by

Pavani akumarthi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Object 1

4
5
3
2

Form:

In PHP, a form refers to an HTML structure that allows users to input data which can be submitted
to a server for processing. Forms are crucial for collecting user information, such as login
credentials, registration details, or any other data input required by an application or website.

GET METHOD:

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..
GET may be used for sending non-sensitive data.
<form action="#" method="GET">

POST METHOD:
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.
<form action="#" method="POST">

PROGRAM:

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

FORM PROCESSING:

HTML forms are used to send the user information to the server and returns the result back to the
browser. For example, if you want to get the details of visitors to your website, and send them good
thoughts, you can collect the user information by means of form processing. Then, the information
can be validated either at the client-side or on the server-side. The final result is sent to the client
through the respective web browser.

Accessing input with user defined function :

• Use <form> tags to encapsulate the form elements.


• Define action attribute to specify where the form data will be submitted (a PHP script).
• Use method="post" or method="get" to define how the form data will be sent (POST or
GET request).
• Input fields (<input>, <textarea>, <select>) to collect user data.
• Each input should have a name attribute to identify the data when the form is submitted.
• Submit Button:
• Include an <input type="submit"> or <button type="submit"> to allow users to submit the
form.
• Create a PHP script that receives and processes the form data.
Access form data using PHP superglobals ($_POST for POST method, $_GET for GET
method).

Example.php

<html >
<body>
<h2>PHP Form Example</h2>
<form action="process_form.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>

<label>Gender:</label><br>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>

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


</form>
</body>
</html>

output:
PHP Form Example
Name:
male
female

Submit

process_form.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$gender = $_POST['gender'];

echo "Name: " . $name . "<br>";


echo "Gender: " . $gender . "<br>";
}
?>
output:
Name:latha
female

Combining HTML and PHP Code on a Single Page

•Write PHP code with HTML code on a single page as on hard copy.

•More flexibility to write the entire page dynamically.

•For this use a PHP_SELF variable is in the action field of the <form> tag.

•The action field of the FORM instructs where to submit the form data when the user presses the
“submit” button.

•The same PHP page as the handler for the form as well.

•The action field of form use to switch to control to other page but Using PHP_SELF variable do
not need to edit the action field.

Example:-
A file called form-abcd.php and want to load the same page after the form is submitted.
<form method="post" action="abcd.php" >
We can use the PHP_SELF variable instead of “abcd.php”.
The code becomes:
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
program:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
output

This PHP code is above the HTML part and will be executed first.

•The first line of code is checking if the form is submitted or not.

•The name of the submit button is “submit”.

•When the submit button is pressed the $_POST['submit'] will be set and the IF condition will
become true.

•It is showing the name entered by the user.


•If the form is not submitted the IF condition will be FALSE as there will be no values
in $_POST['submit'] and PHP code will not be executed.

The HTML <input type=”hidden”> element defines a hidden input field. Hidden fields store data
that are not visible or modifiable by users when they submit a form. They are useful for including
data that needs to be sent with the form but does not need to be displayed.

Syntax
<input type="hidden">
Example: This example demonstrates the use of HTML <input type=”hidden”> element

<html>
<head>
<title>
HTML Input Type Hidden
</title>
</head>
<body>
<h2>HTML &lt;input type="hidden"&gt;</h2>
<form action="#">
<input type="hidden" id="myFile" value="1234">

Enter Heading:
<input type="text" name="heading" id="heading">
<br><br>
Enter Paragraph:
<textarea name="content" id="content"></textarea>
<br><br>
Enter Meta Description:
<textarea name="content" id="content"></textarea>
<br><br>
<input type="submit" value="Create Post">
</form>
</body>
</html>

Redirection the user:


Redirection from one page to another in PHP is commonly achieved using the following two ways:
Using Header Function in PHP:
The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper
Text Transfer Protocol) header to the client.
Syntax:
header( $header, $replace, $http_response_code )
Parameters: This function accepts three parameters as mentioned above and described below:
$header: This parameter is used to hold the header string.
•$replace: This parameter is used to hold the replace parameter which indicates the header should
replace a previous similar header, or add a second header of the same type. It is optional parameter.
•$http_response_code: This parameter hold the HTTP response code.

<?php
// Redirect browser
header("Location: https://www.geeksforgeeks.org");
exit;
?>

sending mail on form submission :


Sending mail in PHP can be as simple as calling the built-in function mail(). mail() takes up to five
parameters but the first three are all that is required to send an email (although the four parameters
is commonly used as will be demonstrated below). The first three parameters are:
1. The recipient's email address (string)
2. The email's subject (string)
3. The body of the email (string) (e.g. the content of the email)
Parameter Details
string $to The recipient email address
string $subject The subject line
string $message The body of the emai
string $additional_headers Optional: headers to add to the email
string $additional_parameters Optional: arguments to pass to the

configured mail send application in the command line

the From name and email address the user will see
the Reply-To email address the user's response will be sent to
additional non-standards headers like X-Mailer which can tell the recipient this email was sent via
PHP
First, create an HTML form where users can enter their information. Include fields for email
address, subject, message, etc.
Contact.form
<html >
</head>
<body>
<h2>Contact Us</h2>
<form action="send_email.php" method="post">
Name:
<input type="text" id="name" name="name" required><br><br>
Email:
<input type="email" id="email" name="email" required><br><br>
Subject:
<input type="text" id="subject" name="subject" required><br><br>
Message:
<textarea id="message" name="message" rows="4" required></textarea><br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
send_email.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

// Set up email parameters


$to = "[email protected]"; // Replace with your email address
$headers = "From: $email \r\n";
$headers .= "Reply-To: $email \r\n";

// Compose the email content


$email_content = "You have received a new message from your website contact form.\n\n";
$email_content .= "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Subject: $subject\n";
$email_content .= "Message:\n$message\n";

// Send the email


if (mail($to, $subject, $email_content, $headers)) {
echo "<h2>Email sent successfully!</h2>";
} else {
echo "<h2>Failed to send email. Please try again later.</h2>";
}
}
?>

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.
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we
can get file name, file type, file size, temp file name and errors associated with file.
$_FILES['filename']['name']
returns file name.

$_FILES['filename']['type']
returns MIME type of the file.

$_FILES['filename']['size']
returns size of the file (in bytes).

$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.

$_FILES['filename']['error']
returns error code associated with this file.
Uploader.html
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data"> Select image to
upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
<?php

uploder.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:
select file: choose fil
choose file
upload image
Cookie
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.

setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can
access it by $_COOKIE superglobal variable.

$_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example

1. $value=$_COOKIE["CookieName"];//returns cookie value


PHP Cookie Example
File: cookie1.php

<?php
setcookie("user", "Sonoo");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Output: Sorry, cookie is not found!

Delete Cookie
If you set the expiration date in past, cookie will be deleted.
File: cookie1.php

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

Session

PHP session is used to store and pass information from one page to another temporarily (until user
close the website).
PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.

session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes existing session.
It returns existing session if session is created already. If session is not available, it creates and
returns new session.
EXAMPLE: session_start();

PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get
session variable values.
Example: Store information
1. $_SESSION["user"] = "Sachin";
Example: Get information

1. echo $_SESSION["user"];

Program:
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
echo "User is: ".$_SESSION["user"];
?>
Destroying Session
PHP session_destroy() function is used to destroy all session variables completely.

You might also like