UNIT4 PHP
UNIT4 PHP
UNIT-4
1
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.
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.
• 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.";
?>
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
Susscess.php
<?php
$fname=$_POST[fname];
$id=$_POST[custid];
?>
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.
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.
// start a session
session_start();
$_SESSION["session_variable_name"] = session_variable_value;
<?php
// start a session
session_start();
?>
<html>
<body>
</body>
</html>
<?php
session_start();
?>
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.
$_SESSION["session_variable_name"] = "new_value";
?>
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:
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.
Syntax:
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.
?>
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.
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')
// Expires in 30 days
setcookie("UserID", 007, strtotime('+30 days'));
?>
Syntax:
$_COOKIE["cookie_name"];
?>
?>
?>
When a cookie is deleted and we try to access it, the interpreter will raise an Undefined index
error.
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.
?>
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
The simplest regular expression is one that matches a single character inside the string. For
example - "g" inside the toggle or cage string.
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 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
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 .
$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
\S Non-whitespace character
Modifier ‘I’
PHP currently provides seven functions to search strings using Regular expression
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.
Syntax
int preg_match (string $pattern, string $subject, array $matches, int $flags, int $offset)
Parameters
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
Flags
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.
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. ?>
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
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.
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
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.
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:
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.
$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:
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';
// Display result
print_r($result);
?>
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 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.
✓ Let users contact you via email by providing a contact us form on the website that emails
✓ 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
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:
$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
$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)
parameters
Optional. Specifies an additional parameter to the send mail program
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
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";
</body>
</html>
SMTP
https://www.youtube.com/watch?v=RdNErie6dKU
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
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
difficult with mail(). However, with PHPMailer, you can do that with a single line of
code.
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.
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.
Building Notification