0% found this document useful (0 votes)
2 views31 pages

UNIT4 PHP

The document covers state management in PHP, explaining the importance of maintaining user-specific information in a stateless HTTP protocol. It discusses various methods for state management, including URL rewriting, hidden form fields, sessions, and cookies, detailing how to implement and manage each method. Additionally, it introduces regular expressions in PHP, highlighting their advantages and uses in validating and manipulating text strings.

Uploaded by

mafiatitan946
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)
2 views31 pages

UNIT4 PHP

The document covers state management in PHP, explaining the importance of maintaining user-specific information in a stateless HTTP protocol. It discusses various methods for state management, including URL rewriting, hidden form fields, sessions, and cookies, detailing how to implement and manage each method. Additionally, it introduces regular expressions in PHP, highlighting their advantages and uses in validating and manipulating text strings.

Uploaded by

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

PHP NOTES FOR MGSU EXAMS

UNIT-4
1

State Management in PHP

HTTP is a stateless protocol which means every user request is processed


independently and it has nothing to do with the requests processed before
it. Hence there is no way to store or send any user specific details using
HTTP protocol.

But in modern applications, user accounts are created and user specific
information is shown to different users, for which we need to have
knowledge about who the user(or what he/she wants to see etc) is on every
webpage.

State is useful, though. You can't build a shopping-cart application, for


example, if you can't keep track of a sequence of requests from a single user.
You need to know when a user puts a item in his cart, when he adds items,
when he removes them, and what's in the cart when he decides to check out.

To keep login user in website until it will not logout. Avoid cart to be empty
when we refresh the page all these are managed by the state.

Using URL Rewriting (Query String) for State Management

In URL rewriting, a token(parameter) is added at the end of the URL. The


token consist of name/value pair seperated by an equal(=) sign.
• The information sent across the web pages.
• This information is called a query string.
• This query string can be passed from one page to another by appending its address
of the page.
• Passing more than one query string by inserting the & sign between the query
strings.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


2

• A query string contains two things: the query string ID and its value.
• The query string passed across the web pages is stored in $_REQUEST, $_GET, or
$_POST variable.
• Avoid to manage state of sensitive data using url rewriting
• Limitation of data is about 2000 characters in URL rewriting

Example:- the query strings username and email (the names of textboxes) are passed
from a page called login.php to another page called welcome.php when We click the
submit button.

Login.php:

<html>
<head>
<title>Login form</title>
</head>
<body>
<form action="welcome.php" method=”get”>
<table>
<tr>
<td>User name:</td><td> <input type="text" name="username" ></td>
</tr>
<tr>
<td>E-mail: </td><td><input type="text" name="email" ></td>
</tr>
<tr>
<td><input type="submit" name="sub" value="submit"></td>
</tr>
</table>
</form>
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
3

</body>
</html>

welcome.php:

<?php
echo "<strong>Welcome ".$_GET['username']. "!</strong><br/>";
echo "Please remember this e-mail: ".$_GET['email']. " for later use.";
?>

Hidden Form Field


In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of
an user.

In such case, we store the information in the hidden field and get it in our php file. This approach
is better if we have to submit form in all the pages and we don't want to depend on the browser.

Note. While the value is not displayed to the user in the pages content. It is visible (and can be
edited) using any browser tool or view source functionality. Do not use hidden input as a form of
security

Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">

<form action=”success.php” method=”POST”>

<input type=”text” id=”fname” name=”fname”><br> <br>


<input type=”hidden” id=”custid” name=”custid” value=”224”>
<input type=”submit” value=”submit”>
</form>
<p> the hidden field is not shown to the user, but the data is sent when the form is submitted
</p>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


4

Susscess.php

<?php

$fname=$_POST[fname];

$id=$_POST[custid];

Echo $fname”. .”$id

?>

What is a session
Sessions are states that are saved to the server (like a unique ID), or if a user is logged into their
account.

NOTE Because sessions are not stored in the browser like cookies, it is a more secure option.

As an example, let’s consider a social media application like Facebook.

When users log into their Facebook account, the application remembers who they are until they
log out. When logged in, a user has access to special features such as sending messages,
uploading images and videos, joining groups etc.

The application tracks these states and stores them as a session on the server. As soon as the
user is logged out, the session is destroyed.

How to start a session and store session data


To start a session in PHP, we use the session_start() function. We store session data by
using the $_SESSION superglobal.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


5

// start a session

session_start();

// set a session variable

$_SESSION["session_variable_name"] = session_variable_value;

The session_start() function must be the first statement in the document.

EXAMPLE main.php - start a session and store session data

<?php

// start a session
session_start();

// set a session variable


$_SESSION["username"] = "John";
$_SESSION["userID"] = 1;

?>
<html>
<body>

<a href="sessions.php">Sessions page</a>

</body>
</html>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


6

How to access session data


We access session data in the same way we would access an array element.

Example: sessions.php - access session data

<?php
session_start();

echo "Hello " . $_SESSION["username"];

?>

When we run the main.php file, it stores the session data. Clicking the link takes us to a new
page where we display the stored data. The username value survived across pages.

How to change session data


Session variables are mutable, which means they can be changed during runtime. To change the
value of a session variable, we simply assign a new value to it.

$_SESSION["session_variable_name"] = "new_value";

How to remove stored session data from variables


If we want to clear out all the stored values from session variables, we use
the session_unset() function.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


7

Example: session.php - remove stored session data from variables


<?php
session_start();

echo "Hello " . $_SESSION["username"];

// unset username value


session_unset();

// try to print username to the page


echo $_SESSION["username"];

?>

After we unset the value of the username variable, we can no longer print it and the interpreter
will raise an Undefined index error.

Output:

Notice: Undefined index: username on line 10

How to destroy a session


We can destroy a whole session completely with the session_destroy() function.

Example: sessions.php - destroy a session


<?php
session_start();
echo "Hello " . $_SESSION["username"];
// unset username value
session_destroy();
// try to print username to the page
echo $_SESSION["username"];
?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


8

When the session is destroyed, both echo statements will not be able to print the username
variable, and the interpreter will raise an error.

Output:
Notice: Undefined index: username on line 4
Hello
Notice: Undefined index: username on line 10

Typically, a session is destroyed after logout or checkout etc. to clean the session variable of the
user specific data.

What is a cookie
Cookies are states that are saved to the user’s system, instead of the server. Unlike a session, a
cookie has a 1024 byte size limit. Cookies are sent to the web server as header information in
every HTTP request.

NOTE Cookies are not stored on the server, they can be modified and deleted. Cookies are less
reliable and secure than sessions.

As an example, let’s consider an application with a member area. Once a user enters their log in
details, a cookie is created on that user’s system that saves those details.

If the user comes back to the application, the login details can be automatically filled into the
form so that the user doesn’t have to repeat the process.

Cookies are also commonly used to serve advertisements based on products that the user views
around the web. For example, if a user views a product on Amazon, they will find
advertisements of similar products when using Facebook or Google services.

How to set a cookie


PHP provides us with the setcookie() function to create, or set, a cookie.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


9

Syntax:

setcookie(name, value, expiration, path, domain, secure);

The first argument, name, is mandatory for every cookie. The rest of the arguments are
optional, but recommended.

Argument Usage
name Required. The name the cookie will be referred to. Must be a string.
value Optional. The value of the cookie.
expiration Optional. If an expiration time is not set, the cookie will expire when the browser is closed.
path Optional. The path on the server the cookie will be available on. The cookie can be set to '/'
to be available to the entire domain.
domain Optional. The (sub)domain that the cookie is available to. Sub-domains of the specified
domain are automatically included.
secure Optional. If set to true, the cookie will only be set for a HTTPS secure connection.

Example: how to set a cookie


<?php

// Expires when the browser closes


setcookie("UserID", 007);

// Expires in 1 minute (60 seconds)


setcookie("SelfDestructMsg", "1 minute", time()+60)

// Only available to a specific subdomain over HTTPS


setcookie("Name", "Bond, James", time()+60, "/totally_not_cookies/",
"agents.mi6.com", 1);

?>

The value portion of the cookie will automatically be urlencoded when the cookie is sent.
Characters such as a space and . will be converted to underscores. When the cookie is
received, it will be automatically decoded and assigned to a variable with the same name.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


10

The expiration time is often confusing for many beginners that aren’t used to working with the UNIX
timestamp. In such a case we can use the strtotime() function which converts time from a string
into the correct time.

Syntax:

strtotime('+30 days')

Example: alternate expiration time


<?php

// Expires in 30 days
setcookie("UserID", 007, strtotime('+30 days'));

?>

How to access cookie data


We access a cookie’s value via the $_COOKIE superglobal by specifying its name as the key.

Syntax:

$_COOKIE["cookie_name"];

Example: access a cookie


<?php

setcookie("Name", "Bond, James", time()+60);

echo "Agent: " . $_COOKIE["Name"];

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


11

How to change cookie data


We can change any argument of the cookie, except the name, by assigning a new value. When a
new name is assigned, it will create a new cookie instead of changing the current cookie.

Example: how to change cookie data


<?php

setcookie("Name", "Hunt, Ethan", time()+5);

echo "Agent: " . $_COOKIE["Name"];

?>

How to delete a cookie


We delete a cookie by setting its expiration time to anything in the past.

Example: how to delete a cookie


<?php

// Current time - 60 minutes


setcookie("Name", "Hunt, Ethan", time()-3600);

echo "Agent: " . $_COOKIE["Name"];

?>

When a cookie is deleted and we try to access it, the interpreter will raise an Undefined index
error.

Output: deleted cookie error

Notice: Undefined index: Name on line 6

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


12

The error is raised as an undefined index because the index Name in


the $_COOKIE superglobal doesn’t exist anymore.

There is a risk of the user modifying their system’s time backwards so that the cookie does not
expire. We recommend that the cookie be set to expire one second into the future, instead of in
the past.

Example: delete a cookie in a second


<?php

// Current time - 60 minutes


setcookie("Name", "Hunt, Ethan", time()+1);

echo "Agent: " . $_COOKIE["Name"];

?>

-------------------------------- ---------------------- ------------------------ ------------------- -----


----------------------------- ------------------------------ ---------------- ----------------------------

PHP Regular Expressions


--------- https://www.youtube.com/watch?v=3RlDZEa6gW8 ------------

Regular expressions are commonly known as regex. These are nothing more than a pattern or a
sequence of characters, which describe a special search pattern as text string.

Regular expression allows you to search a specific string inside another string. Even we can replace
one string by another string and also split a string into multiple chunks. They use arithmetic
operators (+, -, ^) to create complex expressions.

One of the usage of the regular expression to validate form or identify the password is strong or
not by matching the string with the expression

By default, regular expressions are case sensitive.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


13

Advantage and uses of Regular Expression


Regular expression is used almost everywhere in current application programming. Below some
advantages and uses of regular expressions are given:

1. Regular expression helps the programmers to validate text string.


2. It offers a powerful tool to analyze and search a pattern as well as to modify the text string.
3. By using regexes functions, simple and easy solutions are provided to identify the patterns.
4. Regexes are helpful for creating the HTML template system recognizing tags.
5. Regexes are widely used for browser detection, form validation, spam filtration, and
password strength checking.
6. It is helpful in user input validation testing like email address, mobile number, and IP
address.
7. It helps in highlighting the special keywords in file based upon the search result or input.
8. Metacharacters allow us to create more complex patterns.

POSIX Regular Expression


The structure of POSIX regular expression is similar to the typical arithmetic expression: several
operators/elements are combined together to form more complex expressions.

The simplest regular expression is one that matches a single character inside the string. For
example - "g" inside the toggle or cage string.

PERL Style Regular Expression


Perl-style regular expressions are much similar to POSIX. The POSIX syntax can be used with Perl-
style regular expression function interchangeably. The quantifiers introduced in POSIX section can
also be used in PERL style regular expression.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


14

You can create complex search patterns by applying some basic rules of regular expressions.
Many arithmetic operators (+, -, ^) are also used by regular expressions to create complex
patterns.

Operator Description

[] It finds a range of characters, e.g., [abc] means a, b, or c.

\ It denotes the escape character.

- It finds the range between the elements, e.g., [a-z] means a through z.

| It is a logical OR operator, which is used between the elements. E.g., a|b, which means either a

geeks The string “geeks”

^geeks The string which starts with “geeks”

geeks$ The string which have “geeks” at the end.

^geeks$ The string where “geeks” is alone on a string.

[a-z] Any lowercase letter

[^A-Z] Any letter which is NOT a uppercase letter

Example of a expression

$exp = “/helo/i”;

We can pass these expression in various regukar expression function to find the string of
replace the string .

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


15

Other example of regular expression is

$exp=”/ w[a-f]b/i”

This expression will check string like wab , wbb, wcb, wdb, web, wfb in another string

Metacharacters
A metacharacter is an alphabetical character followed by a backslash that gives a special meaning
to the combination.

For example - '\d' metacharacter can be used search large money sums: /([\d]+)000/. Here /d
will search the string of numerical character.

Character Description

. Matches a single character

\s It matches a whitespace character like space, newline, tab.

\S Non-whitespace character

\d It matches any digit from 0 to 9.

\D Matches a non-digit character.

\w Matches for a word character such as - a-z, A-Z, 0-9, _

\W Matches a non-word character.

Modifier ‘I’

i Makes case insensitive search


We can use modifier I which make the search a case insensitive for example a expression /cat/ will
Search the string cat only in the lowercase but when we use modifier I in it example /cat/I it will
search both cat as well as CAT

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


16

PHP currently provides seven functions to search strings using Regular expression

PHP preg_match() function

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It
returns true if a match is found and false if a match is not found.

The preg_match() function is a built-in function of PHP that performs a regular expression match.
This function searches the string for pattern, and returns true if the pattern exists otherwise
returns false.

Generally, the searching starts from the beginning of $subject string parameter. The optional
parameter $offset is used to start the search from the specified position.

In general it stops when the first match of the string is found .

Syntax

int preg_match (string $pattern, string $subject, array $matches, int $flags, int $offset)

Parameters

This function accepts five parameters, which are described below:

Pattern

It is a string type parameter. This parameter holds the pattern to search as a string.

subject

This parameter holds the input string in which we search for pattern.

matches

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


17

If matches parameter is provided, it will contain the search results.

Flags

The flags can have the following flags given below:

o PREG_OFFSET_CAPTURE: If this flag is passed in preg_match(), for every occurring match


the appendant string offset will also return.
o PREG_UNMATCHED_AS_NULL: If this flag is passed in preg_match(), unmatched
subpattern will be reported as NULL, otherwise they will be reported as empty string.

offset

By default, the search starts from the beginning of the $subject parameter. The offset parameter
is used to specify the place where the searching will start. It is an optional parameter.

Return Type
The preg_match() function returns true if pattern matches otherwise, it returns false.

Examples: case-insensitive search

1. <?php
2. //initialize a variable of string type
3. $website = "JTP is a best online platform to learn.";
4.
5. //case insensitive search for word jtp
6. //The "i" after pattern delimiter indicates case-insensitive search
7. $res = preg_match('/jtp/i', $website, $matches);
8.
9. if ($res) { Output
10. echo "Pattern matched in string.</br>"; Pattern matched in string.
11. print_r($matches); Array ( [0] => JTP )
12. } else {
13. echo "Pattern not matched in string.";
14. }
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
18

15. ?>

PHP preg_match_all() function

The preg_match_all() function returns the number of matches of a pattern that were found
in a string and populates a variable with the matches that were found.it is same as like
preg_match function also the perameters are same the only difference it returns number
of matches of a pattern

PHP preg_replace() function

preg_replace() in PHP – this function is used to perform a pattern match on a string and
then replace the match with the specified text.

This function searches for pattern in subject parameter and replaces them with
the replacement.

Syntax

1. preg_replace (mixed $pattern, mixed $replacement, mixed $subject, int $limit, int $count)

Parameters
This function accepts five parameters, which are described below:

pattern

This parameter can be either a string or an array with strings. It holds the pattern to search in
subject parameter.

replacement

It is a string or an array with strings parameter. This parameter replaces the pattern matched in
subject parameter. It is a mandatory parameter.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


19

o If the replacement parameter is a string and the pattern parameter is an array, all patterns
will be replaced by that string.
o If both replacement and pattern parameters are arrays, each pattern will be replaced by
the replacement counterpart.
o If the replacement array consists of fewer elements than the pattern array, any extra pattern
will be replaced by an empty string.

subject

The subject parameter can also be either a string or an array of string to search and replace.

If the subject is an array, the search and replacement are performed on every entry of subject,
and the returned value will also be an array.

limit

The limit is an optional parameter that specifies the maximum possible replacement for each
pattern. The default value of limit is -1, which means no limit.

count

It is an optional parameter. If this parameter is passed, this variable will contain the number of
replacements done. This parameter added in PHP 5.1.0.

Return Type
The preg_replace() function returns an array if the subject parameter is an array otherwise it
returns a string.

o After the replacement has done, the modified string will be returned.
o If any matches do not find, the string will remain unchanged.

Examples
Simple Replacing

1. $res = preg_replace('/abc/', 'efg', $string); #Replace all 'abc' with 'efg'


2. $res = preg_replace('/abc/i', 'efg', $string); #Replace with case-insensitive matching
3. $res = preg_replace('/\s+/', '', $string); #Strip all whitespace
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
20

In the below example, preg_replace() replace is with was from the given string.

1. <?php
2. $str = 'Camila Cabello is a Hollywood singer.'; Output
3. $str = preg_replace('/is/', 'was ', $str);
4. echo $str;
Camila Cabello was a Hollywood
5. ?>
singer.

PHP preg_split() function

The preg_split() function is an inbuilt function in PHP which is used to convert the given string
into an array. The function splits the string into smaller strings or sub-strings of length which is
specified by the user. If the limit is specified then small string or sub-strings up to limit return
through an array.

This function exactly works like split() function except the condition is that it accepts regular
expression as an input parameter for pattern. Mainly it divides the string by a regular expression.

Syntax:

array preg_split( $pattern, $subject, $limit, $flag )

Parameter: This function accepts four parameters as mentioned above and described below:

$pattern: The value is string type which the pattern to search as a string otherwise its separates
the elements.

$subject: The $subject is variable which is used to store input string.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


21

$limit: The $limit is indicates the limit. If the limit is specified ,then small or sub-string to be
returned up to limit.If limit is 0 or -1 ,it indicates “no limit” then used by flag ($strflag).

$flags: The $flags is used for signalize and its variable type used for indicates two state True or
False to control the program. Its combinations of different flags such as below:

• PREG_SPLIT_NO_EMPTY: If flag variable is set to PREG_SPLIT_NO_EMPTY, then only non-


empty pieces will be returned by preg_split() function.

• PREG_SPLIT_DELIM_CAPTURE: If flag variable is set to PREG_SPLIT_DELIM_CAPTURE, the


parenthesized expression in the delimiter pattern will be captured and returned as well.

• PREG_SPLIT_OFFSET_CAPTURE: If flag variable is set to PREG_SPLIT_OFFSET_CAPTURE, for


each occurring match the appendant string offset will be returned and changes the return
value in an array where matched string offset will be 0 and input string offset will be 1.

Return Value: This function returns an array after the split boundaries matched. When the limit
of the original array or string exceeds then returns with an array element otherwise it’s False.
Below programs illustrate the preg_split() function in PHP:

<?php

// Input string
$inputstrVal = 'Geeksarticle';

// Implementation of preg_split() function


$result = preg_split('//', $inputstrVal , -1, PREG_SPLIT_NO_EMPTY);

// Display result
print_r($result);
?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


22

Output:

Array

[0] => G

[1] => e

[2] => e

[3] => k

[4] => s

[5] => a

[6] => r

[7] => t

[8] => i

[9] => c

[10] => l

[11] => e

------------------------------------------------------------------------------------

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


23

PHP Mail
Php mail is the built in PHP function that is used to send email form php script. 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.

✓ It is a cost effective way to notifying users on important events

✓ Let users contact you via email by providing a contact us form on the website that emails

the provided content

✓ Developer can use it to receive system errors by email

✓ You can use it to email your newsletters subscribers

✓ You can use it to send password reset links to users who forget their password

✓ You can use it to mail activation/ confirmation links. This is useful when registering users

and verifying their email addresses

The PHP mail() Function

Sending email message are very common for a web application, for example,
sending welcome email when a user create an account on your website, sending
newsletters to your registered users, or getting user feedback or comment through
websites contact form and so on

You can use the php built in mail() function for creating and sending email message
to one or more recipient dynamically from your PHP application either in a plain-
text form or formatted HTML. The basic syntax of this function can be given with

Syntax:

Mail(to, subject , message, headers, parameters)


PHP NOTES FOR MGSU EXAMS GORISH MITTAL
24

$to: specifies receiver or receivers of the mail. The receiver must be specified one of the following
forms.

o user@example.com
o user@example.com, anotheruser@example.com
o User <user@example.com>
o User <user@example.com>, Another User anotheruser@example.com

$subject: represents subject of the mail.

$message: represents message of the mail to be sent. Each line should be separated with the line
feed-LF (/n). line should not exceed 70 characters

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

{php email header explain….. pending topic}

parameters
Optional. Specifies an additional parameter to the send mail program

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


25

PHP Mail Example

File: mailer.php

1. <?php
2. $to = "sonoojaiswal1987@gmail.com";//change receiver address
3. $subject = "This is subject";
4. $message = "This is simple text message.";
5. $header = "From:sonoojaiswal@javatpoint.com \r\n";
6.
7. $result = mail ($to,$subject,$message,$header);
8.
9. if( $result == true ){
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
26

10. echo "Message sent successfully...";


11. }else{
12. echo "Sorry, unable to send mail...";
13. }
14. ?>

If you run this code on the live server, it will send an email to the specified receiver.

Example
Following example will send an HTML email message to xyz@somedomain.com copying it to
afgh@somedomain.com. You can code this program in such a way that it should receive all
content from the user and then it should send an email.

<html>

<head>
<title>Sending HTML email using PHP</title>
</head>

<body>

<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";

$message = "<b>This is HTML message.</b>";


$message .= "<h1>This is headline.</h1>";

$header = "From:abc@somedomain.com \r\n";


$header .= "Cc:afgh@somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
27

$header .= "Content-type: text/html\r\n";

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

if( $retval == true ) {


echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>

</body>
</html>

SMTP
https://www.youtube.com/watch?v=RdNErie6dKU

o SMTP stands for Simple Mail Transfer Protocol.


o SMTP is a set of communication guidelines that allow software to transmit an electronic
mail over the internet is called Simple Mail Transfer Protocol.
o It is a program used for sending messages to other computer users based on e-mail
addresses.
o It provides a mail exchange between users on the same or different computers, and it also
supports:
o It can send a single message to one or more recipients.
o Sending message can include text, voice, video or graphics.
o It can also send the messages on networks outside the internet.
o The main purpose of SMTP is used to set up communication rules between servers. The
servers have a way of identifying themselves and announcing what kind of communication
they are trying to perform. They also have a way of handling the errors such as incorrect

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


28

email address. For example, if the recipient address is wrong, then receiving server reply
with an error message of some kind.

Working of SMTP
Communication between sender and the receiver :

The sender’s user agent prepares the message and sends it to the MTA. The MTA’s responsibility
is to transfer the mail across the network to the receiver’s MTA. To send mails, a system must
have a client MTA, and to receive mails, a system must have a server MTA.

SENDING EMAIL:

Mail is sent by a series of request and response messages between the client and the server. The
message which is sent across consists of a header and a body. A null line is used to terminate the
mail header and everything after the null line is considered as the body of the message, which is
a sequence of ASCII characters. The message body contains the actual information read by the
receipt.

RECEIVING EMAIL:
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
29

The user agent at the server-side checks the mailboxes at a particular time of intervals. If any
information is received, it informs the user about the mail. When the user tries to read the mail it
displays a list of emails with a short description of each mail in the mailbox. By selecting any of
the mail users can view its contents on the terminal.

PHP Mailer
PHP Mailer is a code library and used to send emails safely and easily via PHP code from a web
server. Sending emails directly via PHP code requires a high-level familiarity to SMTP standard
protocol and related issues and vulnerabilities about Email injection for spamming. PHPMailer
simplifies the process of sending emails and it is very easy to use. Installation: The best way to
install PHP Mailer is by using composer.

PHP’s built-in mail() function has some limitations, including poor handling of attachments,
difficulty sending HTML emails, and susceptibility to spam filters. We can use the PHPMailer
library instead, which provides a simple and reliable way to send emails in PHP.

PHPMailer is a third-party PHP library that provides a simple way to send emails in PHP. It offers
a range of features that make it a popular alternative to PHP’s built-in mail() function, such as
support for HTML emails, attachments, and SMTP authentication.

PHPMailer is easy to set up and use and provides a high level of customization and flexibility,
making it a popular choice for developers who need to send emails from their PHP applications.
It is also actively maintained and updated, making it a reliable and secure email option

Advantages of Using PHPMailer


Plain Text Version of Email

mail() can be a good option for sending simple, plain text emails, but it limits you
from doing anything more. Adding attachments or sending HTML emails is very

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


30

difficult with mail(). However, with PHPMailer, you can do that with a single line of
code.

Error Sending in Multiple Languages

mail() restricts you from sending emails to very few compatible languages
and frameworks. Whereas the PHPMailer library enables you to send error
messages in more than 40 languages when message sending fails.

Headers and Dirty Code

Developers write dirty code such as escape characters, encoding, and code for
formatting. This is usually done while sending attachments via email in mail().
PHPMailer makes a developer’s life painless, as there is no need to create headers
in the same way as in mail() function.

How to Install PHPMailer Library?


You can install the PHPMailer library in your PHP project by running the following
command in Composer.

composer require phpmailer/phpmailer

Building Notification

PHP NOTES FOR MGSU EXAMS GORISH MITTAL

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy