220245-MSBTE-22619-PHP (Unit 4)
220245-MSBTE-22619-PHP (Unit 4)
12 marks
Introduction to Webpage
To run any code on server or to get connected with PHP on server we need to set up Web pages
in a specific fashion.
Two methods “get” and “post” mentioned in form are commonly used to send data from HTML
controls to PHP scripts on the server.
URL is used to specify location, which helps browsers understand where to send the data on the
server mentioned in the “action: attribute of a form”.
Two methods get and post mentioned in form are commonly used to send data from HTML
controls to PHP script on server.
URL is used to specify the location which specifies where to send data on the server.
PHP script handles both displaying of HTML controls and then reading of data from HTML
controls when the user clicks on the submit button.
A document that contains blank fields, that the user can fill the data or user can select the data
is known as form.Generally the data will be stored in the database.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
Browser used one of the two HTTP methods - GET and POST to communicate with the server.
Both methods are used to pass the information differently to the server.
GET method:
1. The GET method sends the encoded user information appended to the page request (to
the url). The code and the encoded information are separated by the ? character.
2. http://www.test.com/index.htm?name1=value1&name2=value2
3. The GET method produces a long string that appears in our server logs, in the browser’s
location:box.
4. Never use the GET method if we have a password or other sensitive information to be sent to
the server. Get cannot be used to send binary data, like images or word documents, to the
server.
5. The data sent by the GET method can be accessed using the QUESRY_STRING
environment variable.
6. PHP provides a $_GET associative array to access all the sent information using the GET
method.
POST Method
1. The POST method transfers information via HTTP headers. The information is encoded as
described in the case of the GET method and put into a header called QUERY_STRING.
2. The POST method does not have any restriction on data size to be sent.
3.The POST method can be used to send ASCII as well as binary data.
4.The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides a $_POST associative array to access all the sent information using the POST
method.
GET Method
1. Information sent from a form with the get method is visible to everyone(all variable names
and values are displayed in the URL)
2. GET has limits on the amount of information to send. The limitation is about 2048 characters
3.$_GET is an array of variables passed to the current script via the URL parameters.
4. Can be bookmarked.
5. Can be cached.
POST Method
1. 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)
2. Post has no limits on the amount of information to send.
3. $_POST is an array of variables passed to the current script via the HTTP POST method.
4.Cannot be bookmarked.
5. Not cached.
6. Parameters are not saved in browser history.
Server Role
4.2 Form controls: text box, text area, radio button, check box, list, button
1. Textbox
A text input field allows the user to enter a single line of text
Textbox field enable the user to input text information to be used by the program
step3
Step 4
2. Textarea
A text area field is similar to a text input field but it allows the user to enter multiple line of text
Syntax
<textarea name=name of component row=“some number”cols=“some number”>< /textarea>
Eg<textarea name=”address” rows=“5” cols=“40”>< /textarea>
3. Checkbox
<form action="#" method="post">
<?php
if(isset($_POST['submit']))
{//to run PHP script on submit
if(!empty($_POST['check_list']))
{
// Loop to store and display values of individual checked checkboxes.
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}
}
}
?>
4. List Box
<html>
<body>
<div>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label> Best Engineering College in Maharashtra</label>
<p><select name="products[]" multiple="multiple">
<option>VESIT</option>
<option>VJTI</option>
<option>COEP</option>
<option>PCIT</option>
<form method="post">
<h3>personal information form</h3>
user name:<input type="text" name="username"/>
<br/><br/>
address:<input type="text" name="address"/>
<br/><br/>
<input type="submit" name="submit_personal_info" value="submit"/>
<br/>
<form method="post">
<h3>Simple Arithmetic Calculator</h3>
Number 1: <input type="text" size="5" name="num1"/>
<br/><br>
Number 2: <input type="text" size="5" name="num2"/>
<br/><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
<input type="submit" name="mul" value="MULTIPLICATION"/>
<input type="submit" name="div" value="DIVISION"/>
<?PHP
if(!empty($_POST['add'])) {
$result=$_POST['num1']+$_POST['num2'];
echo "<h3> Addition: ".$result."</h3>";
}
if(!empty($_POST['sub']))
{
$result=$_POST['num1']-$_POST['num2'];
echo "<h3> Subtraction: ".$result."</h3>";
}
if(!empty($_POST['mul']))
What is Validation ?
Required field will check whether the field is filled or not in the proper way. Most of cases we
will use the * symbol for required field.
Validation means checking the input submitted by the user. There are two types of validation
available in PHP. They are as follows −
● Client-Side Validation − Validation is performed on the client machine web browsers.
● Server Side Validation − After submitted by data, The data is sent to a server and
performs validation checks in the server machine.
Example of validation
1.Valid URL
Below code shows validation of URL
$website = input($_POST["site"]);
if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=
~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
Above syntax will verify whether a given URL is valid or not. It should allow some keywords as
https, ftp, www, a-z, 0-9,..etc..
2.Valid Email
Below code shows validation of Email address
$email = input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid format and please re-enter valid email";
}
Above syntax will verify whether a given Email address is well-formed or not.if it is not, it will
show an error message.
1. The filterName() function validates input value as a person's name. A valid name can
only contain alphabetical characters (a-z, A-Z).
3. The filterString() function only sanitizes the input value by stripping HTML tags and
special characters. It doesn't validate the input value against anything.
1.Cookie is a small piece of information stored as a file in the user's browser by the web server.
2.Once created, cookie is sent to the web server as header information with every HTTP
request.
3. You can use cookies to save any data but it should not exceed 1K(1024 bytes) in size.
4. Before we move on to how to create, update and delete cookies, let's learn a few real world
uses of cookies.
Here,
1) A user requests for a page that stores cookies
2) The server sets the cookie on the user’s computer
3) Other page requests from the user will return the cookie name and value
● Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer.
The path where the cookies are stored depends on the browser.
Internet Explorer usually stores them in the Temporary Internet Files folder.
● Personalizing the user experience – this is achieved by allowing users to select their
preferences.
The page requested that follows are personalized based on the set preferences in the
cookies.
● Tracking the pages visited by a user
● To store user information like when he/she visited, what pages were visited on the
website etc, so that next time the user visits your website you can provide a better user
experience.
● To store basic website specific information to know this is not the first visit of a user.
2. Types of Cookies
1. Session Cookie: This type of cookies are temporary and expire as soon as the session
ends or the browser is closed.
2. Persistent Cookie: To make a cookie persistent we must provide it with an expiration
time. Then the cookie will only expire after the given expiration time, until then it will be
a valid cookie.
3. You can use cookies to store number of visits or view counter
The first argument which defines the name of the cookie is mandatory, rest all are optional
arguments.
name Used to specify the name of the cookie. It is a mandatory argument. Name of
the cookie must be a string.
value Used to store any value in the cookie. It is generally saved as a pair with a
name. For example, name is userid and value is 7007, the userid for any user.
expire Used to set the expiration time for a cookie. if you do not provide any value,
the cookie will be treated as a session cookie and will expire when the
browser is closed.
path Used to set a web URL in the cookie. If set, the cookie will be accessible only
from that URL. To make a cookie accessible through a domain, set '/' as cookie
path.
domain The domain of your web application. It can be used to limit access to cookies
for sub-domains.
secure If you set this to 1, then the cookie will be available and sent only over HTTPS
connection.
E.g So if we want to create a cookie to store the name of the user who visited your website, and
set an expiration time of a week, then we can do it like this,
<?php
setcookie("username", "Shika", time()+60*60*24*7);
?>
To access a stored cookie we use the $_COOKIE global variable, and can use the isset() methods
to check whether the cookie is set or not.
Let's have a complete example where we will set a cookie and then retrieve it to show its value
in the HTML page.
<?php
// set the cookie
setcookie("username", "Ramkra", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
</body>
</html>
So by providing the name of the cookie inside the square brackets with the global variable
$_COOKIE[] we can access the cookie.
NOTE: setcookie() function should be placed before the starting HTML tag(<html>).
<?php
// updating the cookie
setcookie("username", "Ambarish", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
We just update the value of the username cookie
<?php
1.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 user's computer.
2. When you work with an application, you open it, do some changes, and then you close it. This
is much like a Session.
3. 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.
4. 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.
5. So; Session variables hold information about one single user, and are available to all pages in
one application.
Tip: If you need permanent storage, you may want to store the data in a database.
PHP mail
PHP mail is the built-in PHP function that is used to send emails from PHP scripts.
<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>
HERE,
“$to_email_address” is the email address of the mail recipient
“$subject” is the email subject
“$message” is the message to be sent.
“[$headers]” is optional, it can be used to include information such as CC, BCC
CC is the acronym for carbon copy. It’s used when you want to send a copy to an interested
person i.e. a complaint email sent to a company can also be sent as CC to the complaints board.
BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses included in the
BCC section will not be shown to the other recipients.
1. File :-Php.ini
//email function
smtp_port=465
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
mail.add_x_header=on
2. File:- sendemail.ini
smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=auto
error_logfile=error.log
[email protected]
1. Configure SMTP settings on your localhost Assuming you are using xampp on windows, locate
the “php.ini” in the directory “C:\xampp\php”.
● Open it using a notepad or any text editor. We will use a notepad in this example. Click
on the edit menu
<?php
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
Output: